Ruby hash encrypting

时间:2016-04-04 17:33:43

标签: ruby-on-rails ruby encryption activesupport

I trying to encrypt and decrypt hash in Ruby by using ActiveSupport::MessageEncryptor. Firstly I create and serialize hash:

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

Then I crypt serialized hash:

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"

Problem is that I can not decrypt it:

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'

However, sometimes it works. How can I fix it?

3 个答案:

答案 0 :(得分:1)

对我来说很好,添加最后一步给我原始哈希

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

答案 1 :(得分:0)

You used a different variable name compared to the name you used as the argument in the last command. The following command works for me:

crypt.decrypt_and_verify(crypted_string)

答案 2 :(得分:0)

Make sure to use the same key/salt. If you're trying that in console, the problem is most probably in variable name encrypted_string vs crypted_string = ...