AES encryption in Crypto Js and Rails gives different results

I am trying to encrypt text using AES-256-CBC with Crypto Js (client side) and OpenSSL in rails (server side), and they give me different results. This explains why I cannot decode the ciphertext on the server side and vice versa on the client side.

Here is how I do it:

Client Side (Crypto JS) - Edited

iv = CryptoJS.enc.Base64.parse("kT+uMuPwUk2LH4cFbK0GiA==") key = CryptoJS.enc.Hex.parse("6476b3f5ec6dcaddb637e9c9654aa687") encrypted_text = CryptoJS.AES.encrypt("test", key, {mode: CryptoJS.mode.CBC, formatter : Base64Formatter, iv : iv}) encrypted_text => "7Qu7/V7yXHt67wMOV0/1Tg==" 

Server Side (Rails OpenSSL) - Edited

 iv = Base64.decode64("kT+uMuPwUk2LH4cFbK0GiA==") key = "6476b3f5ec6dcaddb637e9c9654aa687" cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc') cipher.encrypt cipher.key = key cipher.iv = iv text = cipher.update("test") + cipher.final encrypted_text = Base64.strict_encode64(text) encrypted_text => "fHhNBuopuuthdq2SFvvgDw==" 

Does anyone know what I'm doing wrong? I'm just at a dead end.

Help is much appreciated ... thanks!

Floor

+4
source share
2 answers

In line:

 key = CryptoJS.enc.Hex.parse("abcdefghijklmnopqrstuvwxyz012345") 

The string "abcdefghijklmnopqrstuvwxyz012345" is not in the hexadecimal system. I would start with this.

+2
source

Based on documents, CryptoJS seems to select 128/192/256 based on the key size. This key, when analyzing from hexadecimal to binary, is 16 bytes, which means that it will encode using AES-128-CBC. Therefore, the choice of AES-256-CBC on the Ruby side is incorrect.

In addition, the key is not hex decoded on the ruby ​​side. With these changes, the code looks like this:

 iv = Base64.decode64("kT+uMuPwUk2LH4cFbK0GiA==") key = ["6476b3f5ec6dcaddb637e9c9654aa687"].pack("H*") cipher = OpenSSL::Cipher::Cipher.new('aes-128-cbc') cipher.encrypt cipher.key = key cipher.iv = iv text = cipher.update("test") + cipher.final encrypted_text = Base64.strict_encode64(text) 

And the output => "7Qu7/V7yXHt67wMOV0/1Tg==" . What we expect.

+1
source

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


All Articles