前端引入jsencrypt.min.js
创建jsencrypt.js,内容
import JSEncrypt from './jsencrypt.min.js';
//支付宝开放平台开发助手生成公/私钥
const publicKey = ''
const privateKey = ''
class JsEncryptNew extends JSEncrypt {
constructor() {
super();
this.b64map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
this.b64pad = '=';
this.BI_RM = '0123456789abcdefghijklmnopqrstuvwxyz';
}
int2char = function(n) {
return this.BI_RM.charAt(n);
};
b64tohex = function(s) {
var ret = '';
var i;
var k = 0; // b64 state, 0-3
var slop = 0;
for (i = 0; i < s.length; ++i) {
if (s.charAt(i) === this.b64pad) {
break;
}
var v = this.b64map.indexOf(s.charAt(i));
if (v < 0) {
continue;
}
if (k === 0) {
ret += this.int2char(v >> 2);
slop = v & 3;
k = 1;
} else if (k === 1) {
ret += this.int2char((slop << 2) | (v >> 4));
slop = v & 0xf;
k = 2;
} else if (k === 2) {
ret += this.int2char(slop);
ret += this.int2char(v >> 2);
slop = v & 3;
k = 3;
} else {
ret += this.int2char((slop << 2) | (v >> 4));
ret += this.int2char(v & 0xf);
k = 0;
}
}
if (k === 1) {
ret += this.int2char(slop << 2);
}
return ret;
};
hex2b64 = function(h) {
var i;
var c;
var ret = '';
for (i = 0; i + 3 <= h.length; i += 3) {
c = parseInt(h.substring(i, i + 3), 16);
ret += this.b64map.charAt(c >> 6) + this.b64map.charAt(c & 63);
}
if (i + 1 === h.length) {
c = parseInt(h.substring(i, i + 1), 16);
ret += this.b64map.charAt(c << 2);
} else if (i + 2 === h.length) {
c = parseInt(h.substring(i, i + 2), 16);
ret += this.b64map.charAt(c >> 2) + this.b64map.charAt((c & 3) << 4);
}
while ((ret.length & 3) > 0) {
ret += this.b64pad;
}
return ret;
};
// 分段加密
encryptLong = function(string) {
debugger;
var k = this.getKey();
// var maxLength = (((k.n.bitLength() + 7) >> 3) - 11);//117
try {
// var lt = '';
var ct = '';
// RSA每次加密117bytes,需要辅助方法判断字符串截取位置
// 1.获取字符串截取点
var bytes = [];
bytes.push(0);
var byteNo = 0;
var len, c;
len = string.length;
var temp = 0;
for (var i = 0; i < len; i++) {
c = string.charCodeAt(i);
if (c >= 0x010000 && c <= 0x10FFFF) {
byteNo += 4;
} else if (c >= 0x000800 && c <= 0x00FFFF) {
byteNo += 3;
} else if (c >= 0x000080 && c <= 0x0007FF) {
byteNo += 2;
} else {
byteNo += 1;
}
if ((byteNo % 117) >= 114 || (byteNo % 117) === 0) {
if (byteNo - temp >= 114) {
bytes.push(i);
temp = byteNo;
}
}
}
// 2.截取字符串并分段加密
if (bytes.length > 1) {
for (let i = 0; i < bytes.length - 1; i++) {
var str;
if (i === 0) {
str = string.substring(0, bytes[i + 1] + 1);
} else {
str = string.substring(bytes[i] + 1, bytes[i + 1] + 1);
}
var t1 = k.encrypt(str);
ct += t1;
}
;
if (bytes[bytes.length - 1] !== string.length - 1) {
var lastStr = string.substring(bytes[bytes.length - 1] + 1);
ct += k.encrypt(lastStr);
// debugger;
}
return this.hex2b64(ct);
}
var t = k.encrypt(string);
var y = this.hex2b64(t);
return y;
} catch (ex) {
return false;
}
};
// 分段解密长字符串
decryptLong = function(text) {
// Return the decrypted string.
// console.log(this);
var k = this.getKey();
var maxLength = ((k.n.bitLength() + 7) >> 3);
try {
var str = this.b64tohex(text);
// var b=hex2Bytes(str);
var inputLen = str.length;
var ct = '';
if (inputLen > maxLength) {
var lt = str.match(/.{1,256}/g);
lt.forEach(function(entry) {
var t1 = k.decrypt(entry);
ct += t1;
});
return ct;
}
var y = k.decrypt(this.b64tohex(text));
return y;
} catch (ex) {
return false;
}
};
}
export const $encruption = (str, key = publicKey) => {
const ENCRYPT = new JsEncryptNew();
ENCRYPT.setPublicKey(key);
return ENCRYPT.encryptLong(str.toString());
};
export const $decryption = (str, key = privateKey) => {
const ENCRYPT = new JsEncryptNew();
ENCRYPT.setPrivateKey(key);
return ENCRYPT.decryptLong(str.toString());
};
使用地方引入import { $encruption } from '@/utils/jsencrypt'
使用:$encruption(JSON.stringify('123'));
后端工具类
package com.cssnj.biz.comm.utils;
import com.cssnj.biz.comm.constant.TestCont;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* @author : sean
* @version V1.0
* @Project: jsencrypt
* @Package utils
* @date Date : 2021年09月23日 21:36
* @Description: RSA加解密工具类,实现公钥加密私钥解密和私钥解密公钥解密
*/
public class RsaUtils {
/**
* 公钥加密私钥解密
*/
public static void test1(RSAKeyPair keyPair, String source) throws Exception {
System.out.println("***************** 公钥加密私钥解密开始 *****************");
String text1 = encryptByPublicKey(keyPair.getPublicKey(), source);
String text2 = decryptByPrivateKey(keyPair.getPrivateKey(), source);
System.out.println("加密前:" + source);
System.out.println("加密后:" + text1);
System.out.println("解密后:" + text2);
if (source.equals(text2)) {
System.out.println("解密字符串和原始字符串一致,解密成功");
} else {
System.out.println("解密字符串和原始字符串不一致,解密失败");
}
System.out.println("***************** 公钥加密私钥解密结束 *****************");
}
public static void main(String[] args) throws Exception {
RSAKeyPair rsaKeyPair = new RSAKeyPair(TestCont.publicKey,TestCont.privteKey);
test1(rsaKeyPair,"123");
}
/**
* 私钥加密公钥解密
*
* @throws Exception
*/
private static void test2(RSAKeyPair keyPair, String source) throws Exception {
System.out.println("***************** 私钥加密公钥解密开始 *****************");
String text1 = encryptByPrivateKey(keyPair.getPrivateKey(), source);
String text2 = decryptByPublicKey(keyPair.getPublicKey(), text1);
System.out.println("加密前:" + source);
System.out.println("加密后:" + text1);
System.out.println("解密后:" + text2);
if (source.equals(text2)) {
System.out.println("解密字符串和原始字符串一致,解密成功");
} else {
System.out.println("解密字符串和原始字符串不一致,解密失败");
}
System.out.println("***************** 私钥加密公钥解密结束 *****************");
}
/**
* 公钥解密
*
* @param publicKeyText
* @param text
* @return
* @throws Exception
*/
public static String decryptByPublicKey(String publicKeyText, String text) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
}
/**
* 私钥加密
*
* @param privateKeyText
* @param text
* @return
* @throws Exception
*/
public static String encryptByPrivateKey(String privateKeyText, String text) throws Exception {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(text.getBytes());
return Base64.encodeBase64String(result);
}
/**
* 私钥解密
*
* @param privateKeyText
* @param text
* @return
* @throws Exception
*/
public static String decryptByPrivateKey(String privateKeyText, String text) throws Exception {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
}
/**
* 公钥加密
*
* @param publicKeyText
* @param text
* @return
*/
public static String encryptByPublicKey(String publicKeyText, String text) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(text.getBytes());
return Base64.encodeBase64String(result);
}
/**
* 构建RSA密钥对
*
* @return
* @throws NoSuchAlgorithmException
*/
public static RSAKeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
RSAKeyPair rsaKeyPair = new RSAKeyPair(publicKeyString, privateKeyString);
return rsaKeyPair;
}
/**
* RSA密钥对对象
*/
public static class RSAKeyPair {
private String publicKey;
private String privateKey;
public RSAKeyPair(String publicKey, String privateKey) {
this.publicKey = publicKey;
this.privateKey = privateKey;
}
public String getPublicKey() {
return publicKey;
}
public String getPrivateKey() {
return privateKey;
}
}
}
TestCont为常量公/私钥