Springboot+RSA非对称加密

这是百度百科对(对称加密丶非对称加密)的解释:

(1)对称加密算法在加密和解密时使用的是同一个秘钥。

(2)非对称加密算法需要两个密钥来进行加密和解密,这两个秘钥是公开密钥(public key,简称公钥)和私有密钥(private key,简称私钥)。

处理的思路:
(1)服务端利用RSA创建一对公私钥,服务端存储私钥,将公钥给客户端
(2)每次请求前,将明文数据利用公钥进行加密,然后将密文传递给服务端
(3)服务端拿到密文,利用私钥进行解密,得到明文数据,然后进行业务处理

1.引入jarbao

<dependency>
          <groupId>io.jsonwebtoken</groupId>
          <artifactId>jjwt</artifactId>
          <version>0.9.1</version>
      </dependency>
      
      <dependency>
         <groupId>com.auth0</groupId>
         <artifactId>jwks-rsa</artifactId>
         <version>0.9.0</version>
     </dependency>
<dependency>
	    <groupId>commons-io</groupId>
	    <artifactId>commons-io</artifactId>
	    <version>2.4</version>
	</dependency>
	
	<dependency>
	    <groupId>org.apache.commons</groupId>
	    <artifactId>commons-lang3</artifactId>
	</dependency>

2.创建自定义注解

package com.othp.core.config;

import java.lang.annotation.*;
import org.springframework.web.bind.annotation.Mapping;

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Mapping
@Documented
public @interface RsaParameter {

	/**
     * 入参是否解密,默认解密
     */
    boolean inDecode() default true;
 
    /**
     * 出参是否加密,默认加密
     */
    boolean outEncode() default false;
    
}

3.加入增强控制器

package com.othp.core.advice;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import com.othp.core.config.RsaParameter;
import com.othp.core.util.RSAEncrypt;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@ControllerAdvice(basePackages = {"com.othp.mine.controller","com.othp.mine.controller"})
public class RsaDecodeRequestBodyAdvice implements RequestBodyAdvice {

	@Override
	public boolean supports(MethodParameter methodParameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
		try {
            boolean encode = false;
            if (methodParameter.getMethod().isAnnotationPresent(RsaParameter.class)) {
                //获取注解配置的包含和去除字段
            	RsaParameter serializedField = methodParameter.getMethodAnnotation(RsaParameter.class);
                //入参是否需要解密
                encode = serializedField.inDecode();
            }
            if (encode) {
                log.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密");
                return new MyHttpInputMessage(inputMessage);
            }else{
                return inputMessage;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密出现异常:"+e.getMessage());
            return inputMessage;
        }
	}

	@Override
	public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		return body;
	}

	@Override
	public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
			Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
		return body;
	}
	
	class MyHttpInputMessage implements HttpInputMessage {
        private HttpHeaders headers;
        private InputStream body;
        public MyHttpInputMessage(HttpInputMessage inputMessage) throws Exception {
            this.headers = inputMessage.getHeaders();
            String content = IOUtils.toString(inputMessage.getBody(),"utf-8");
        	this.body = IOUtils.toInputStream(RSAEncrypt.rsaDecrypt(content));
            
        }
        @Override
        public InputStream getBody() throws IOException {
            return body;
        }
        @Override
        public HttpHeaders getHeaders() {
            return headers;
        }

	}


}

4.加入RSA工具类

package com.othp.core.util;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import com.fasterxml.jackson.databind.util.JSONPObject;

public class RSAEncrypt {
	
	private static Map<Integer, String> keyMap = new HashMap<Integer, String>();  //用于封装随机产生的公钥与私钥
	
	//公钥
	private static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxkIbCWY8re71Fwmf4ehTl+6xuvFSbEuE7ZumXMlOkvWdSVatiTNnrX29I33uAicp19XJAwZSy2hKUPkoSmqzyZ9Si+fi3h1ZGD31WtSVxiAGgkmclVjIiuph2v8kjc/knzZgzLQaPX5E5SkFKPK+9bWJ+2Fkrx3ulSBxAeqWTuQIDAQAB";
	
