将 AES 256 cbc 加密和解密方法从 PHP 转换为节点 js

问题描述 投票:0回答:0

我在我的项目中预先编写了AES 256 cbc加密和解密方法,现在我正在将几个模块升级到Node.js。这是 PHP 方法:

function encrypt($data)
    {
        $first_key = base64_decode(FIRSTKEY);
        $second_key = base64_decode(SECONDKEY);

        $method = "aes-256-cbc";
        $iv_length = openssl_cipher_iv_length($method);
        $iv = openssl_random_pseudo_bytes($iv_length);

        $first_encrypted = openssl_encrypt($data, $method, $first_key, OPENSSL_RAW_DATA, $iv);
        $second_encrypted = hash_hmac('sha512', $first_encrypted, $second_key, TRUE);

        $output = base64_encode($iv.$second_encrypted.$first_encrypted);
        return $output;
    }
function decrypt($input)
    {
        $first_key = base64_decode(FIRSTKEY);
        $second_key = base64_decode(SECONDKEY);
        $mix = base64_decode($input);
                
        $method = "aes-256-cbc";
        $iv_length = openssl_cipher_iv_length($method);
                    
        $iv = substr($mix, 0, $iv_length);
        $second_encrypted = substr($mix, $iv_length, 64);
        $first_encrypted = substr($mix, $iv_length+64);
                    
        $data = openssl_decrypt($first_encrypted, $method, $first_key, OPENSSL_RAW_DATA, $iv);
        $second_encrypted_new = hash_hmac('sha512', $first_encrypted, $second_key, true);
        if ( (strlen($input)>0) && hash_equals($second_encrypted, $second_encrypted_new) ){
            return $data;
        }
            
        return false;
    }

请在这里帮助我将这些方法转换为 Node.js。我是 Node.

的新手
php node.js aes
© www.soinside.com 2019 - 2024. All rights reserved.