gpt4 book ai didi

javascript - 将 PHP mcrypt() 调用转换为 Node 的 mcrypt

转载 作者:太空宇宙 更新时间:2023-11-04 03:31:18 24 4
gpt4 key购买 nike

我正在尝试使用 Node 的 mycrypt 模块将旧 PHP 应用程序中的加密函数重新创建到新的 Node JS 应用程序中。

我的目标是确保在给定相同的原始字符串和盐的情况下,下面的 PHP 脚本会生成与 Node 脚本相同的加密值。

<小时/>

PHP

<?php
$string = 'This is my password';
$salt = 'sodiumChloride12';
$encrypted = base64_encode(
mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
$salt,
$string,
MCRYPT_MODE_ECB,
mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND)
)
);

echo "Encrypted: $encrypted\n";

它产生:

Encrypted: iOKEAxaE4vIeWXBem01gHr2wdof7ZO2dld3BuR9l3Nw=
<小时/>

JavaScript

var mcrypt = require('mcrypt');
var MCrypt = mcrypt.MCrypt;

// Set algorithm and mode
var rijndaelEcb = new MCrypt('rijndael-128', 'ecb');

// Set up salt and IV
var salt = 'sodiumChloride12';
var iv = rijndaelEcb.generateIv();
rijndaelEcb.open(salt, iv);

/** ENCRYPTION **/
var cipher = rijndaelEcb.encrypt('This is my password');
var cipherConcat = Buffer.concat([iv, cipher]).toString('base64');
console.log('Encrypted: ' + cipherConcat);

/** DECRYPTION **/
// Convert back from base64
var ivAndCipherText = new Buffer(cipherConcat, 'base64');

// Undo concat of IV
var ivSize = rijndaelEcb.getIvSize();
iv = new Buffer(ivSize);
var cipherText = new Buffer(ivAndCipherText.length - ivSize);
ivAndCipherText.copy(iv, 0, 0, ivSize);
ivAndCipherText.copy(cipherText, 0, ivSize);

var plaintext = rijndaelEcb.decrypt(cipherText).toString();
console.log('Decrypted: ' + plaintext);

Node 版本产生:

Encrypted: 834aJoVRxla/fGNACUAVFYjihAMWhOLyHllwXptNYB69sHaH+2TtnZXdwbkfZdzc
Decrypted: This is my password

基于它解密了原始短语的事实,我知道调用正在按预期工作,但加密的输出与 PHP 脚本中的不同。解密逻辑来自this answer ,但我更关心的是让加密以同样的方式工作。

我在 Node 中使用 IV 所做的事情与在 PHP 中是否不同?

我查看了this question ,但它使用 crypto 模块而不是我正在使用的 mcrypt 模块。

最佳答案

Am I doing something different with the IV in Node than in PHP?

嗯。代码说了什么?

MCRYPT_MODE_ECB,

var rijndaelEcb = new MCrypt('rijndael-128', 'ecb');

您正在使用ECB mode ,它不使用 IV。实际上,您正在浪费 CPU 周期来生成一个。即使您使用的是 CBC 模式,MCRYPT_RAND 在这里使用也是一个不好的常量。

var cipherConcat = Buffer.concat([iv, cipher]).toString('base64');

您正在将未使用的 IV 连接到密文中,并提示结果无效? PHP 代码仅返回 cipher(在 Node.js 等效术语中),而不是 ivcipher 的串联。

<小时/>

更重要的是,这里存在一些严重的密码学缺陷需要解决,首先是如上所述的 ECB 模式:

  1. Do not encrypt passwords ,使用密码散列算法。 There's a huge difference .
  2. 如果您要加密,use authenticated encryption .
  3. Don't use mcrypt .
  4. 不要deploy home-grown crypto protocols into production or encourage other developers to do the same .

建议步骤:

  1. 使用 PHP 解密您的数据,然后存储密码 properly .
  2. 如果您出于任何其他目的需要加密,use a high-level cryptography library ,如 libsodium。

关于javascript - 将 PHP mcrypt() 调用转换为 Node 的 mcrypt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37289128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com