DES3 decryption in Ruby on Rails

encoding, encryption, openssl, ruby, ruby-on-rails

Solution

The documentation for OpenSSL::Cipher states:

Make sure to call `.encrypt` or `.decrypt` before using any of the following methods:

- [`key=`, `iv=`, `random_key`, `random_iv`, `pkcs5_keyivgen`]

In your specific case, omitting the call to `cipher.decrypt` causes a `bad decrypt` error, as you've seen.

The following example corrects that problem and exhibits the expected behavior:

require 'openssl'
require 'Base64'

# For testing purposes only!
message = 'MyTestString'
key = 'PasswordPasswordPassword'
iv = '12345678'

# Encrypt plaintext using Triple DES
cipher = OpenSSL::Cipher::Cipher.new("des3")
cipher.encrypt # Call this before setting key or iv
cipher.key = key
cipher.iv = iv
ciphertext = cipher.update(message)
ciphertext << cipher.final

puts "Encrypted \"#{message}\" with \"#{key}\" to:\n\"#{ciphertext}\"\n"

# Base64-encode the ciphertext
encodedCipherText = Base64.encode64(ciphertext)

# Base64-decode the ciphertext and decrypt it
cipher.decrypt
plaintext = cipher.update(Base64.decode64(encodedCipherText))
plaintext << cipher.final

# Print decrypted plaintext; should match original message
puts "Decrypted \"#{ciphertext}\" with \"#{key}\" to:\n\"#{plaintext}\"\n\n"

Problem

My RoR server receives a string, that was encrypted in C++ application using des3 with base64 encoding The cipher object is created so: ``` cipher = OpenSSL::Cipher::Cipher::new("des3") cipher.key = key_str cipher.iv = iv_str ``` key_str and iv_str: are string representations of key and initialization vector for encryption algorithm. They are the same for RoR and C++ application. The code on the RoR side is following: ``` result = "" result << cipher.update( Base64.decode64(message) ) result << cipher.final ``` After executing the last line of code, i get an exception ``` OpenSSL::CipherError (bad decrypt) ``` What is wrong here ? Any ideas ?

Original source