0
votes

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

  • know what are those characters
  • cross reference the two results
  • use only one npm package (crypto)
1
Do not use mcrypt, it doesn't support PKCS5 padding. Additionally, I know it sounds shocking, but the reason you are getting an invalid key length error is because the key is of invalid length gasp. Your key is 8 bytes long, AES requires a minimum key size of 16 bytes. - Luke Joshua Park
@LukeJoshuaPark that key I received, and mcrypt gives a kind a correct result with my 8bytes key. - user3568719
If the key is literally the raw hex characters then why are you decoding it as hex in your first code excerpt...? - Luke Joshua Park
@LukeJoshuaPark because I am blind :) Thanks, it works now, and it gives the same result. What is good, but on the other hand I still have those ugly characters. - user3568719
Because you aren't using padding... - Luke Joshua Park

1 Answers

1
votes

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.