Lin*_*der 43 encryption ruby-on-rails
我刚才看到有可能在rails中解密和加密字符串而不包括任何库,但我找不到博客文章.
我希望能够加密和解密字符串而不包含任何内容.使用相同的密钥可以用于rails中的所有其他内容,例如签名的cookie.
有任何想法吗?
ger*_*tas 125
你的意思是这个?:ActiveSupport :: MessageEncryptor.以下是重用Rails 4应用程序秘密的方法:
crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base)
encrypted_data = crypt.encrypt_and_sign('my confidental data')
Run Code Online (Sandbox Code Playgroud)
加密数据可以解密:
decrypted_back = crypt.decrypt_and_verify(encrypted_data)
Run Code Online (Sandbox Code Playgroud)
以前Rails 3使用secret_token
配置选项和加密方法encrypt
decrypt
.
Rails 5 更新:
crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base[0..31])
encrypted_data = crypt.encrypt_and_sign('my confidental data')
Run Code Online (Sandbox Code Playgroud)
Rails 5.x 需要一个正好为 32 字节的键。
要使用更长的密钥验证先前签名的消息:
crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base[0..31], Rails.application.secrets.secret_key_base)
encrypted_data = crypt.encrypt_and_sign('my confidental data')
Run Code Online (Sandbox Code Playgroud)
如文档中所述
Rails 5要求密钥为32字节.
编辑到Rails 4回答适用于Rails 5:
key = SecureRandom.random_bytes(32)
crypt = ActiveSupport::MessageEncryptor.new(key)
encrypted_data = crypt.encrypt_and_sign('my confidental data')
Run Code Online (Sandbox Code Playgroud)
解密:
decrypted_back = crypt.decrypt_and_verify(encrypted_data)
Run Code Online (Sandbox Code Playgroud)