一、首先RSA非对称加解密,是在前端加密,后端解密,所以前端使用了jsEncrypt;后台要能工具包附在下文。
1、引入别人的wx_rsa.js
https://github.com/UFO0001/WX_RSA/tree/master/utils
2、在使用的文件中
import RSA from '../../../../utils/wx_rsa';
//加密
encryt: function () {
var publicKey = "-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA*****-----END PUBLIC KEY-----"
let input_rsa = '18910012002';
let encrypt_rsa = new RSA.RSAKey();
encrypt_rsa = RSA.KEYUTIL.getKey(publicKey);
let encStr = encrypt_rsa.encrypt(input_rsa)
encStr = RSA.hex2b64(encStr);
console.log("加密结果:" + encStr)
this.setData({
output: encStr
})
this.decrypt()
},
//解密
decrypt: function () {
var privateKey = '-----BEGIN PRIVATE KEY-----MIICeAIBADANBg*****-----END PRIVATE KEY-----'
var decrypt_rsa = new RSA.RSAKey();
decrypt_rsa = RSA.KEYUTIL.getKey(privateKey);
let encStr = this.data.output
if (encStr.length <= 0) {
wx.showToast({
title: '请先加密',
icon: 'loading',
duration: 1000
})
} else {
encStr = RSA.b64tohex(encStr);
var decStr = decrypt_rsa.decrypt(encStr)
console.log("解密结果:" + decStr)
this.setData({
output: decStr
})
}
},
后端工具类:
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
*
*/
public class RSAUtilsBack {
private static final String KEY_ALGORITHM = "RSA";
private static final String SIGNATURE_ALGORITHM = "MD5withRSAtest";
// 公钥
private static String PUBLIC_KEY = "MIGfMA0GCSqGSIb3D***";
// 私钥
private static String PRIVATE_KEY = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAm****";
public static String getPUBLIC_KEY() {
return PUBLIC_KEY;
}
public void setPUBLIC_KEY(String pUBLIC_KEY) {
PUBLIC_KEY = pUBLIC_KEY;
}
public static String getPRIVATE_KEY() {
return PRIVATE_KEY;
}
public static void setPRIVATE_KEY(String pRIVATE_KEY) {
PRIVATE_KEY = pRIVATE_KEY;
}
/**
* 初始化密钥
*
* @return
* @throws Exception
*/
public static Map<String, String> initKey() {
Map<String, String> map = new HashMap<String, String>();
try {
//随机生成密钥对
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
//按照指定字符串生成密钥对
// SecureRandom secureRandom = new SecureRandom("我是字符串".getBytes());
// keyPairGen.initialize(1024, secureRandom);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
PUBLIC_KEY = Coder.encryptBASE64(publicKey.getEncoded());
System.out.println("公钥" + PUBLIC_KEY.replaceAll("\n","").replaceAll("\r",""));
// 私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
PRIVATE_KEY = Coder.encryptBASE64(privateKey.getEncoded());
System.out.println("私钥" + PRIVATE_KEY.replaceAll("\n","").replaceAll("\r",""));
map.put("pubkey", PUBLIC_KEY);
map.put("prikey", PRIVATE_KEY);
} catch (Exception e) {
e.printStackTrace();
System.out.println("初始化密钥异常" + e);
}
return map;
}
/**
* 公钥加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static String encryptByPublicKey(String data, String key) {
try {// 对公钥解密
byte[] keyBytes = Coder.decryptBASE64(key);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Coder.encryptBASE64(cipher.doFinal(data.getBytes("utf-8")));
} catch (Exception e) {
e.printStackTrace();
System.out.println("公钥加密异常" + e);
}
return null;
}
/**
* 公钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static String decryptByPublicKey(String data, String key) {
// 对密钥解密
try {
byte[] keyBytes = Coder.decryptBASE64(key);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] encryptedData = Coder.decryptBASE64(data);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > 128) {
cache = cipher.doFinal(encryptedData, offSet, 128);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * 128;
}
byte[] decryptedData = out.toByteArray();
out.close();
return new String(decryptedData, "utf-8");
} catch (Exception e) {
e.printStackTrace();
System.out.println("公钥解密异常" + e);
}
return null;
}
/**
* 私钥加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static String encryptByPrivateKey(String data, String key) {
try {
// 对密钥解密
byte[] keyBytes = Coder.decryptBASE64(key);
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return Coder.encryptBASE64(cipher.doFinal(data.getBytes("utf-8")));
} catch (Exception e) {
e.printStackTrace();
System.out.println("私钥加密异常" + e);
}
return null;
}
/**
* 私钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static String decryptByPrivateKey(String data, String key) {
try {
// 对密钥解密
byte[] keyBytes = Coder.decryptBASE64(key);
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] encryptedData = Coder.decryptBASE64(data);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > 128) {
cache = cipher.doFinal(encryptedData, offSet, 128);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * 128;
}
byte[] decryptedData = out.toByteArray();
out.close();
return new String(decryptedData, "utf-8");
} catch (Exception e) {
e.printStackTrace();
System.out.println("私钥解密异常" + e);
}
return null;
}
/**
* 用私钥对信息生成数字签名
*
* @param data
* 加密数据
* @param privateKey
* 私钥
*
* @return
* @throws Exception
*/
public static String sign(byte[] data, String privateKey) throws Exception {
// 解密由base64编码的私钥
byte[] keyBytes = Coder.decryptBASE64(privateKey);
// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// 取私钥匙对象
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 用私钥对信息生成数字签名
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(priKey);
signature.update(data);
return Coder.encryptBASE64(signature.sign());
}
/**
* 校验数字签名
*
* @param data
* 加密数据
* @param publicKey
* 公钥
* @param sign
* 数字签名
*
* @return 校验成功返回true 失败返回false
* @throws Exception
*
*/
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
// 解密由base64编码的公钥
byte[] keyBytes = Coder.decryptBASE64(publicKey);
// 构造X509EncodedKeySpec对象
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// 取公钥匙对象
PublicKey pubKey = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(pubKey);
signature.update(data);
// 验证签名是否正常
return signature.verify(Coder.decryptBASE64(sign));
}
public static Map<String, String> createKeys(int keySize) throws Exception{
//为RSA算法创建一个KeyPairGenerator对象
KeyPairGenerator kpg;
try{
kpg = KeyPairGenerator.getInstance("RSA");
}catch(NoSuchAlgorithmException e){
throw new IllegalArgumentException("No such algorithm-->[" + "RSA" + "]");
}
//初始化KeyPairGenerator对象,密钥长度
kpg.initialize(keySize);
//生成密匙对
KeyPair keyPair = kpg.generateKeyPair();
//得到公钥
Key publicKey = keyPair.getPublic();
String publicKeyStr = Coder.encryptBASE64(publicKey.getEncoded());
//得到私钥
Key privateKey = keyPair.getPrivate();
String privateKeyStr = Coder.encryptBASE64(privateKey.getEncoded());
Map<String, String> keyPairMap = new HashMap<String, String>();
keyPairMap.put("publicKey", publicKeyStr);
keyPairMap.put("privateKey", privateKeyStr);
return keyPairMap;
}
public static void main(String[] args){
try {
System.out.println(initKey());
} catch (Exception e) {
e.printStackTrace();
}
String s = encryptByPublicKey("188910012801", getPUBLIC_KEY());
System.out.println("----:"+s);
System.out.println(decryptByPrivateKey(s, getPRIVATE_KEY()));
}
}