How to encrypt data in a UTF-8 string using OpenSSL::Cipher? How to encrypt data in a UTF-8 string using OpenSSL::Cipher? ruby ruby

How to encrypt data in a UTF-8 string using OpenSSL::Cipher?


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

cipher = OpenSSL::Cipher.new 'aes-256-cbc'cipher.encryptcipher.key = cipher.random_keycipher.iv = cipher.random_ivencrypted = cipher.update 'most secret data in the world'encrypted << cipher.finalencoded = 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:

cipher = OpenSSL::Cipher.new 'aes-256-cbc'cipher.decryptcipher.key = random_keycipher.iv = random_ivdecrypted = cipher.update encodeddecrypted << cipher.final> decrypted => 'most secret data in the world'


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

> encrypted.encoding  => #<Encoding:ASCII-8BIT>> encrypted.force_encoding "utf-8"> encrypted.encoding  => #<Encoding:UTF-8>