如何将此加密功能从PHP转换为Javascript

时间:2019-06-28 10:16:21

标签: javascript php encryption translate mcrypt

我正在将Web应用程序从PHP迁移到基于JS的框架。该应用程序使用mcrypt_encrypt和base64进行加密。我尝试在Javascript中使用mcrypt模块,但结果不一样。

原始的PHP函数如下所示

function safe_b64encode($string) {
    $data = base64_encode($string);
    $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
    return $data;
}

function encrypt($value) {
    $text = $value;
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, ENCRYPTION_KEY, $text, MCRYPT_MODE_ECB, $iv);
    return trim(safe_b64encode($crypttext));
}

我的JS版本看起来像这样

const MCrypt = require('mcrypt').MCrypt

const rijndael128Ecb = new MCrypt('rijndael-128', 'ecb')
const iv = rijndael128Ecb.generateIv()

rijndael128Ecb.validateKeySize(false)
rijndael128Ecb.open(ENCRYPTION_KEY, iv)

let cipherText = rijndael128Ecb.encrypt('sometext')
cipherText = Buffer.concat([iv, cipherText]).toString('base64')
cipherText = cipherText.replace('+','-').replace('/','_').replace('=','')

1 个答案:

答案 0 :(得分:2)

我认为您已经快到了,您只需要使用相同的算法,就使用了128位Rijndael,我在Node.js中切换到256位,它现在可以正常工作。

// Surely this key is uncrackable...
const ENCRYPTION_KEY = 'abcdefghijklmnop';
const MCrypt = require('mcrypt').MCrypt;

function encryptRijndael256(plainText, encryptionKey) {

    const rijndael256Ecb = new MCrypt('rijndael-256', 'ecb');
    const iv = rijndael256Ecb.generateIv();

    rijndael256Ecb.validateKeySize(false);
    rijndael256Ecb.open(encryptionKey, iv);

    let cipherText = rijndael256Ecb.encrypt(plainText);
    cipherText = cipherText.toString('base64');
    cipherText = cipherText.replace('+','-').replace('/','_').replace('=','')

    return cipherText;
}

const plainText = 'sometext';
const cipherText = encryptRijndael256(plainText, ENCRYPTION_KEY); 
console.log("Cipher text: ", cipherText);

我正在使用以下密文(具有琐碎和不安全的!)密钥:

k3ZQ8AbnxhuO8TW1VciCsNtvSrpbOxlieaWX9qwQcr8

同时显示PHP和JavaScript中的结果。