加密流程:
1.客户端GET请求java 后端Controller
2.java 后端 Controller读取公钥内容发送到前端
3.前端获取到公钥使用JSEncrypt加密
4.将加密以后的数据发送到后端
5.后端通过私钥解密字段
需要的工具:
前端加密JSEncrypt 下载:
https://github.com/travist/jsencrypt
后端需要 code
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.66</version>
</dependency>
前端代码
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>登录</title>
<script th:src="@{/jsencrypt.js}" type="text/javascript"></script>
<script th:src="@{/jquery.js}" type="text/javascript"></script>
<script type="text/javascript" th:inline="javascript">
$(function() {
$('#testme').click(function() {
var pubkey = [[${publicKey}]];
console.log(pubkey);
var encrypt = new JSEncrypt();
encrypt.setPublicKey(pubkey);
var encrypted = encrypt.encrypt($('#input').val());
console.log(encrypted);
$.post("/page/logins", {"payload":encrypted} );
});
});
</script>
</head>
<body>
<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>
后端代码
Controller 接收代码
package org.lbyang.controller.page;
import org.kong.controller.util.RSAUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Encoder;
import java.security.PrivateKey;
/**
* @Author: libo
* @Date: 2020/8/6
*/
@Controller
@RequestMapping("/page")
public class PageController {
@GetMapping("/login")
public ModelAndView login(){
ModelAndView modelAndView = new ModelAndView("loginpage2");
String publicKeyFileName =getClass().getResource("/rsaPublicKey.txt").getFile();
//String publicKeyFileNameCer =getClass().getResource("/sso-form-qat-pubic.cer").getFile();
try{
//byte[] encoded=RSAUtils.getPublicKeyFromCer(publicKeyFileName).getEncoded();
//BASE64Encoder base64ecoder = new BASE64Encoder();
//modelAndView.addObject("publicKey",RSAUtils.base64ecoder.encode(encoded));
modelAndView.addObject("publicKey",RSAUtils.readRSAKeyPem(publicKeyFileName));
}catch (Exception ex){
ex.printStackTrace();
}
return modelAndView;
}
@PostMapping("/logins")
public String postlogin(String payload) throws Exception {
System.out.println(payload);
RSAUtils(payload);
return "loginpage2";
}
private void RSAUtils(String payload) throws Exception {
String privateKeyFileName =getClass().getResource("/rsaPrivateKey.txt").getFile();
PrivateKey privateKeyFromPem = RSAUtils.getPrivateKeyFromPem(privateKeyFileName);
BASE64Encoder base64ecoder = new BASE64Encoder();
String decrypt = RSAUtils.decrypt(payload, base64ecoder.encode(privateKeyFromPem.getEncoded()));
System.out.println(decrypt);
}
}
RSA 工具类
package org.lbyang.util;
import javax.crypto.Cipher;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.security.*;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* @Author: lbyang
* @Date: 2020/8/10
*/
public class RSAUtils {
private static final String KEY_ALGORITHM = "RSA";
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
private static final String UTF_8="UTF-8";
public static final Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
private static BASE64Decoder base64decoder = new BASE64Decoder();
private static BASE64Encoder base64ecoder = new BASE64Encoder();
static {
Security.addProvider(provider);
}
public static String readRSAKeyPem(String keypath) throws Exception{
BufferedReader br = new BufferedReader(new FileReader(keypath));
String s = br.readLine();
String str = "";
s = br.readLine();
while (s.charAt(0) != '-') {
str += s + "\r";
s = br.readLine();
}
return str;
}
public static PrivateKey getPrivateKeyFromPem(String privateKeyPath) throws Exception {
byte[] b = base64decoder.decodeBuffer(readRSAKeyPem(privateKeyPath));
KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(b);
return kf.generatePrivate(keySpec);
}
public static PublicKey getPublicKeyFromCer(String cerPath) throws Exception{
CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
FileInputStream fis = new FileInputStream(cerPath);
X509Certificate Cert = (X509Certificate) certificatefactory.generateCertificate(fis);
return Cert.getPublicKey();
}
public static PublicKey getPublicKeyFromPem(String publicKeyPath) throws Exception{
byte[] b = base64decoder.decodeBuffer(readRSAKeyPem(publicKeyPath));
KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(b);
return kf.generatePublic(keySpec);
}
public static String encrypt(String str, String publicKey) throws Exception{
byte[] decoded=base64decoder.decodeBuffer(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(new X509EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
return base64ecoder.encode(cipher.doFinal(str.getBytes(UTF_8)));
}
public static String decrypt(String str, String privateKey) throws Exception{
byte[] inputByte = base64decoder.decodeBuffer(str);
byte[] decoded= base64decoder.decodeBuffer(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, priKey);
return new String(cipher.doFinal(inputByte));
}
public static void genKeyPair() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
System.out.println("public key:"+new String(publicKey.getEncoded(),UTF_8));
System.out.println("private key:"+new String(privateKey.getEncoded(),UTF_8));
}
public static String sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = base64decoder.decodeBuffer(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(data);
return base64ecoder.encode(signature.sign());
}
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
byte[] keyBytes = base64decoder.decodeBuffer(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicK = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(data);
return signature.verify(base64decoder.decodeBuffer(sign));
}
public static void main(String[] args) {
try{
// String privateKeyFileName = "/Users/mac/Documents/javawork/kong-gateway/kong-controller/src/main/resources/rsaPrivateKey.txt";
// String publicKeyFileName = "/Users/mac/Documents/javawork/kong-gateway/kong-controller/src/main/resources/rsaPublicKey.txt";
//
// PublicKey publicKey = getPublicKeyFromPem(publicKeyFileName);
// PrivateKey privateKeyFromPem = getPrivateKeyFromPem(privateKeyFileName);
// String encrypt = encrypt("zhangsan", base64ecoder.encode(publicKey.getEncoded()));
// String decrypt = decrypt(encrypt, base64ecoder.encode(privateKeyFromPem.getEncoded()));
// System.out.println(encrypt);
// System.out.println(decrypt);
String privateKeyFileName = "/Users/mac/Documents/javawork/kong-gateway/kong-controller/src/main/resources/sso_form_qat-private.key";
String publicKeyFileName = "/Users/mac/Documents/javawork/kong-gateway/kong-controller/src/main/resources/sso-form-qat-pubic.cer";
PublicKey publicKey = getPublicKeyFromCer(publicKeyFileName);
PrivateKey privateKeyFromPem = getPrivateKeyFromPem(privateKeyFileName);
String encrypt = encrypt("zhangsan", base64ecoder.encode(publicKey.getEncoded()));
String decrypt = decrypt(encrypt, base64ecoder.encode(privateKeyFromPem.getEncoded()));
System.out.println(encrypt);
System.out.println(decrypt);
}catch (Exception ex){
ex.printStackTrace();
}
}
}
公钥
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAleOgtAqdr5l4PRT0s5QB
3YIozBwk1koFOs8pNSYzWqtld8Y6hEaQaT8o7ilohTg46EhBWwER1fn3P/28iZ5w
KnMrfYYdP8U/BtBW580NiKwn8I7qfKZ30SY0KjbtviwbixA3+pi85jMguYMA0nMY
JjYkmkOhuWfvUeV4D/mTJFPsM9gXpnxkAfUyS+Ndwsl5UE2UbEfa84h7aWM1JG+t
hkeqD3EBCaAVP/G+8zZWycFE2lnljBznFcC/knPZlvdiOJFTBXaVOMiwqIl8/RuD
tSyU2Ur0klT0EtqFDRu0PiyZhWiK+zH7YbGMrUx5DbQea+EWJrcgtSdC6LVWns1Z
ZQIDAQAB
-----END PUBLIC KEY-----
私钥
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCV46C0Cp2vmXg9
FPSzlAHdgijMHCTWSgU6zyk1JjNaq2V3xjqERpBpPyjuKWiFODjoSEFbARHV+fc/
/byJnnAqcyt9hh0/xT8G0FbnzQ2IrCfwjup8pnfRJjQqNu2+LBuLEDf6mLzmMyC5
gwDScxgmNiSaQ6G5Z+9R5XgP+ZMkU+wz2BemfGQB9TJL413CyXlQTZRsR9rziHtp
YzUkb62GR6oPcQEJoBU/8b7zNlbJwUTaWeWMHOcVwL+Sc9mW92I4kVMFdpU4yLCo
iXz9G4O1LJTZSvSSVPQS2oUNG7Q+LJmFaIr7MfthsYytTHkNtB5r4RYmtyC1J0Lo
tVaezVllAgMBAAECggEA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