示例代码
优质
小牛编辑
137浏览
2023-12-01
crypto 加密实例代码
"use strict";
//引用crypto模块
const crypto = require("crypto");
//-------------MD5 可以任意多次调用update(),update()默认字符串编码是UTF-8
const hash = crypto.createHash("md5");
hash.update("hello, world!");
console.log(hash.digest("hex"));
//--------------SHA1
const sha1 = crypto.createHash("sha1");
sha1.update("hello,world!");
console.log(sha1.digest("hex"));
//-------------SHA256
const sha256 = crypto.createHash("sha256");
sha256.update("hello,world!");
console.log(sha256.digest("hex"));
//------------SHA512
const sha512 = crypto.createHash("sha512");
sha512.update("hello,world!");
console.log(sha512.digest("hex"));
//------------Hmac
const hmac = crypto.createHash("sha256","secret-key");
hmac.update("hello world!");
console.log(hmac.digest("hex"));
//-----------AES
function aesEncrypt(data, key) {
const cipher = crypto.createCipher("aes192", key);
var crypted = cipher.update(data, "utf8", "hex");
crypted += cipher.final("hex");
return crypted;
}
function aesDecrypt(encrypted, key) {
const decipher = crypto.createDecipher("aes192", key);
var decrypted = decipher.update(encrypted, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
}
var data = "hello this a secret message!";
var key = "password";
var encrypted = aesEncrypt(data,key);
var decrypted = aesDecrypt(encrypted, key);
console.log("plain text:" + data);
console.log("Encrypted text:" +encrypted);
console.log(("Decrypted text:" + decrypted));
//------------------diffie-hellman
var ming = crypto.createDiffieHellman(512);
var ming_keys = ming.generateKeys();
var prime = ming.getPrime();
var generator = ming.getGenerator();
console.log("Prime:" + prime.toString("hex"));
console.log("Generator:" + generator.toString("hex") );
var hong = crypto.createDiffieHellman(prime, generator);
var hong_keys = hong.generateKeys();
var ming_secret = ming.computeSecret(hong_keys);
var hong_secret = hong.computeSecret(ming_keys);
console.log("Secret of xiao ming:" + ming_secret.toString("hex"));
console.log("Secret of xiao hong:" + hong_secret.toString("hex"));
//----------RSA
const fs = require("fs");
//从文件加载key
function loadKey(file) {
return fs.readFileSync(file,"utf8");
};
let prvKey = loadKey("./rsa-prv.pem");
let pubKey = loadKey("./rsa-pub.pem");
let message = "hello world!";
//使用私钥加密公钥解密
let enc_by_prv = crypto.privateEncrypt(prvKey,Buffer.from(message,"utf8"));
console.log("encrypted by private key:" + enc_by_prv.toString("hex"));
let dec_by_pub = crypto.publicDecrypt(pubKey, enc_by_prv);
console.log("decrypted by public key:" + dec_by_pub.toString("utf8"));
//使用公钥进行加密私钥解密
let enc_by_pub = crypto.publicEncrypt(pubKey,Buffer.from(message,"utf8"));
console.log("encrypted by public key:" + enc_by_pub.toString("hex"));
let dec_by_prv = crypto.privateDecrypt(prvKey,enc_by_pub);
console.log("decrypted by private key:" + dec_by_prv.toString("utf8"));