持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第4天, 点击查看活动详情
一、RSA是什么
RSA是一种非对称加密算法,也就是说,有两个密钥来进行加密和解密,分别是公钥和私钥。顾名思义,公钥是公开的,私钥是需要保密的。在公开密钥密码体系中,虽然公钥和加密算法、解密算法都是公开的,但却不能根据公私计算出私钥。这种算法的密钥越长,就越难破解。目前公布的被破解的最长RAS密钥是768位,基本上可以认为1024位的RSA密钥基本安全。由于RAS进行的都是大数计算,使得RSA最快的情况也比DES慢上好几倍,速度一直是RSA的缺陷。一般来说只用于少量数据加密。
二、RSA秘钥生成方式
最方便的是这种在线密钥生成工具 ( web.chacuo.net/netrsakeypa…
openssl genrsa -out private.pem 1024
3、从私钥中提取公钥
openssl rsa -in private.pem -pubout -out public.pem
三、jsencrypt.js
jsencrypt.js是一个基于RSA算法加解密的库。
3.1、官网地址
3.2、介绍
When browsing the internet looking for a good solution to RSA Javascript encryption, there is a whole slew of libraries that basically take the fantastic work done by Tom Wu @ www-cs-students.stanford.edu/~tjw/jsbn/ and then modify that code to do what they want.
What I couldn't find, however, was a simple wrapper around this library that basically uses the library practically untouched, but adds a wrapper to provide parsing of actual Private and Public key-pairs generated with OpenSSL.
This library is the result of these efforts.
3.3、安装
npm install jsencrypt
3.4、引入
import JSEncrypt from "jsencrypt";
3.5、公钥加密
export const GetRsaCode = (value: string): string => {
let encryptor = new JSEncrypt(); // 创建加密对象实例
//之前ssl生成的公钥,复制的时候要小心不要有空格
let pubKey =
"-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3R2oMsiDws1jzuUxSfkaasNr/ZFsFER7Qn3ZC8uRwHgV+KQBMk//STuEvoYf0d+axg2T4xdJ/drjcIdQgGXn+xqYVfN88FYsHn3TTjoZ9/OS1nmVpnax/LIX77FwBghSC1YDHU9a006y71k1SnldtnW5FJ2uRM/KsdSOuIkPkFQIDAQAB-----END PUBLIC KEY-----";
encryptor.setPublicKey(pubKey); // 设置公钥
let rsaPassWord:any = "";
rsaPassWord = encryptor.encrypt(value); // 对内容进行加密
return rsaPassWord;
3.6、私钥解密
export const GetRsaCode = (value: string): string => {
let encryptor = new JSEncrypt(); // 创建加密对象实例
// 之前ssl生成的私钥,复制的时候要小心不要有空格
let pubKey =
'-----BEGIN RSA PRIVATE KEY-----MIICXQIBAAKBgQC3R2oMsiDws1jzuUxSfkaasNr/ZFsFER7Qn3ZC8uRwHgV+KQBMk//STuEvoYf0d+axg2T4xdJ/drjcIdQgGXn+xqYVfN88FYsHn3TTjoZ9/OS1nmVpnax/LIX77FwBghSC1YDHU9a006y71k1SnldtnW5FJ2uRM/KsdSOuIkPkFQIDAQABAoGBAJI5cNvGNk+z11FEUicyxiPe3CqMp63INfyebN0HKshku18nWSy/m4fwFOtKhcy+6JhRy3pLYiD92IkQmEwv50rKP0FdPg6DwyXoqlTvkxdinBCeNtlaRUgtqhzGiKET/K+lrv0GjCUgaMGrECsKHZS67TQHCRKnd/1/CX/1qkOBAkEA6A+Y83AiwarbRtc4rX9UZEu3A0SaEAphHxmU8i4M1o/RMZ5YMdI/aFAzo+7adZ0yScN9OlHCGh1AIyPBNjTdoQJBAMovjcD7iJ2n7dCNmMszhBsjkQQmsWreQODabduizU6+gN+oRnpy+ViDIJKYzOsPAfeRWJ988iEo8LCdsOkNKfUCQQCTrlFtIwDLdRslAxRrvWuMhG7MopzU9nYGX7ZdRRcgeNftltKTqjR2AwxKGFhonwiAzurj8WHwUosdkcSE5bHhAkBF6R2F3jPF99wGYf+0O5LxY2HwYoS0ZDdgyIZ2DJwbH0omi+Qa0Qig725i4kzw9laCyRIwy55ZkvNuzofufavFAkBiPvNlBRg5VNvxtlbJomnzMQ86HRbbhVLaK3rDJm3dJbkD00Xx7FUEcHeLzTKzxVJiiMfMre1GQroSguFoL9vF-----END RSA PRIVATE KEY-----';
encryptor.setPrivateKey(pubKey); // 设置私钥
let parm: any = encryptor.decrypt(value);
console.log(parm);
return parm;
一般在传密码给后端时用到非对称加密,前端用公钥加密,后端用私钥解密,保证了密码的安全性。不建议在前端做解密操作,爬虫一扒拉私钥就下来了。