Ilya
Ilya

Reputation: 13487

Ruby hash encrypting

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?

Upvotes: 2

Views: 1845

Answers (3)

Teddy
Teddy

Reputation: 18572

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)

Upvotes: 0

nibbex
nibbex

Reputation: 361

Works fine for me, adding this last step gives me the original hash

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

Upvotes: 1

Vasfed
Vasfed

Reputation: 18504

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 = ...

Upvotes: 0

Related Questions