I'm considering using the attr_encrypted gem for field-level encryption in a Rails app. How do I generate an encryption key for use with this gem?
Update:
The documentation for Encryptor, which is the underlying encryption used by attr_encrypted, states the following (under Usage | Basic):
secret_key = Digest::SHA256.hexdigest('a secret key')
encrypted_value = Encryptor.encrypt('some string to encrypt', :key => secret_key)
I would guess that a secret key
can be any arbitrary-length random string and the call to hexdigest
will compute an appropriate fixed-length string from it. Is this the recommended way to do it?
The key is just a string, any string will do, you just want to keep it away from people who are not allowed to see the plaintext data. You could simply generate a key using SecureRandom.base64
. That would make it practically unguessable by brute force, with very little effort from you.
The interesting thing here is key management. Your options with this gem appear to be:
Hard-code the key into the application. This prevents "accidental" reading of sensitive data by e.g. a DBA or support engineer, but it is not secure from anyone who knows how the gem works, if they can access both the source code and the database.
Reference a named method which will determine the key. This is more interesting, but beware: Putting the key into the database does not really add much security. Someone who can access the database and code can do much the same as if the value were hard-coded.
You can improve things slightly, or at least get the development team separated from the encrypted data, by having the application read at least part of the key from a location that developers (or perhaps just the majority of developers) cannot access in production. Going beyond that is harder, at least with this gem as-is, because the application will need to run with access to the encrypt/decrypt keys.
Whether or not this is good enough depends on why you are encrypting the data in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With