RSA,RSA2公钥私钥加密解密
AES加解密在线调试工具
// RSA依赖
npm install jsencrypt --save
// AES依赖
npm install cryptojs
创建rsa.js
import JSEncrypt from 'jsencrypt'
/**
* rsa加密
* @param {string} str 原文
* @param {string} keyCode 公钥
* @returns {string} 加密后的文本
*/
export function getRsaCode(str, keyCode) {
const encryptStr = new JSEncrypt()
const pubKey = `-----BEGIN RSA PRIVATE KEY-----${
keyCode}-----END RSA PRIVATE KEY-----`
// 设置 加密公钥
encryptStr.setPublicKey(keyCode)
// 进行加密
const data = encryptStr.encrypt(str.toString())
return data
}
/**
* rsa解密
* @param {string} str 加密的文本
* @param {string} keyCode 公钥
* @returns {string} 解密后的文本
*/
export function getRsaDeCode(str, keyCode) {
var decrypt = new JSEncrypt()
// ES6 模板字符串 引用 rsa 公钥
// const pubKeyPrivate = `-----BEGIN RSA PRIVATE KEY-----${keyCode}-----END RSA PRIVATE KEY-----`
// 解密公钥
decrypt.setPrivateKey(keyCode)
// 解密
var decryptMsg = decrypt.decrypt(str.toString())
return decryptMsg
}
/**
* 生成32位16进制随机数
* @returns {string} 32位字符
*/
export function createHexRandom() {
var num = ''
for (let i = 0; i <= 31; i++) {
var tmp = Math.ceil(Math.random() * 15).toString(16)
num += tmp
}
return num
}
使用rsa
import {
getRsaCode, getRsaDeCode } from './mixins/rsa.js'
/**
* 加密头部
* @param {headers} headers 头部
* @param {string} keyCode 加密码
* @description 装修加密头部信息
*/
function addEnHeaders(headers, keyCode) {
let publicKey =
'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjVweqeSHRKNACRj9yIXyfIE57J+7D3RtsVKeh4sHy4kKAOB1uweqEAOPGWM+X1dGgxY2oxcDaQDm697dimfguhHonAxMc6rMXOXO0Jb9i8NDsPCV9osHhepPzEeq1zfP9M7Knlzzskrszil3gEPi0815KqEiO+gAuMUdzqwepwzQyjPkB2/OWjoqTWN8NDazyvvfqbhrz/k8shn6W9K2HGbG8I4APm1+g0McumTErMw9WBOCJg4aEYc5p+S5URnAoOmJ0DChUhNxbr/MkW0xXCNLDxrmqPuVPYYx8P8LZwLwexroJC0gAgfhcRWrK/tG+zfUZUCuejs72rteiu+LYWalN4OwIDAQAB'
headers['Content-Type'] = 'application/encrypted-json;charset=UTF-8'
headers['X-Encrypted-Key'] = getRsaCode(keyCode, publicKey)
}
公钥从后端接口获取,可以从在线RSA,RSA2公钥私钥加密解密生成测试密钥
import cryptoJs from 'crypto-js'
/**
* 加密
* @param {*} word 需要加密数据
* @param {string} keyCode 加密秘钥
* @param {string} ivCode 矢量
*
* @returns {string} 新数据
*/
export function encrypt(word, keyCode, ivCode) {
if (!word) {
return
}
// 16位秘钥(128bit),支持128位、192位、256位key
let key = CryptoJS.enc.Utf8.parse(keyCode || '11111111ffffffff')
// 16位矢量码
let iv = CryptoJS.enc.Utf8.parse(ivCode || '11111111ffffffff')
let encrypted = ''
if (typeof word == 'string') {
let srcs = CryptoJS.enc.Utf8.parse(word)
encrypted = CryptoJS.AES.encrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
// PKCS5Padding或PKCS7Padding
padding: CryptoJS.pad.Pkcs7,
})
} else if (typeof word == 'object') {
// 对象格式的转成json字符串
let data = JSON.stringify(word)
let srcs = CryptoJS.enc.Utf8.parse(data)
encrypted = CryptoJS.AES.encrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
})
}
return encrypted.ciphertext.toString()
}
/**
* 解密
* @param {*} word 数据
* @param {string} keyCode 加密秘钥码
* @param {string} ivCode 矢量码
*
* @returns {string} 新数据
*/
export function decrypt(word, keyCode, ivCode) {
if (!word) {
return
}
let key = CryptoJS.enc.Utf8.parse(keyCode || '1234567890000000')
let iv = CryptoJS.enc.Utf8.parse(ivCode || '1234567890000000')
let encryptedHexStr = CryptoJS.enc.Hex.parse(word)
let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)
let decrypt = CryptoJS.AES.decrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
})
let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
return decryptedStr.toString()
}
```js
## Base64方式
Base64加密
```js
... {
...
return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
}
Base64解密
...(word) {
let key = CryptoJS.enc.Utf8.parse(keyCode),
// 通过base64解析密文
ciphertext = CryptoJS.enc.Base64.parse(word).toString(),
encryptedHexStr = CryptoJS.enc.Hex.parse(ciphertext),
srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr),
cipherParams = {
iv: CryptoJS.enc.Utf8.parse(ivCode),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7, // PKCS5Padding或PKCS7Padding
},
decrypt = CryptoJS.AES.decrypt(srcs, key, cipherParams),
decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
return decryptedStr.toString()
}
axios.js
import axios from 'axios'
import aes from './mixins/aes.js'
import {
getRsaCode, getRsaDeCode } from './mixins/rsa.js'
...
// http request 拦截器
axios.interceptors.request.use(
config => {
// 获取时区GMT+8时间戳
let keyCode = getZoneTimestamp(8).toString()
/**
* 1、创建32位十六进制随机数
* 2、截取前面19位 + GT8时间戳补全
*/
keyCode = aes.createHexRandom().substring(0, 32 - keyCode.length) + keyCode
if (config.method == 'get') {
// get方式不需要加密
config.params = config.params.params
} else if (config.method == 'post') {
if (加密条件) {
// 加密数据
config.data = aes.encrypt(
config.data.params,
keyCode,
keyCode.substring(0, 16),
)
addEnHeaders(headers, keyCode)
} else {
config.data = config.data.params
headers['Content-Type'] = 'application/json'
}
}
},
error => {
return Promise.reject(err)
},
error => {
reqArray = []
Indicator.close()
return Promise.reject(error)
},
)
// http response 拦截器
axios.interceptors.response.use(
response => {
}
)
...
话说代码不能写太全,,,留给别人更多点的思考机会。这样才能更快的成长!!!