Reputation: 161
I am trying to encrypt text using AES-256-CBC with Crypto Js (on the client side) and OpenSSL in rails (on the server side) and they are giving me different results. This explains why I cannot decode the encrypted text on the server side and vice-versa on the client side.
Here is how I am doing it:
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=="
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 have any idea as to what I am doing wrong? I am just stumped at this point.
Help is much appreciated..thanks!
Paul
Upvotes: 5
Views: 3523
Reputation: 14089
Based on the docs CryptoJS appears to select 128/192/256 based on size of key. That key, when parsed from hex back to binary, is 16 bytes, which would mean it would encode using AES-128-CBC. The selection of AES-256-CBC on the Ruby side is therefore incorrect.
Additionally, the key is not being hex decoded on the ruby side. With these changes the code looks like:
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 is => "7Qu7/V7yXHt67wMOV0/1Tg=="
. Just what we expect.
Upvotes: 2
Reputation: 5654
In the line:
key = CryptoJS.enc.Hex.parse("abcdefghijklmnopqrstuvwxyz012345")
The string "abcdefghijklmnopqrstuvwxyz012345" is not in hexadecimal notation. I'd start with that.
Upvotes: 2