Abhineet Kumar
Abhineet Kumar

Reputation: 13

Encryption & decryption in node aes-256-cbc goes Error

i need to encrypt my data with given key using aes-256-cbc algorithm but i am getting error "RangeError: Invalid key length" in node while using crypto library.

Php code results "w8mBJyHzQ3yJlkSvAX8t3qy9GVaUvBiOBAPFDXOzFMQ=" with

key = "9v6ZyFBzNYoP2Un8H5cZq5FeBwxL6itqNZsm7lisGBQ="
text = "Hello, Help me with this"
output is "w8mBJyHzQ3yJlkSvAX8t3qy9GVaUvBiOBAPFDXOzFMQ="
// Encryption Function
function encrypt($text, $key, $size = 16)
{
    $pad = $size - (strlen($text) % $size);
    $padtext = $text . str_repeat(chr($pad), $pad);
    $crypt = openssl_encrypt($padtext, "AES-256-CBC", base64_decode($key), OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, '0123456789abcdef');
    return base64_encode($crypt);
}
// Decryption Function
function decrypt($crypt, $key)
{
    $padtext = openssl_decrypt(base64_decode($crypt), "AES-256-CBC", base64_decode($key), OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, '0123456789abcdef');
    $pad = ord($padtext[strlen($padtext) - 1]);
    if ($pad > strlen($padtext)) {
        return false;
    }

    if (strspn($padtext, $padtext[strlen($padtext) - 1], strlen($padtext) - $pad) != $pad) {
        $text = "Error";
    }
    $text = substr($padtext, 0, -1 * $pad);
    return $text;
}

And node code results "RangeError: Invalid key length"

key = "9v6ZyFBzNYoP2Un8H5cZq5FeBwxL6itqNZsm7lisGBQ="
data = "Hello, Help me with this"
output is "RangeError: Invalid key length"
function encrypt(data, key) {
    try {
        const cipher = crypto.createCipheriv("aes-256-cbc", atob(key), '0123456789abcdef');
        return cipher.update(data, 'utf-8', 'base64') + cipher.final('base64');
        // let encryption = Buffer.concat([cipher.update(Buffer.from(data, "utf8")), cipher.final()]);
        // return encryption.toString("base64");
    } catch (error) {
        console.log(error);
        return error
    }

}
function decrypt(enc_data, key) {
    try {
        const decipher = crypto.createDecipheriv("aes-256-cbc", atob(key), '0123456789abcdef');
        return (decipher.update(enc_data, 'base64', 'utf-8') + decipher.final('utf-8'));
        // const decryption = Buffer.concat([decipher.update(Buffer.from(enc_data, "base64")), decipher.final()]);
        // return decryption.toString("utf8");
    } catch (error) {
        console.log(error);
        return error
    }
}

Upvotes: 0

Views: 750

Answers (1)

刘海华
刘海华

Reputation: 11

let cipher = crypto.createCipheriv("aes-256-cbc", Buffer.from(keyStr,'base64'), Buffer.from(ivStr));

Upvotes: 0

Related Questions