	//私钥
	private static String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALGQhsJZjyt7vUXCZ/h6FOX7rG68VJsS4Ttm6ZcyU6S9Z1JVq2JM2etfb0jfe4CJynX1ckDBlLLaEpQ+ShKarPJn1KL5+LeHVkYPfVa1JXGIAaCSZyVWMiK6mHa/ySNz+SfNmDMtBo9fkTlKQUo8r71tYn7YWSvHe6VIHEB6pZO5AgMBAAECgYBJuOHai2if+y4oaoDUb4uBuS5sg5D1Ga+eBCpz9hc4TNM7IgqYM6Q+z07bCL60LYF73D5lmHnukBAqsHn8o2+uPBl202/Mg9j3VGD3BVfcjXOeNmtbdGRbK8qR/AG33WoUC41DqXG5teXQ1bqbzgIhd/o8c3beLGkS6kNjhOXCiQJBAOCcgRgeRSetiZMFCBzXEqds0Zk7rOUyjFGUA6ANsHZQbiZYYqXWuvetbLcjdYmSW5H92+FsVZDSIq7kGQzk9y8CQQDKYOsF+a7MEQaSyJ84olmiRyL9OCxBW0Qkgi81mZSbAQ4zKEN42rYYhpzEFSRYNltYbqlr5UaheOnGtw4nwumXAkEApHWziGdRl3XXT9DVWdiYjgJ9jcdGFyPl3i2UYfLkDB1kKat5v5f0mjlfatEJ1MtXRRQtlWbvV/Sk9I2LUgesfQJAft4a93f6uDrEIChciChegHiP2qXoOGB6a1ihN7y7iCA1QqSvB4g0N1PL2rBWRGZvBRT6aIUmrfsaslP3L73kqQJBAJ0GwkZTKLEMTzObpKWooYP/UE8kdTf6FMrL0BJohZ1DMQ33hdLr+qO9MM4wU9HtI+MjBKzOg4FvQwe1TlNLH/Q=";
	
	public static void main(String[] args) throws Exception {
		//生成公钥和私钥
		genKeyPair();
		//加密字符串
		
//		String message = "{\"name\":\"1\",\"password\":\"2\"}";
		String message = "{\r\n" + 
				"  \"feedbackContent\": \"string\",\r\n" + 
				"  \"feedbackId\": \"string\",\r\n" + 
				"  \"feedbackPicture\": \"string\",\r\n" + 
				"  \"userId\": \"123\",\r\n" + 
				"  \"userType\": \"1\"\r\n" + 
				"}";
//		System.out.println("随机生成的公钥为:" + keyMap.get(0));
//		System.out.println("随机生成的私钥为:" + keyMap.get(1));
		
		System.out.println("\t加密前的字符串为:" + message);
//		String messageEn = encrypt(message);
		String messageEn = rsaEncrypt(message);
		System.out.println("\t加密后的字符串为:" + messageEn);
//		String messageDe = decrypt(messageEn);
		String messageDe = rsaDecrypt(messageEn);
		System.out.println("\t还原后的字符串为:" + messageDe);
	}
	
	/** 
	 * 随机生成密钥对 
	 * @throws NoSuchAlgorithmException 
	 */  
	public static void genKeyPair() throws NoSuchAlgorithmException {  
		// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象  
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");  
		// 初始化密钥对生成器,密钥大小为96-1024位  
		keyPairGen.initialize(1024,new SecureRandom());  
		// 生成一个密钥对,保存在keyPair中  
		KeyPair keyPair = keyPairGen.generateKeyPair();  
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥  
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥  
		String publicKeyString = new String(Base64.getEncoder().encodeToString(publicKey.getEncoded()));  
		// 得到私钥字符串  
		String privateKeyString = new String(Base64.getEncoder().encodeToString(privateKey.getEncoded()));  
		// 将公钥和私钥保存到Map
		keyMap.put(0,publicKeyString);  //0表示公钥
		keyMap.put(1,privateKeyString);  //1表示私钥
	} 
	
	/** 
	 * RSA公钥加密 
	 *  
	 * @param str 
	 *            加密字符串
	 * @param publicKey 
	 *            公钥 
	 * @return 密文 
	 * @throws Exception 
	 *             加密过程中的异常信息 
	 */  
	public static String encrypt(String str) throws Exception{
		//base64编码的公钥
		byte[] decoded = Base64.getDecoder().decode(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.getEncoder().encodeToString(cipher.doFinal(str.getBytes("UTF-8")));
		return outStr;
	}
	
	/** 
	 * RSA私钥解密
	 *  
	 * @param str 
	 *            加密字符串
	 * @param privateKey 
	 *            私钥 
	 * @return 铭文
	 * @throws Exception 
	 *             解密过程中的异常信息 
	 */  
	public static String decrypt(String str) throws Exception{
		//64位解码加密后的字符串
		byte[] inputByte = Base64.getDecoder().decode(str.getBytes("UTF-8"));
		//base64编码的私钥
		byte[] decoded = Base64.getDecoder().decode(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;
	}
	
	//加密长度不超过117Byte,解密长度不超过128Byte
	//解密
	public static String rsaDecrypt(String input) {
	    String result = "";
		try {
		    // 将Base64编码后的公钥转换成PublicKey对象
			byte[] decoded = Base64.getDecoder().decode(privateKey);
			RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));  
			// 加密
			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.DECRYPT_MODE, priKey);
			byte[] inputArray = Base64.getDecoder().decode(input.getBytes("UTF-8"));
			int inputLength = inputArray.length;
			// 最大加密字节数,超出最大字节数需要分组加密
			int MAX_ENCRYPT_BLOCK = 128;
			// 标识
			int offSet = 0;
			byte[] resultBytes = {};
			byte[] cache = {};
			while (inputLength - offSet > 0) {
				if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
					cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
					offSet += MAX_ENCRYPT_BLOCK;
				} else {
					cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
					offSet = inputLength;
				}
				resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
				System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
			}
			result = new String(resultBytes);
		} catch (Exception e) {
			System.out.println("rsaEncrypt error:" + e.getMessage());
			result = input;
		}
		return result;
	}
	
	//加密长度不超过117Byte,解密长度不超过128Byte
	//加密
	public static String rsaEncrypt(String input) {
	    String result = "";
		try {
		    // 将Base64编码后的公钥转换成PublicKey对象
			byte[] buffer = Base64.getDecoder().decode(publicKey);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
			PublicKey publicKey = keyFactory.generatePublic(keySpec);
			// 加密
			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			byte[] inputArray = input.getBytes();
			int inputLength = inputArray.length;
			// 最大加密字节数,超出最大字节数需要分组加密
			int MAX_ENCRYPT_BLOCK = 117;
			// 标识
			int offSet = 0;
			byte[] resultBytes = {};
			byte[] cache = {};
			while (inputLength - offSet > 0) {
				if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
					cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
					offSet += MAX_ENCRYPT_BLOCK;
				} else {
					cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
					offSet = inputLength;
				}
				resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
				System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
			}
			result = Base64.getEncoder().encodeToString(resultBytes);
		} catch (Exception e) {
			System.out.println("rsaEncrypt error:" + e.getMessage());
		}
		return result;
	}
	

}

5.直接在需要加密的controller上加注解

 @RequestMapping(value = "/saveFeedbackInfo", method = RequestMethod.POST)
    @RsaParameter
    public ResponseResult<Boolean> saveFeedbackInfo(
            @RequestBody @Validated SJ0408_01_BO bo) {

        Boolean result = sj0408_01_Service.saveFeedbackInfo(bo);

        return ResponseResult.success(result);
    }

加密处理只对requestBody进行加密,特殊处理过,不加密也能执行。

6.有个简易的处理

弊端:Cipher提供加解密API,其中RSA非对称加密解密内容长度是有限制的,加密长度不超过117Byte,解密长度不超过128Byte,报错如下:javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes。
一、引入jar包

<dependency>  
    <groupId>cn.shuibo</groupId>  
    <artifactId>rsa-encrypt-body-spring-boot</artifactId>  
    <version>1.0.1.RELEASE</version>
</dependency>

二、启动类Application中添加@EnableSecurity注解
三、在application.yml或者application.properties中添加RSA公钥及私钥

rsa:
  encrypt:
      open: true # 是否开启加密 true  or  false    
      showLog: true # 是否打印加解密log true  or  false    
      publicKey: # RSA公钥    
      privateKey: # RSA私钥

四、在controller方法上加
@Encrypt 返回值进行加密
@Decrypt 传过来的加密参数解密

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值