需要帮助使用加密将加密河豚 php 转换为 Nodejs



您好,我需要帮助使用加密模块将我的PHP加密函数转换为Nodejs:

此代码已在工作

// Constructor params
$this->algorithm = "blowfish";
$this->token = "3SzzaErRzj0#RuGr@JTkh[MO0AMIW*d!Sul/CEL!*rPnq$oOEgYaH}fNw{jw1b/DyLUdL])+JOMES@Z7MIRI>(p*nY{yl%h]4ylx";
public function decrypt($string)
{
$key = hash('sha256', $this->token);
list($encrypted_data, $iv) = explode('::', base64_decode($string), 2);
return openssl_decrypt($encrypted_data, $this->algorithm, $key, 0, $iv);
}
public function encrypt($string)
{
$output = false;
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->algorithm));
// hash
$key = hash('sha256', $this->token);
$output = openssl_encrypt($string, $this->algorithm, $key, 0, $iv);
return base64_encode($output . '::' . $iv);
}

nodejs 中的代码,我使破译工作正常,但密码不起作用

const crypto = require('crypto');
const decipher = async (alg, key, value) => {
const hash = crypto.createHash('sha256');
hash.update(key);
let token = hash.digest('hex');
let buff = new Buffer.from(value, 'base64');
let [encrypted, iv] = buff.toString('ascii').split('::', 2);
iv = new Buffer.from(iv);
const decipher = crypto.createDecipheriv(alg, token, iv);
let decrypted = await decipher.update(encrypted, 'base64', 'ascii');
decrypted += decipher.final('ascii');
return decrypted;
}
/* this one is not working */
const cipher = async (alg, key, value) => {

let iv = crypto.randomBytes(8);
var sha256 = crypto.createHash('sha256');
sha256.update(key);
var newkey = sha256.digest('base64');
var encryptor = await crypto.createCipheriv(alg, newkey, iv);
encrypted = encryptor.update(value, 'utf8', 'base64') + encryptor.final('base64');
var final = encrypted + "::" +iv;
let buf = Buffer.from(final);
let encodedData = buf.toString('base64');
return encodedData;
}

任何帮助帮助我完成工作,我很感激

必须在 NodeJS 代码的cipher方法中进行以下更改:

  • 密钥必须编码为十六进制:

    var newkey = sha256.digest('hex'); 
    
  • IV 必须作为二进制字符串附加:

    var final = encrypted + "::" + iv.toString('binary');
    
  • 并且数据必须解析为二进制字符串:

    let buf = Buffer.from(final, 'binary');
    

通过这些更改,NodeJS 代码中的cipher方法与 PHP 代码中的encrypt方法兼容。

cipher方法使用UTF8编码,decipher方法使用ASCII编码,因此只有ASCII可编码的文本才能正确解密。若要消除对 ASCII 编码的限制,需要在decipher方法中进行以下更改:

  • 二进制字符串的编码必须使用binary而不是ascii完成:

    let [encrypted, iv] = buff.toString('binary').split('::', 2);
    iv = new Buffer.from(iv, 'binary');
    
  • 并且输出编码必须utf8而不是ascii

    let decrypted =  decipher.update(encrypted, 'base64', 'utf8');
    decrypted += decipher.final('utf8');
    

通过这些更改,NodeJS和PHP代码是兼容的。另请注意:

  • 实际上,所应用的 NodeJS 函数都不是异步的,因此使用async/await并不是真正必要的。
  • 可以省略Buffer.from之前的new
  • 该算法用blowfish指定,对应于bf-cbc并表示 CBC 模式下的河豚。
  • 使用 SHA256 生成 32 字节密钥,并以十六进制字符串(64 字节/字符)返回,因此使用 64 字节密钥。对于 Blowfish,此处定义了 56 字节的最大密钥长度。
  • SHA256用作密钥派生功能,更安全的是例如PBKDF2(至少对于弱密码),在这里。
  • 由分隔符分隔的 IV 附加到 Base64 编码的密文
  • 中,生成的数据是 Base64 编码的(即密文因此被 Base64 编码两次)。通常 IV 和密文(按此顺序)在二进制级别连接,生成的数据采用 Base64 编码。分隔符不是必需的,因为IV的长度对应于块大小,因此是已知的。

最新更新