node.jsencryptionaesecb

node.js Decipher AES 128 ECB


I try to decipher a base64 format token with AES 128-ecb on node.

key: ed9d26Z0JES0X52Q (changed some character, but a length is correct)

token: O4girrZ2YeLSE1sZ4FSIvp3Edm1GiwBLHmvDIEYCf+xkvbxP6EfYjy+PEB2kaYe0606EyPmlCC0iExVRq9e3Iw==

  decodeToken(token) {
    var key = new Buffer(exchangeKey, 'hex')
    var encrypted = new Buffer(token, 'base64')
    decipher = crypto.createDecipheriv("aes-128-ecb", key, '')
    decipher.setAutoPadding(false)
    result = decipher.update(encrypted).toString();
    return result;
  }

gives:

crypto.js:239 this._handle.initiv(cipher, toBuf(key), toBuf(iv)); ^

Error: Invalid key length at Error (native) at new Decipheriv (crypto.js:239:16) at Object.Decipheriv (crypto.js:236:12)

After some searching I found this:

// https://github.com/nodejs/node-v0.x-archive/issues/4744#issuecomment-25460050
var aesEcb = new MCrypt('rijndael-128', 'ecb')
aesEcb.open(exchangeKey);
var ciphertext = new Buffer(token, 'base64');
var plaintext = aesEcb.decrypt(ciphertext).toString();
return plaintext

what gives back

f9712fa5-da4a-49fe-b81f-b48d8cfabf91275RAODW24RS

what looks like the expected format and length, but notice the wired characters at the end.

I could use this solution too (and trim the extra characters), but I want to


Solution

  • You're decoding the key as hex when you intend to use the individual hex characters as the key bytes. Don't do that. You've also got padding disabled. Enable padding to remove the weird characters.