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

时间:2022-08-21 13:10:40

In a Rails 3.0 (Ruby 1.9.2) app I'm trying to encrypt some data using something like this:

在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

That will go into a UTF-8 database. My problem is that

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

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

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

How can I get an UTF-8 encrypted string?

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

2 个解决方案

#1


40  

The solution is to convert the ASCII-8BIT string to Base64 and then encode to UTF-8.

解决方案是将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')

Once persisted and retrieved from the database,

一旦持久化并从数据库中检索,

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

and finally decrypt it.

最后解密它。


PS: If you're curious:

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'

#2


0  

I believe your best bet is to use force_encoding found here.

我相信你最好的选择是在这里使用force_encoding。

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

> encrypted.force_encoding "utf-8"

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

#1


40  

The solution is to convert the ASCII-8BIT string to Base64 and then encode to UTF-8.

解决方案是将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')

Once persisted and retrieved from the database,

一旦持久化并从数据库中检索,

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

and finally decrypt it.

最后解密它。


PS: If you're curious:

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'

#2


0  

I believe your best bet is to use force_encoding found here.

我相信你最好的选择是在这里使用force_encoding。

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

> encrypted.force_encoding "utf-8"

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