【问题标题】:PHP mcrypt_decrypt in NodeJSNodeJS 中的 PHP mcrypt_decrypt
【发布时间】:2017-09-18 06:22:15
【问题描述】:

在过去的 3 个小时里,我一直在寻找互联网,我终于决定提出这个问题。是否可以在 NodeJS 中解密通过 PHP 加密的 base64 文本字符串。

我已经尝试了很多步骤来分解它,但我所做的一切似乎都不起作用。

我的旧 PHP 方法确实有效。

class EncryptionSystem{
    private $iv;
    public $iv_size;
    public $key;

    public function __construct(){
        $this->iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
        $this->iv = mcrypt_create_iv($this->iv_size, MCRYPT_RAND);
        $this->key = "SUPER SECURE STRING";
    }

    public function crypt_data($data = null){
        $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key, $data, MCRYPT_MODE_CBC, $this->iv);
        $ciphertext = $this->iv.$ciphertext;
        return $ciphertext;
    }

    public function decrypt_data($data){
        $ciphertext_dec = base64_decode($data);
        $iv_dec = substr($ciphertext_dec, 0, $this->iv_size);
        $ciphertext_dec = substr($ciphertext_dec, $this->iv_size);
        $plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);
        return array($iv_dec,$plaintext_dec);
    }
}

我在 NodeJS 上使用 Mcrypt 的尝试(不起作用)

var post64 = results[0].post;
var de64 = Buffer.from(post64, 'base64');
var desCBC = new MCrypt("rijndael-128","cbc");

var iv = de64.slice(0,desCBC.getIvSize());
var ciphered = de64.slice(desCBC.getIvSize());

console.log("IV:",iv);
console.log(iv.length);
console.log("IV SIZE:",desCBC.getIvSize());
desCBC.open(new Buffer(password.slice(0,desCBC.getIvSize(),"utf8")),new Buffer(iv,"utf8"));

var plaintext = desCBC.decrypt(new Buffer(ciphered,"utf8"));
console.log(plaintext.toString());

使用 Crypto 的另一次尝试(也不起作用)

console.log("Base64",post64);
console.log("RAW",de64.toString("binary"));
var iv = de64.toString("binary").slice(0,16);
var ciphered = de64.toString("binary").slice(16);

console.log("IV:",iv);
console.log(iv.length);
console.log("Ciphered:",ciphered);

var decipher = crypto.createDecipheriv(algorithm,password,new Buffer(iv,'hex'));

【问题讨论】:

    标签: php node.js mcrypt rijndael node-crypto


    【解决方案1】:

    尝试使用模块crypto-js。它对我来说很好用!

    aesDecryptDef(cipherData) {
        let CryptoJS = require("crypto-js"),
            key = CryptoJS.enc.Utf8.parse(this.AES_KEY),
            iv = CryptoJS.enc.Utf8.parse(this.AES_IV),
            decrypted = CryptoJS.AES.decrypt(cipherData, key, {
                iv: iv
            });
        return decrypted.toString(CryptoJS.enc.Utf8);
    };
    

    【讨论】:

    • 看到问题是我有一个随机生成器 IV 用于保存以提高安全性的每个数据。 IV 存储在加密数据的开头。
    猜你喜欢
    • 2023-03-05
    • 2013-10-23
    • 2010-10-12
    • 2012-11-10
    • 2014-07-27
    • 1970-01-01
    • 2014-09-25
    • 2012-01-03
    • 1970-01-01
    相关资源
    最近更新 更多