我试图用ActiveSupport::MessageEncryptor加密和解密ruby中的hash。首先我创建并序列化散列:

hash = { a: 1, b: 2 }
serialized_hash = Marshal.dump(hash) #=> "\x04\b{\a:\x06ai\x06:\x06bi\a"

然后我加密序列化散列:
salt  = SecureRandom.random_bytes(64)
key   = ActiveSupport::KeyGenerator.new('password').generate_key(salt) # => "\x89\xE0\x156\xAC..."
crypt = ActiveSupport::MessageEncryptor.new(key)
crypted_string = crypt.encrypt_and_sign(serialized_hash)
#=> "NHhLdDMwQS9MMkwwK1RFZjMyOFJNRXRkZ2VJY1o3aGtwaC9Wb0wvSnhmVT0tLW1nWTNqUElPWEdhMCsrMHI5R2FST2c9PQ==--01150a6eae1691887ace4164019fea2bd353f092"

问题是我无法解密它:
crypt.decrypt_and_verify(crypted_string)
ActiveSupport::MessageVerifier::InvalidSignature: ActiveSupport::MessageVerifier::InvalidSignature
from /home/user/.rvm/rubies/ruby-2.2.3/lib/ruby/gems/2.2.0/gems/activesupport-4.2.6/lib/active_support/message_verifier.rb:49:in `verify'

然而,有时它是有效的我怎样才能修好它?

最佳答案

对我来说很好,加上最后一步就得到了原始散列

result = crypt.decrypt_and_verify(crypted_string)
Marshal.load(result)

10-02 21:23