Muhammad Faisal Iqbal
Muhammad Faisal Iqbal

Reputation: 1836

rails openssl different results of encryption from code and terminal

when I try to encrypt data from terminal like

echo -n "TestData" | openssl enc -aes-256-cbc -a -K C81E728D9D4C2F636F067F89CC14862C65990ABE58735B91B6B8798E8CE45F22 -iv D342F9C6310F6B21E97AB38595BD8CAA

than the Base64 encoded result I receive is

VJwJBTtVntJvRGkD24S4wg==

But when I try same thing with rails using exactly same key and initialization vector

    cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
    cipher.encrypt
    cipher.key = "C81E728D9D4C2F636F067F89CC14862C65990ABE58735B91B6B8798E8CE45F22"
    cipher.iv = "D342F9C6310F6B21E97AB38595BD8CAA"
    encrypted_data = cipher.update("TestData")
    encrypted_data << cipher.final
    Base64.strict_encode64(encrypted_data)

than I receive entirely different Base64 encoded result

qavpNrU7llgauAyyEZz/bw==

can someone point that what I missed?

Upvotes: 1

Views: 492

Answers (2)

Reinier Torenbeek
Reinier Torenbeek

Reputation: 17363

You provide the key and iv attributes as hex strings, but the expected format is raw bytes. Converting them to binary yields the expected result, with the following script:

require 'openssl'
require 'base64'

def hex_to_bin(s)
 s.scan(/../).map { |x| x.hex.chr }.join
end

cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.encrypt
cipher.key = hex_to_bin("C81E728D9D4C2F636F067F89CC14862C65990ABE58735B91B6B8798E8CE45F22")
cipher.iv = hex_to_bin("D342F9C6310F6B21E97AB38595BD8CAA")
encrypted_data = cipher.update("TestData")
encrypted_data << cipher.final
puts Base64.strict_encode64(encrypted_data)

(Source for the hex_to_bin function: To Hex and Back (With Ruby)).

Calling it encrypt.rb, this is the result of running it:

$ ruby encrypt.rb 
encrypt.rb:8: warning: constant OpenSSL::Cipher::Cipher is deprecated
VJwJBTtVntJvRGkD24S4wg==

To get rid of the "is deprecated" warning I had to replace the deprecated class OpenSSL::Cipher::Cipher with OpenSSL::Cipher.

Upvotes: 2

zaph
zaph

Reputation: 112857

The key is to short, 98304A2480DDC0FA354278936DAC2A0D7D9074650AD6 is an invalid key size, AES keys are 128, 192 or 256 bits in length (16, 24 or 32 bytes). Since it appears the key should be 256-bits (32-bytes) the missing key bytes will be either garbage or possibly nulls, key extension is undefined. Thus different results.

Assuming null padding and PKCS#7 padding for the first case the result is correct: AESCALC

The second example is filling out the key in some other manor.

The solution is to use a full length key.

Upvotes: 0

Related Questions