0

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()?
calyxofheld
  • 1,538
  • 3
  • 24
  • 62

1 Answers1

1

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.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • is there any benefit to storing the key on the model? it seems like it would be a security vulnerability. i'm at a loss for why the docs suggest it. – calyxofheld Sep 24 '19 at 02:48
  • 1
    If you are wondering about the examples hey do not _suggest_ it; they are showing it as an option (e.g. if you want to allow your users to set the key for all encryption related to their data). Similarly, the rest of the examples are not recommendations, but merely explanations of the syntax — you can replace a literal with an environment variable. – Amadan Sep 24 '19 at 04:16