Encryption with Alphanumeric output

What if you want to generate reasonably short alphanumeric user activation codes without having to store anything in a DB (so in this case generating random user codes won’t do) ? Why would someone need this? Think about an application where you want to print activation cards and sell them to your customers. The customer then login to your website, put the activation code that is printed on its card… and bingo : they are activated.
So, how to do this? With encryption, of course.
The thing is that most encryption algorithms will generate ciphers with non-friendly characters, like : Òèç`{&[ùỲgǛ… so bad for readability. It seems complicated at first but finally one solution turns out to be fairly simple :
Step #1

sudo gem install crypt

Step #2

blowfish = Crypt::Blowfish.new(SOME_KEY)
crypted_but_readable = blowfish.encrypt_block("12345678").unpack("H*")

Step #3

  crypted_block = params[:some_crypted_but_readable_block].to_s
  if crypted_block.length == 16
    blowfish = Crypt::Blowfish.new(THE_SAME_KEY)
    decrypted_block = blowfish.decrypt_block(crypted_block.to_a.pack("H*"))
    #do something with decrypted block
  end

The Blowfish algorithm takes 8-bytes blocks only… so you have to take that into account when you generate your keys. The unpack(“H*) and pack(“H*”) parts are the most important. It simply encodes/decodes the block in hexadecimal. So, here we are, you have a readable & decryptable 16-chars cipher that looks like : 9048bb8f56eddd47. You can even display the codes into chunks of 4 characters and it gives you the following friendly code : 9048-bb8f-56ed-dd47
Tip: Associate to each code a SHA-1 hashed password (which is the result of activation code + some salt) and you have a pretty safe account activation procedure that doesn’t pollute your database.

5 thoughts on “Encryption with Alphanumeric output

  1. Thanks for writing it. It took us so long to figure this one out and I hope that it will be the first result on Google when someone is searching for something similar to this. It will save him a lot of time…

  2. Thanks very much, François. Dan was right: Not even two months later, and this entry was at the top of a search for this problem.
    For anyone else who wanders by, the use of unpack works equally well with Ruby’s built-in OpenSSL library. (That’s likely obvious, but just in case.)

  3. The author is known by historical past of the of Georgene Evens.
    Her husband and her thought we would reside in Oklahoma and she doesn’t begin changing it again. Debt collecting has been my profession for skill and I assume I’ll put it back anytime then. The
    favorite hobby for him and his kids is caving but he
    is struggling in order to time get rid of. If you for you to find out more the look at my website: http://nexhost.net/

Leave a Reply

Your email address will not be published. Required fields are marked *