开发者

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

I'm using the foll开发者_如何学Goowing 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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