一、前端代码
<!doctype html>
<html>
<head>
<title>JavaScript RSA Encryption</title>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://passport.cnblogs.com/scripts/jsencrypt.min.js"></script>
<script type="text/javascript">
// Call this code when the page is done loading.
$(function() {
// Run a quick encryption/decryption when they click.
$('#testme').click(function() {
// Encrypt with the public key...
var encrypt = new JSEncrypt();
encrypt.setPublicKey($('#pubkey').val());
var encrypted = encrypt.encrypt($('#input').val());
console.log(encrypted);
alert(encrypted);
});
});
</script>
</head>
<body>
<label for="pubkey">Public Key</label><br/>
<textarea id="pubkey" rows="15" cols="65">-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCdhekzj66uRPf5qWPKCFT9WINBSNmH7ZtaRIkw
440fnMgdKhAV8xheJ7IBbLDPgJPo1x+VrrO6fbKZYWQI5kuCWzgppqPJKEzlqLm6Veg3XQZAEtS4
iWZf9nF+0WA40CzaNIRPAhsolRWVw5Sjnp7gVtxzzLudIIgZ2VLcYWI1twIDAQAB
-----END PUBLIC KEY-----</textarea><br/>
<label for="input">Text to encrypt:</label><br/>
<textarea id="input" name="input" type="text" rows=4 cols=70>This is a test!</textarea><br/>
<input id="testme" type="button" value="Test Me!!!" /><br/>
</body>
</html>
二、Java RSA工具类
package com.exmaple.test;
/**
* @Author: haoshuaiwei
* @Date: 2021/3/23 11:08 上午
*/
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
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.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 生成RSA公私钥工具类
*
* @author Mr.Hao
* @date 2021/03/23
*/
public class RsaKeyPairGenUtil {
/**
* 指定加密算法为RSA
*/
private static final String ALGORITHM = "RSA";
/**
* 密钥长度,用来初始化
*/
private static final int KEYSIZE = 1024;
/**
* 指定公钥存放文件
*/
private static String PUBLIC_KEY_FILE = "1.public";
/**
* 指定私钥存放文件
*/
private static String PRIVATE_KEY_FILE = "1.private";
/**
* 生成密钥对 文件
*
* @throws Exception
*/
public static void generateKeyPairCreateFile() throws Exception {
// /** RSA算法要求有一个可信任的随机数源 */
// SecureRandom secureRandom = new SecureRandom();
/** 为RSA算法创建一个KeyPairGenerator对象 */
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
/** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
// keyPairGenerator.initialize(KEYSIZE, secureRandom);
keyPairGenerator.initialize(KEYSIZE);
/** 生成密匙对 */
KeyPair keyPair = keyPairGenerator.generateKeyPair();
/** 得到公钥 */
Key publicKey = keyPair.getPublic();
/** 得到私钥 */
Key privateKey = keyPair.getPrivate();
ObjectOutputStream oos1 = null;
ObjectOutputStream oos2 = null;
try {
/** 用对象流将生成的密钥写入文件 */
oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));
oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));
oos1.writeObject(publicKey);
oos2.writeObject(privateKey);
} catch (Exception e) {
throw e;
} finally {
/** 清空缓存,关闭文件输出流 */
if (oos1 != null) {
oos1.close();
}
if (oos2 != null) {
oos2.close();
}
}
}
/**
* 获取 RSA 公私钥、键对值
*
* @return
* @throws NoSuchAlgorithmException
*/
public static Map<String, String> genKeyPairBase64() throws NoSuchAlgorithmException {
/** RSA算法要求有一个可信任的随机数源 */
SecureRandom secureRandom = new SecureRandom();
/** 为RSA算法创建一个KeyPairGenerator对象 */
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
/** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
keyPairGenerator.initialize(KEYSIZE, secureRandom);
/** 生成密匙对 */
KeyPair keyPair = keyPairGenerator.generateKeyPair();
/** 得到公钥 */
Key publicKey = keyPair.getPublic();
/** 得到私钥 */
Key privateKey = keyPair.getPrivate();
byte[] publicKeyBytes = publicKey.getEncoded();
byte[] privateKeyBytes = privateKey.getEncoded();
String publicKeyBase64 = new BASE64Encoder().encode(publicKeyBytes);
String privateKeyBase64 = new BASE64Encoder().encode(privateKeyBytes);
Map<String, String> map = new HashMap<>();
map.put("public", publicKeyBase64);
map.put("private", privateKeyBase64);
return map;
}
/**
* RSA公钥加密
*
* @param str 加密字符串
* @param publicKey 公钥
* @return 密文
* @throws Exception 加密过程中的异常信息
*/
public static String encrypt( String str, String publicKey ) throws Exception{
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
}
/**
* RSA私钥解密
*
* @param str 加密字符串
* @param privateKey 私钥
* @return 明文
* @throws Exception 解密过程中的异常信息
*/
public static String decrypt(String str, String privateKey) throws Exception{
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
String outStr = new String(cipher.doFinal(inputByte));
return outStr;
}
/*public static void main(String[] args) {
System.out.println(new Date());
try {
Map<String, String> map = genKeyPair();
System.out.println(map.get("public"));
System.out.println(map.get("private"));
String pwd = "123";
String ePwd = encrypt(pwd,map.get("public"));
String rPwd = decrypt(ePwd,map.get("private"));
System.out.println(ePwd);
System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urm10mutUX8oc6fh+K3YHpzzfgzHiokc\n" +
"FARXGkd3");
System.out.println(rPwd1);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(new Date());
}*/
}
三、Controller使用
@GetMapping(value = "/rsa")
public String rsa(HttpSession httpSession) {
Map<String,String> map = new HashMap<>();
try {
map = RsaKeyPairGenUtil.genKeyPairBase64();
httpSession.setAttribute("private",map.get("private"));
}catch (Exception e){
return "";
}
return map.get("public");
}
四、解密使用
RsaKeyPairGenUtil.decrypt("前端加密的结果","私钥,与公钥对应")