先放npm官方文档:www.npmjs.com/package/node-forge
在知道RSA加密的大致原理后,再往下看
使用例子
简单写个方法:
import forge from 'node-forge';
const encode64 = str => forge.util.encode64(str);
const encrypted = (text: string, publicKey: string, needFormatPem: boolean) => {
if (!publicKey) return text;
let curPublicKey = publicKey;
if (needFormatPem) {
curPublicKey = `-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`;
}
const publicKeyObj = forge.pki.publicKeyFromPem(curPublicKey);
return encode64(publicKeyObj.encrypt(text));
};
export default encrypted;
内容梳理:
1.初始化公钥、私钥对象
需要根据公钥的格式使用对应的生成方法
const pki = forge.pki;
var publicKey = pki.publicKeyFromPem(pem);
var pem = pki.publicKeyToPem(publicKey);
var publicKey = pki.publicKeyFromAsn1(subjectPublicKeyInfo);
var subjectPublicKeyInfo = pki.publicKeyToAsn1(publicKey);
同理,生成私钥需要对应的方法
var privateKey = pki.privateKeyFromPem(pem);
var pem = pki.privateKeyToPem(privateKey);
var privateKey = pki.privateKeyFromAsn1(rsaPrivateKey);
var rsaPrivateKey = pki.privateKeyToAsn1(privateKey);
2.使用公钥/私钥对象进行加密/解密
var encrypted = publicKey.encrypt(bytes);
var decrypted = privateKey.decrypt(encrypted);
加密解密的方法不仅只是一个入参,还有拓展功能,第二个参数用于指定RSA加密的标准
第二个参数为空时默认为 RSAES PKCS#1 v1.5标准
var encrypted = publicKey.encrypt(bytes, 'RSAES-PKCS1-V1_5');
var decrypted = privateKey.decrypt(encrypted, 'RSAES-PKCS1-V1_5');
var encrypted = publicKey.encrypt(bytes, 'RSA-OAEP');
var decrypted = privateKey.decrypt(encrypted, 'RSA-OAEP');
还有别的参数,可以去文档查看,链接见顶部。
|