【问题标题】:How to translate this encryption function from PHP to Javascript如何将此加密功能从 PHP 转换为 Javascript
【发布时间】:2019-11-10 07:19:47
【问题描述】:

我正在将 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('=','')

【问题讨论】:

  • SO 不是转码服务,而是认真的。如果safe_b64encode()(一个非普通的 PHP 函数)是 PHP 过程的一部分,您是否认为如果我们要为您进行转换,也需要向我们展示这一点

标签: javascript php encryption translate mcrypt


【解决方案1】:

我想你快到了,你只需要使用相同的算法,你使用的是 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 中的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 2019-10-25
    • 2015-09-23
    • 1970-01-01
    相关资源
    最近更新 更多