Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将此加密函数从PHP转换为Javascript_Javascript_Php_Encryption_Translate_Mcrypt - Fatal编程技术网

如何将此加密函数从PHP转换为Javascript

如何将此加密函数从PHP转换为Javascript,javascript,php,encryption,translate,mcrypt,Javascript,Php,Encryption,Translate,Mcrypt,我正在将一个web应用程序从PHP迁移到一个基于JS的框架。该应用程序使用mcrypt\u encrypt和base64进行加密。我尝试在Javascript中使用mcrypt模块,但没有得到相同的结果 原始PHP函数如下所示 函数安全\u b64encode($string){ $data=base64_编码($string); $data=str_replace(数组(“+”、“/”、“=”)、数组(“-”、“”、”)、$data); 返回$data; } 函数加密($value){ $te

我正在将一个web应用程序从PHP迁移到一个基于JS的框架。该应用程序使用
mcrypt\u encrypt
和base64进行加密。我尝试在Javascript中使用
mcrypt
模块,但没有得到相同的结果

原始PHP函数如下所示

函数安全\u b64encode($string){
$data=base64_编码($string);
$data=str_replace(数组(“+”、“/”、“=”)、数组(“-”、“”、”)、$data);
返回$data;
}
函数加密($value){
$text=$value;
$iv_size=mcrypt_get_iv_size(mcrypt_RIJNDAEL_256,mcrypt_MODE_ECB);
$iv=mcrypt\u create\u iv($iv\u大小,mcrypt\u兰德);
$crypttext=mcrypt_encrypt(mcrypt_RIJNDAEL_256,加密密钥,$text,mcrypt_模式,$ECB,$iv);
返回修剪(安全编码($crypttext));
}
我的JS版本看起来像这样

常量MCrypt=require('MCrypt')。MCrypt const rijndael128Ecb=新的MCrypt('rijndael-128','ecb') const iv=rijndael128Ecb.generateIv() rijndael128Ecb.validateKeySize(false) rijndael128Ecb.open(加密密钥,iv) 让cipherText=rijndael128Ecb.encrypt('sometext') cipherText=Buffer.concat([iv,cipherText]).toString('base64')) cipherText=cipherText.replace('+','-')。replace('/','''.'')。replace('=','')
我想你差不多做到了,你只需要使用相同的算法,你使用的是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的结果。

SO不是一个代码转换服务,而是一个严肃的服务。如果
safe\u b64encode()
(一个非普通的PHP函数)是PHP过程的一部分,那么如果我们要为您进行转换,您不认为需要向我们展示这一点吗