Search code examples
node.jscryptographyaes

Is there a way to create an AES cipher from a hashed key-secret?


Having lost the plaintext secret, but having the hashed key, it's posible to encript and decript in openssl like so (keys and iv are not the actual ones):

Input:

printf "ciphertext" | base64 -d | openssl enc -aes-256-cbc -d -nosalt -K "0000000000000000000000000000000000000000000000000000000000000000" -iv "00"

Output:

"plaintext"

Now, to be able to do this in a NodeJs application, openssl is called as child_process. As you can guess, spawning openssl calls is not very performant.

To be able to do it in node crypto, the plaintext "secret" is needed in creating the keys.

Is there a way yo generate the cipher from the hashed key?

I have tried doing it like so with no succes.

var crypto=require('crypto')
var iv = Buffer.alloc(16, 0);
var key = '0000000000000000000000000000000000000000000000000000000000000000'
var cipher=crypto.createDecipher('aes-256-cbc', newBuffer(key).toString('binary'), new Buffer('0000000000000000', 'hex').toString('binary'));
var enc = cipher.update("ciphertext", 'base64', 'utf8')
enc += cipher.final('utf8')
console.log(enc);

Output:

internal/crypto/cipher.js:164
  const ret = this._handle.final();
                           ^
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt

Solution

  • Try

    new Buffer('0000000000000000000000000000000000000000000000000000000000000000', 'hex')
    

    for the key and and

    new Buffer('00000000000000000000000000000000', 'hex')
    

    for the IV. Currently you are encoding to a binary string representation of the bytes, instead of (just) decoding the hexadecimal values to 32 bytes and 16 bytes respectively.

    To use this you should use createDecipheriv as createDecipher will still generate the key using the password.