I saw a while ago the possibility to decrypt and encrypt strings in rails without including any library, but I can't find the blog post.
I want to be able to encrypt and decrypt strings without including anything. Using the same key has for the everything else in rails, signed cookies for example.
Any ideas?
Using encryption in Rails 7 It works by declaring which attributes should be encrypted and seamlessly encrypting and decrypting them when needed. The encryption layer sits between the database and the application. The application will access unencrypted data, but the database will store it encrypted.
You mean this one?: ActiveSupport::MessageEncryptor. Here is the way to reuse Rails 5+ on Ruby 2.4+ application's secret:
crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base[0..31]) encrypted_data = crypt.encrypt_and_sign('my confidental data')
And encrypted data can be decrypted with:
decrypted_back = crypt.decrypt_and_verify(encrypted_data)
The above example uses first 32 characters of Rails app secret as an encryption and signing key, because the default MessageEncryptor
cipher aes-256-gcm
requires exactly 256 bit key. By convention, during the app creation, Rails generates a secret as a string of 128 hex digits.
Important! Ruby 2.4 upgrade note
Before Ruby 2.4 and Rails 5 there was no key size restriction and it was popular to just past full secret into the encryptor initializer:
# pre-2.4 crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base)
Internally the encryption algorithm (AES256GCM provided by OpenSSL) was using only 32 characters from the key, however the signing algorithm (SHA1) was consuming all 128 characters.
Therefore, while upgrading an app from pre-2.4 Ruby, and where the app previously encrypted the data with an unrestricted key size, the MessageEncryptor
must get a full secret in the second parameter to avoid ActiveSupport::MessageVerifier::InvalidSignature
on the legacy data decryption:
# post-2.4 upgrade crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base[0..31], Rails.application.secrets.secret_key_base)
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