简体   繁体   中英

ruby OpenSSL RSA character encoding

I'm building an API in Rails which decrypts one of the POST parameters using RSA. When testing encryption and decryption internally in ruby as seen below, the string literal encrypted (which seems to be UTF8 encoded) does not come out as UTF-8 after decryption. Why is it ASCII-8BIT? What's the recommended way to handle this? Should I call force_encoding("UTF-8") on the decrypted string and say in the API specification that all strings should be UTF8 before encrypting?

@rsa = OpenSSL::PKey::RSA.new(1024)

original = "hej på dig\n"

puts original.encoding.name # => "UTF-8"

ciphertext = @rsa.public_encrypt(original)

decrypted = @rsa.private_decrypt(ciphertext)

puts decrypted.encoding.name # => "ASCII-8BIT"

assert_equal original, decrypted
#expected: hej på dig
#actual: hej p\xC3\xA5 dig

I'm using Ruby 2.1.3 on OSX Yosemite with Rails 4.1.5.

Yep, you got it. You should explicitly turn the UTF-8 to bytes before encryption and back again after decryption. The underlying library simply handles unsigned chars, which are the byte equivalent for C.

If I read the Ruby API's correctly you should be able to do this by using:

string.force_encoding(Encoding::UTF_8)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM