我正在尝试编写一个等效于php opensssl解密的脚本,这是我尝试过的,
var crypto = require('crypto');
var ct = 'jKscKK6E/aQ50hAck0YZkA==';
var key = 'gxmo872UXsU6u41t2zXzRNcU9H1cfuNvu/fnI/q1vIc=';
var iv = 'sd+XF3bRJ/WMT9woe8LOkQ==';
var decipher = crypto.createDecipheriv('aes-128-cbc', new Buffer(key, 'base64'), new Buffer(iv, 'base64'));
var content = decipher.update(new Buffer(ct, 'base64'), "binary", "utf8");
content += decipher.final("utf8");
console.log("Decrypted: " + content);
但是我得到了这个错误,
错误:密钥长度无效
这是我要尝试的php代码
openssl_decrypt(base64_decode($ct), 'aes-128-cbc', base64_decode($key), OPENSSL_RAW_DATA, base64_decode($iv))
答案 0 :(得分:0)
我的意图是编写一个等效于Codeiginiter默认解密的脚本,所以我从代码的底部开始,那就是我发现上述错误的地方,最后我能够编写整个脚本,希望这可能是对某人有帮助。
let crypto = require("crypto");
let secret = 'xxxxxxxxxxxxxxxxxxxx';
// ikm is initial keying material
var hkdf = function (hashAlg, salt, ikm) {
this.hashAlg = hashAlg;
// create the hash alg to see if it exists and get its length
var hash = crypto.createHash(this.hashAlg);
this.hashLength = hash.digest().length;
this.salt = salt || new Buffer(this.hashLength).fill(0).toString();
this.ikm = ikm;
// now we compute the PRK
var hmac = crypto.createHmac(this.hashAlg, this.salt);
hmac.update(this.ikm);
this.prk = hmac.digest();
};
hkdf.prototype = {
derive: function(info, size, cb) {
var prev = new Buffer(0);
var output;
var buffers = [];
var num_blocks = Math.ceil(size / this.hashLength);
info = new Buffer(info);
for (var i=0; i<num_blocks; i++) {
var hmac = crypto.createHmac(this.hashAlg, this.prk);
hmac.update(prev);
hmac.update(info);
hmac.update(new Buffer([i + 1]));
prev = hmac.digest();
buffers.push(prev);
}
output = Buffer.concat(buffers, size);
return output;
}
};
function decrypt(code)
{
if (typeof code !== 'string')
return false;
code = code.substring(128);
var buff = new Buffer(code, 'base64');
var iv = buff.slice(0, 16);
var encyptedText = buff.slice(16).toString('base64');
var _hkdf = new hkdf('sha512', null, secret);
var derive_key = _hkdf.derive('encryption', secret.length);
var key = derive_key.slice(0, 16);
var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
var result = decipher.update(encyptedText, 'base64');
result += decipher.final();
return result.replace(/[']/g, '');
}