24

在 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 加密字符串?

4

2 回答 2

44

解决方法是将 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'
于 2012-06-15T03:00:40.007 回答
0

我相信你最好的选择是使用force_encodingfound here

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

> encrypted.force_encoding "utf-8"

> encrypted.encoding
  => #<Encoding:UTF-8>
于 2012-06-15T00:25:42.483 回答