正如CodesInChaos所述,带有 SHA256 的 HMAC 只能用于散列值,这只是单向行程。如果您希望能够加密/解密,则必须使用密码,例如aes
or des
。
关于如何加密/解密的示例:
const crypto = require("crypto");
// key and iv
var key = crypto.createHash("sha256").update("OMGCAT!", "ascii").digest();
var iv = "1234567890123456";
// this is the string we want to encrypt/decrypt
var secret = "ermagherd";
console.log("Initial: %s", secret);
// create a aes256 cipher based on our password
var cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
// update the cipher with our secret string
cipher.update(secret, "ascii");
// save the encryption as base64-encoded
var encrypted = cipher.final("base64");
console.log("Encrypted: %s", encrypted);
// create a aes267 decipher based on our password
var decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
// update the decipher with our encrypted string
decipher.update(encrypted, "base64");
console.log("Decrypted: %s", decipher.final("ascii"));
注意:您必须将密码/解密保存到他们自己的变量中,并确保不要.final
在.update
.
如果您想知道系统上可用的密码,请使用以下命令:
openssl list-cipher-algorithm