Search code examples
ruby-on-railsrubyattr-encrypted

SecureRandom.hex() vs SecureRandom.random_bytes() for key generation in Rails with attr_encrypted


The docs for attr_encrypted say that I must store the results of key = SecureRandom.random_bytes(32) on the model. I think that it would be more secure to have this key stored as an ENV variable. I am also accustomed to running rake secret for my ENV variables. rake secret relies on SecureRandom.hex().

I'm wondering two things:

  1. Am I right to assume that the encryption key should be stored as an ENV variable?
  2. Is there any difference in key encryption strength between either of the two SecureRandom methods? hex() vs random_bytes()?

Solution

  • SecureRandom#hex is defined here as:

    def hex(n=nil)
      random_bytes(n).unpack("H*")[0]
    end
    

    so the data generated by them is exactly the same, just the format differs.

    As for encryption keys, it's up to you and the way you host your app. If it's on a server you control, an uncommitted config file is fine (though environment variable approach still works, obviously). If you are hosting on e.g. Heroku, an environment variable is the way to go.