Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby OpenSSL vs Linux openssl

I have a difficulty reconciling Ruby's OpenSSL library with the standard Linux command line openssl.

What I'm trying to do here is encrypt the string mysecretstring with the password foobar but first hashing the password using sha256 (mimicking the code in the aescrypt gem).

Here is what I do in IRB:

2.0.0-p353 :041 > aes = OpenSSL::Cipher::Cipher.new("AES-256-CBC")
 => #<OpenSSL::Cipher::Cipher:0x000000026b8d50> 
2.0.0-p353 :042 > aes.encrypt
 => #<OpenSSL::Cipher::Cipher:0x000000026b8d50> 
2.0.0-p353 :043 > aes.key=OpenSSL::Digest::SHA256.new('foobar').digest
 => "\xC3\xAB\x8F\xF17 \xE8\xAD\x90G\xDD9Fk<\x89t\xE5\x92\xC2\xFA8=J9`qL\xAE\xF0\xC4\xF2" 
2.0.0-p353 :044 > Base64.encode64(aes.update('mysecretstring')+aes.final)
 => "305V0Kbklj/HoBSK4ferhA==\n" 
2.0.0-p353 :045 > 

So far so good. Now I want to see how this matches what I can do with openssl directly in the linux command line.

[(master)]$ echo -n "foobar" | openssl dgst -sha256 -c
(stdin)= c3:ab:8f:f1:37:20:e8:ad:90:47:dd:39:46:6b:3c:89:74:e5:92:c2:fa:38:3d:4a:39:60:71:4c:ae:f0:c4:f2
[(master)]$ echo -n "mysecretstring" | openssl enc -e -aes-256-cbc -a
enter aes-256-cbc encryption password:
Verifying - enter aes-256-cbc encryption password:
U2FsdGVkX18EOcTrTMNQuCRnstUe6oY9b5RLuTOFcNo=
[(master)]$ 

where in the last two steps I pasted the string c3:ab:8f:f1:37:20:e8:ad:90:47:dd:39:46:6b:3c:89:74:e5:92:c2:fa:38:3d:4a:39:60:71:4c:ae:f0:c4:f2 that I got by hashing the password 'foobar' in the first step.

Why am I not getting the same answer, and more importantly, what do I need to do in the linux cmd to mimic what I get from Ruby?

like image 737
Assaf Shomer Avatar asked Feb 15 '26 08:02

Assaf Shomer


1 Answers

You need to use the -K option in your openssl line. Then you can provide the hexadecimal key. Otherwise OpenSSL uses it's own key derivation mechanism to derive a key from the password. When supplying -K you should also supply -iv. In this case, to be compatible, the IV should consist of 16 bytes set to zero.

So try the following line:

echo -n "mysecretstring" | openssl enc -e -aes-256-cbc -a -K c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2 -iv 00000000000000000000000000000000
like image 65
Maarten Bodewes Avatar answered Feb 17 '26 06:02

Maarten Bodewes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!