Simple Encryption in Ruby without external gems

2019-01-17 07:06发布

I need a simple encryption for some text strings. I want to create coupon codes and make them look cool so subsequently created code should look very different. (And besides looking cool, it shouldn't be easy to guess a code.) But I want to be able to decrypt them again. So the algorithm must be reversible.

I alread tried some stuff with moving bits around so they look kind of random already. But two subsequent codes (just one bit different) of course look very similar.

Any suggestions? I would like to do that without using external gems.

Philip

8条回答
走好不送
2楼-- · 2019-01-17 08:07

I guess the simplest way is a * x + b (mod 2^n)

Note that you need to calculate the inverse of a on 2^n, you can to that with Wolfram Alpha using extended GCD.

查看更多
Bombasti
3楼-- · 2019-01-17 08:11

For basic encoding/decode purpose I guess ruby's inbuilt Base64 library can be handy:

2.2.1 :001 > require 'base64'
 => true 
2.2.1 :002 > str = "abc@example.com"
 => "abc@example.com" 
2.2.1 :003 > Base64.encode64(str)
 => "YWJjQGV4YW1wbGUuY29t\n" 

It also has the urlsafe version methods in case the encoded strings are to be used in urls.

Reference: http://ruby-doc.org/stdlib-2.3.0/libdoc/base64/rdoc/Base64.html

查看更多
登录 后发表回答