Ruby-on-rails 使用 Rails 加密、解密

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5492377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:48:31  来源:igfitidea点击:

Encrypt, decrypt using Rails

ruby-on-railsencryption

提问by Linus Oleander

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.

不久前我看到了在不包含任何库的情况下在 rails 中解密和加密字符串的可能性,但我找不到博客文章。

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.

我希望能够在不包含任何内容的情况下加密和解密字符串。对 rails 中的其他所有内容使用相同的密钥,例如签名 cookie。

Any ideas?

有任何想法吗?

回答by gertas

You mean this one?: ActiveSupport::MessageEncryptor. Here is the way to reuse Rails 4 application's secret:

你是说这个?:ActiveSupport::MessageEncryptor。下面是重用 Rails 4 应用程序的秘密的方法:

crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base)
encrypted_data = crypt.encrypt_and_sign('my confidental data')

And encrypted data can be decrypted with:

加密数据可以通过以下方式解密:

decrypted_back = crypt.decrypt_and_verify(encrypted_data)

Previously Rails 3 was using secret_tokenconfiguration option and encryptor methods were encryptdecrypt.

以前 Rails 3 使用secret_token配置选项,加密方法是encryptdecrypt.

回答by guero64

Rails 5 requires that the key be 32 bytes.

Rails 5 要求密钥为 32 字节。

Edit to Rails 4 answer that works for Rails 5:

编辑适用于 Rails 5 的 Rails 4 答案:

 key = SecureRandom.random_bytes(32)
 crypt = ActiveSupport::MessageEncryptor.new(key) 
 encrypted_data = crypt.encrypt_and_sign('my confidental data')

Decrypt:

解密:

 decrypted_back = crypt.decrypt_and_verify(encrypted_data)

回答by estani

Rails 5 update:

Rails 5 更新:

crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base[0..31])
encrypted_data = crypt.encrypt_and_sign('my confidental data')

Rails 5.x Needs a key of exactly 32 bytes.

Rails 5.x 需要一个正好为 32 字节的键。

To verify a previously signed message with a longer key:

要使用更长的密钥验证先前签名的消息:

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')

as described in the docu

文档中所述

and the discussion on this change

以及关于这个变化讨论