user715697
user715697

Reputation: 887

Encryptor and MySQL, saving key to the database / encoding?

I'm using the following methods to encrypt a data-key:

data_key      = ActiveSupport::SecureRandom.random_number(99999999)
secret_key    = Digest::SHA256.hexdigest(params[:user][:password])
encrypted_key = Encryptor.encrypt(data_key.to_s, :key => secret_key)

encrypted_key will then equal, for example:

"%\x807\x1F\xFE.N\xEC\x85\x04\xEA\xED(\xD6\xFC\xC9"

If I try and save this in my MySQL database using:

Key.create(:encrypted_key => encrypted_key)

The only value that is save into the :encrypted_key column is:

%

I have tried another one:

"2T`E\xBDP\x12\x81\x00U\x92\xFE\x1A\xDC=\xA4"

Which stores in the column:

2T`E

So I think it's the \ breaking it.

Upvotes: 0

Views: 399

Answers (1)

Paul Russell
Paul Russell

Reputation: 4747

I think MySQL can probably only store ASCII characters. The '\x???' characters are unicode characters.

I would suggest Base64 encoding the key before you store it:

data_key      = ActiveSupport::SecureRandom.random_number(99999999)
secret_key    = Digest::SHA256.hexdigest(params[:user][:password])
encrypted_key = Encryptor.encrypt(data_key.to_s, :key => secret_key)
encoded_key   = Base64.encode64(encrypted_key)
Key.create(:encrypted_key => encoded_key)

This will encode all the non-ASCII characters into plain ASCII.

When you read the key from the database, you'll need to decode it before you decrypt it using `Base64.decode64

Upvotes: 2

Related Questions