1.什么是公钥加密私钥解密
简单一点来说一般加密解密都用的是同一个秘钥或者根本不用,而这里采用的是加密用一个秘钥,解密用另一个秘钥且能解密成功.这就属于不对称加密解密算法的一种了.
2.公钥秘钥的生成
由于这种加密方案,公钥秘钥是成对的,所以需要一些工具生成
利用 openssl 生成公钥私钥
生成公钥: openssl genrsa -out rsa_private_key.pem 1024
生成私钥: openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
3.具体就直接贴代码吧,都是直接掉用 crypto 里的方法,只是写法上需要注意点
const crypto = require('crypto')
const fs = require('fs')
const publicKey = fs.readFileSync('./openssl/rsa_public_key.pem').toString('ascii');
const privateKey = fs.readFileSync('./openssl/rsa_private_key.pem').toString('ascii');
console.log(publicKey)
console.log(privateKey)
const data = "alex";
console.log("content: ", data)
//公钥加密
const encodeData = crypto.publicEncrypt(publicKey, Buffer.from(data)).toString('base64');
console.log("encode: ", encodeData)
//私钥解密
const decodeData = crypto.privateDecrypt(privateKey, Buffer.from(encodeData.toString('base64'), 'base64'));
console.log("decode: ", decodeData.toString())
4.贴运行结果
—–BEGIN PUBLIC KEY—–
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/rzb20kypDANTLSMU30PeoWwP
ZVltVZC3tm6Nh5jlqmldB4hez02ojg+qOfSxvi1SNvlij3rNSKhMnJOofvBlj8/H
nSNX25EBlhC0/8vSkiHuePxGG04oCXvsWTNMJ2W9U54rno0IM2KDrFP5UZDxR8ft
jGOK3tJnuJO2TUQhawIDAQAB
—–END PUBLIC KEY—–
—–BEGIN RSA PRIVATE KEY—–
MIICXAIBAAKBgQC/rzb20kypDANTLSMU30PeoWwPZVltVZC3tm6Nh5jlqmldB4he
z02ojg+qOfSxvi1SNvlij3rNSKhMnJOofvBlj8/HnSNX25EBlhC0/8vSkiHuePxG
G04oCXvsWTNMJ2W9U54rno0IM2KDrFP5UZDxR8ftjGOK3tJnuJO2TUQhawIDAQAB
AoGADpPMokir+88mEZVFLbks+Clehm02t9HiB5agIbNGNXEYQjLodA1f4omrN07h
BQNpfu8fWBeBR0tXQTxHHnFI5s6vNs8Y8jZu22hNJlI5B3Q2b4P1IgJfVzLK9qqv
958i++SOj3d0gpCeUXnDBZhyuK/FA82vKKDwj/j3Gm4zcgECQQDfkuXPcknDiZkK
5wXF3l7KDkEDMFLo3Rvzl0gklUJ1qxi4oKqMluDR/ynfAcL+DjXMzE0+sQjhHkau
/uiHxYlhAkEA23xKrGuLCzxSZb2vQi3hOgI6R/JE/pjTRQmMfj3D4n5+afciQDDP
l5Vf9i5+4UKSQs499MmbDUHZDIFQ/eYiSwJAWdYPHeJQnY/GvUjDWxTVhd9gZEWg
qw1d0+2wAXMwd1O+5UE6BrABuqALVR7CGY/gMmDNkSlV5g9iW6L2EMhhQQJAYRTt
Aq7e5a1c1Nu99YvNn5b0qHYkxmhaqqK6new8BKbmy4AgijwM1oOf2oheXszPXPVU
uj2ic464rqtUY7mzWQJBALRpxw3qroCNSw9OcgNpunSD+os9DVHTi32EQ4SW6lSR
ve6eLn43rqXO/C40priPf/7iQ6h1JJAD9usSt5FhGp4=
—–END RSA PRIVATE KEY—–
content: alex
encode: FHwyQV5vt6XdMc6Lv50wyvpv1asfUAZuRxVh7Nn7hiHUJeKnSLxOrE+Hy2tig8pK6WO4fMq1Xvs0GrxlmNL5+5tb2MG0qyOg0v4qf5Yzo1u2GYQT1PROrWFjh/kNZgMiCfqW7aAeLWv8s6ntOg8kIvrk3yVjZxtYZswqDsLZ1HA=
decode: alex
5.一些参考 =>
https://www.cnblogs.com/sunws/p/4783358.html
https://blog.csdn.net/wherwh/article/details/46699767
//crypto 里面公钥加密私钥解密的主要方法
crypto.privateDecrypt(private_key, buffer)
crypto.privateEncrypt(private_key, buffer)
crypto.publicDecrypt(public_key, buffer)
crypto.publicEncrypt(public_key, buffer)
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_24078843/article/details/80776769