如何使用OpenSSL :: Cipher加密UTF-8字符串中的数据?

时间:2012-06-14 23:18:18

标签: ruby-on-rails ruby utf-8 openssl aes

在Rails 3.0(Ruby 1.9.2)应用程序中,我正在尝试使用以下内容加密某些数据:

cipher = OpenSSL::Cipher.new 'aes-256-cbc'
cipher.encrypt
cipher.key = cipher.random_key
cipher.iv = cipher.random_iv

encrypted = cipher.update 'most secret data in the world'
encrypted << cipher.final

这将进入UTF-8数据库。我的问题是

> encrypted.encoding
 => #<Encoding:ASCII-8BIT>

> encrypted.encode 'utf-8'
Encoding::UndefinedConversionError: "\xF7" from ASCII-8BIT to UTF-8

如何获取UTF-8加密字符串?

2 个答案:

答案 0 :(得分:42)

解决方案是将ASCII-8BIT字符串转换为Base64,然后编码为UTF-8。

cipher = OpenSSL::Cipher.new 'aes-256-cbc'
cipher.encrypt
cipher.key = cipher.random_key
cipher.iv = cipher.random_iv

encrypted = cipher.update 'most secret data in the world'
encrypted << cipher.final

encoded = Base64.encode64(encrypted).encode('utf-8')

从数据库中保留并检索后,

decoded = Base64.decode64 encoded.encode('ascii-8bit')

最后解密。


PS:如果你很好奇:

cipher = OpenSSL::Cipher.new 'aes-256-cbc'
cipher.decrypt
cipher.key = random_key
cipher.iv = random_iv

decrypted = cipher.update encoded
decrypted << cipher.final

> decrypted
 => 'most secret data in the world'

答案 1 :(得分:0)

我认为最好的办法是使用force_encoding找到here

> encrypted.encoding
  => #<Encoding:ASCII-8BIT>

> encrypted.force_encoding "utf-8"

> encrypted.encoding
  => #<Encoding:UTF-8>