从php加密时,文件解密在Node中不起作用

时间:2017-07-27 09:53:52

标签: encryption openssl cryptography aes cryptojs

终于解决了,你可以在下面看到我的答案 从php加密时,文件解密在Node中不起作用 PHP代码加密

<?php

$key = "f9036c20bdb656106fd176d260878c63";
$iv = "7152201381f54b46";




exec('openssl enc -aes-256-cbc   -K '.$key.' -iv '.$iv.' -in a.txt -out b.txt');



exec('openssl enc -d -aes-256-cbc  -K '.$key.' -iv '.$iv.' -in b.txt -out outr.txt');
?>

解密在PHP中运行良好

解密的JS代码以下方法都不起作用

var CryptoJS = require('crypto-js');
var key ="f9036c20bdb656106fd176d260878c63";

var iv1 = "7152201381f54b46";


var text = require('fs').readFileSync('../b.txt');

var bytes  = CryptoJS.AES.decrypt(text,key,{iv:iv1, mode: CryptoJS.mode.CBC,padding: CryptoJS.pad.Pkcs7 });

console.log(CryptoJS.enc.Utf8.stringify(bytes));
require('fs').writeFile('../out.txt', CryptoJS.enc.Utf8.stringify(bytes), function (err) {
        if (err) {
            return console.error(err);
        }
    });

也尝试加密没有运气

    const crypto = require('crypto');
const fs = require('fs');

var secret = "f9036c20bdb656106fd176d260878c63";
const buf_secret = Buffer.from(secret);

var iv = "7152201381f54b46";
const buf_iv = Buffer.from(iv);


const decipher = crypto.createCipheriv('aes-256-cbc', buf_secret, buf_iv);
decipher.setAutoPadding(true);
fs.readFile('../b.txt', function (err, data) {
    if (err) {
        return console.log(err);
    }
    const buf_data = Buffer.from(data);
    console.log(buf_data);
    let decrypted = decipher.update(buf_data, 'utf8');
    decrypted += decipher.final('utf8');
    console.log(decrypted);

});

我确定有一些填充问题,有人可以指出它有什么错误吗?

1 个答案:

答案 0 :(得分:1)

它已经解决了。问题是PHP openssl接受密钥和iv作为十六进制。对于openssl256,密钥长度应为64,iv长度应为32,但在PHP密钥长度为32,iv长度为16,这是openssl128,因此PHP添加尾随零。在JS中添加尾随零并将其视为十六进制后,其工作正常。

const crypto = require('crypto');
const fs = require('fs');
const key_size = 64;
const iv_size = 32;

var secret = "f9036c20bdb656106fd176d260878c63";
secret = pad(secret,key_size,"0"); //pad with trailing zeros

const buf_secret = Buffer.from(secret,'hex');

var iv = "7152201381f54b46";
iv = pad(iv,iv_size,"0");//pad with trailing zeros

const buf_iv = Buffer.from(iv,'hex');



const decipher = crypto.createDecipheriv('aes-256-cbc', buf_secret, buf_iv);
decipher.setAutoPadding(true);

const input = fs.createReadStream('../b.txt');
const output = fs.createWriteStream('../decrypted.txt');

input.pipe(decipher).pipe(output);

//content if you want instead of direct writing
//fs.readFile('../b.txt', function (err, data) {
//    if (err) {
//        return console.log(err);
//    }
//    const buf_data = Buffer.from(data);
//    console.log(buf_data);
//    let decrypted = decipher.update(buf_data, 'utf8');
//    decrypted += decipher.final('utf8');
//    console.log(decrypted);
//
//});

//for padding trailing zeros
function pad(value, width, padchar) {

    while (value.length < width) {
        value += padchar;
    }
    return value;
}