DES3 Decryption in Ruby on Rails

My RoR server receives a string that has been encrypted in a C ++ application using des3 base64 encoded

The encryption object is created as follows:

cipher = OpenSSL::Cipher::Cipher::new("des3")
cipher.key = key_str
cipher.iv =  iv_str

key_str and iv_str: are string representations of the key and initialization vector for the encryption algorithm. They are the same for RoR and C ++ applications.

The code on the RoR side is as follows:

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?

+3
source share
2 answers

The documentation for OpenSSL :: Cipher states:

.encrypt .decrypt :

  • [key=, iv=, random_key, random_iv, pkcs5_keyivgen]

cipher.decrypt bad decrypt, .

:

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"
+14
gem install encryptor

Ruby OpenSSL .

require 'encryptor'
Base64.decode64(message).decrypt(:algorithm => 'des', :key => key, :iv => iv)
+1

Source: https://habr.com/ru/post/1728063/


All Articles