Reputation: 19
I've been working on decrypting a few strings, and I've gotten them decrypted in Ruby (that's where they were originally encrypted). In Ruby, this is the method I'm calling to decrypt:
Using https://rubygems.org/gems/aes
def decrypt(str)
AES.decrypt(str, ENV["AES_KEY"])
end
In Node, this is what I've tried:
const CryptoJS = require('crypto-js');
const decryptedBytes = CryptoJS.AES.decrypt(secret, key);
const decryptedMessage = decryptedBytes.toString(CryptoJS.enc.Utf8);
But no luck using that — my result is always equal to an empty String. I'm probably missing something very small or stupid, but any suggestions or ideas are appreciated.
Upvotes: 1
Views: 1765
Reputation: 94038
The key in the Ruby code is the hexadecimal encoding of the bytes, so you need to decode it first. Then you should not use the decrypt
mode that just uses the secret
and key
parameters but also specify the key and IV as WordArray
:
For the key, when you pass a string, it's treated as a passphrase and used to derive an actual key and IV. Or you can pass a
WordArray
that represents the actual key. If you pass the actual key, you must also pass the actual IV.
Now the IV is prefixed to the ciphertext as base 64, separated by a dollar sign.
The ciphertext is also base 64 encoded, so you need to decode that first too. There are encoder functions in the library to help you with that:
So in the end you should be doing something similar to this:
CryptoJS.AES.decrypt(
CryptoJS.enc.Base64.parse(ciphertext),
CryptoJS.enc.Hex.parse(keyHex),
{ iv: CryptoJS.enc.Base64.parse(ivHex) }).toString(CryptoJS.enc.Utf8);
Upvotes: 3