Generating access keys in Ruby

This is a somewhat obscure but very efficient way to generate access keys. Look ma, no loops!

Array.new(16) { rand(256) }.pack('C*').unpack('H*').first

This will generate a 32-length key, like b3512f4972d314da94380e1a70e6814a.

This may look strange unless you’ve used Array.new, Array#pack, and String#unpack many times in the past. In the gaming world, I tended to deal with binary data on a regular basis, so pack and unpack became commonly-used weapons in my repertoire. They allow you to operate on binary data – pack creates binary data (stored in a regular string) from an array of Ruby objects, and unpack takes binary data and creates Ruby objects in an array. If you think about it, you are dealing with binary data here: you’re creating a random 128-bit (16-byte) key which you want in hex-format, so using pack and unpack do make sense. The parameters (C* and H*, in this case), are formats which indicate how to process the data.

Very cool cats may want to create more-compact Base64 keys. Be aware that Base64 is case sensitive:

[ Array.new(16) { rand(256) }.pack('C*') ].pack('m').chop

This generates keys like Gv5CJ68ptOZKVRvAFdzGpg==.