我正在使用当前的解决方案从Node.js加密文本并从iOS应用解密。 https://stackoverflow.com/a/27893935/2977578
可以使用Node.js进行加密,但是CryptoJS速度很慢。我试图移植此代码以使用Node.js中的内置crypto module来提高速度,但我不是这些功能的专家。是否可以仅使用内置的加密模块使此代码正常工作?
var password = "...";
var salt = "...";
var iv64 = "...";
var hash = CryptoJS.SHA256(salt);
var key = CryptoJS.PBKDF2(password, hash, { keySize: 256/32, iterations: 1000 });
var iv = CryptoJS.enc.Base64.parse(iv64);
var encrypted = CryptoJS.AES.encrypt(message, key, { iv: iv });
return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
答案 0 :(得分:1)
我已经使用内置的Node.js加密模块实现了这种加密逻辑,还使用了crypto-js函数对相同的纯文本进行了加密,并对它们进行了解码以确保结果一致:
const CryptoJS = require('crypto-js');
const crypto = require("crypto");
function encrypt_cryptojs(message, password, iv64, salt) {
var hash = CryptoJS.SHA256(salt);
var key = CryptoJS.PBKDF2(password, hash, { keySize: 256/32, iterations: 1000 });
var iv = CryptoJS.enc.Base64.parse(iv64);
var encrypted = CryptoJS.AES.encrypt(message, key, { iv: iv });
return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
}
// Use built-in crypto module.
function encrypt(message, password, iv64, salt) {
const iv = Buffer.from(iv64, 'base64');
const hash = crypto.createHash('sha256').update(salt, 'utf8').digest()
const key = crypto.pbkdf2Sync(password, hash, 1000, 32, null);
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
let encrypted = cipher.update(message, 'utf8', 'base64')
encrypted += cipher.final('base64');
return encrypted;
}
function decrypt(messagebase64, password, iv64) {
const iv = Buffer.from(iv64, 'base64');
const hash = crypto.createHash('sha256').update(salt, 'utf8').digest()
const key = crypto.pbkdf2Sync(password, hash, 1000, 32, null);
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
let decrypted = decipher.update(messagebase64, 'base64');
decrypted += decipher.final();
return decrypted;
}
const plaintext = "If you prick us do we not bleed? If you tickle us do we not laugh";
const salt = "some salt";
const password = crypto.scryptSync("some password", salt, 16).toString("base64");
const iv64 = "XxbSho8OZacvQwXC6S5RQw==";
console.log("Ciphertext (crypto js):", encrypt_cryptojs(plaintext, password, iv64, salt));
console.log("Ciphertext (built-in crypto module):", encrypt(plaintext, password, iv64, salt));
console.log("Decrypted (crypto js):", decrypt(encrypt_cryptojs(plaintext, password, iv64, salt), password, iv64));
console.log("Decrypted (built-in crypto module):", decrypt(encrypt(plaintext, password, iv64, salt), password, iv64));