Saim
Saim

Reputation: 2523

Ruby/Rails: How to get same encrypted value every time we encrypt a particular string

Does ActiveSupport::MessageEncryptor support deterministic encryption so that we get the same encrypted value every time we encrypt a particular string? If not, are there any other Ruby libs that support deterministic encryption?

My goal is to get same encrypted value every time I encrypt a string and I should be able to decrypt it to original value as well.

Thanks.

Upvotes: 6

Views: 2055

Answers (3)

khaled_gomaa
khaled_gomaa

Reputation: 3412

I did not get why ActiveSupport:MessageEncryptor didn't work. Here is another way to do it.

require 'bcrypt'

encrypted_password = BCrypt::Engine.hash_secret('password@!2#4', 'ADD SALT HERE')

you can also use it like this:

class User
  SALT = 'GENERATE A STATIC SALT HERE AND KEEP IT SECURE'.freeze
  include BCrypt

  def password=(given_password)
    @encrypted_password = Engine.hash_secret(given_password, SALT)
  end
end

For the full documentation please check their repo

PS: using a static salt for all users for authentication is a bad idea.

Upvotes: 4

Tobias
Tobias

Reputation: 4653

You get different crypts because ActiveSupport::MessageEncryptor uses OpenSSL for encryption which requires an iv by default to prevent attackers from inferring relationships between segments of the encrypted message. I would highly recommend you to not mess around with that because you open ways for attackers to infer the encryption key.

However if you still want to do that take a look into the OpenSSL documentation of ruby. There should be a way to encrypt without vector.

Because it's a high security risk I don't add code to the answer to protect others from unnecessary loop holes.

Upvotes: 8

Greg
Greg

Reputation: 6648

Of course: one just need to use the same key to get the same encryption

x = ActiveSupport::MessageEncryptor.new('12345678901234567890123456789012').encrypt_and_sign('foo')
=> "bXJmRUczdjVXRFdLTitUcmkvRnk1UT09LS0vb2ZYdDRybGdWbmNXMUI1VDNnQzVBPT0=--13232bbe31d966f7d1df3aaa6fcc1cdc9eea60a1"
ActiveSupport::MessageEncryptor.new('12345678901234567890123456789012').decrypt_and_verify(x)
=> "foo"

It's hard to tell why you get different results since you didn't post any code...

Upvotes: -1

Related Questions