gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:29:38 36 4
gpt4 key购买 nike

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

最佳答案

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

关于ruby-on-rails - 如何使用 OpenSSL::Cipher 加密 UTF-8 字符串中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11042657/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com