Springboot接口返回参数以及入参RSA加密解密

网上有好多通过aop切面以及自定义的RSA工具类进行加密解密的方法,期中的过程繁琐也不好用,博主研究了一天从网上到了超好用的基于Springboot框架实现的接口RSA加密解密方式,通过rsa-encrypt-body-spring-boot实现了对Spring Boot接口返回值、参数值通过注解的方式自动加解密。注意:rsa-encrypt-body-spring-boot是某一个大神写的工具类上传到了maven库中,大家引用即可

一、引入rsa-encrypt-body-spring-boot


  cn.shuibo
  rsa-encrypt-body-spring-boot
  1.0.1.RELEASE

二、启动类Application中添加@EnableSecurity注解

@SpringBootApplication
@EnableCaching
@MapperScan("com.ujia")
@EnableScheduling
@EnableSecurity
public class RestApplication {
    public static void main(String[] args) {
        SpringApplication.run(RestApplication.class, args);
    }

}

三、在application.yml或者application.properties中添加RSA公钥及私钥

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

 补充知识:rsa公钥私钥生成命令,在电脑文件夹中打开命令框依次执行

openssl
# 生成私钥
genrsa -out id_rsa_private 2048
# 生成私钥(把RSA私钥转换成PKCS8格式)
pkcs8 -topk8 -inform PEM -in id_rsa_private -outform pem -nocrypt -out id_rsa_private_pkcs
# 生成公钥
rsa -in id_rsa_private -pubout -out id_rsa_public.pub

重点注意:生成的私钥一定要转成pkcs8,否则会报错

Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
	at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
	at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
	at com.hashland.otc.common.util.coder.RSACoder.sign(RSACoder.java:42)
	at com.hashland.otc.common.util.coder.RSACoder.main(RSACoder.java:306)
Caused by: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
	at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:352)
	at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:357)
	at sun.security.rsa.RSAPrivateCrtKeyImpl.(RSAPrivateCrtKeyImpl.java:91)
	at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75)
	at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316)
	at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213)
	... 3 more

四、对返回值进行加密

@Encrypt
@GetMapping("/encryption")
public TestBean encryption(){
    TestBean testBean = new TestBean();
    testBean.setName("shuibo.cn");
    testBean.setAge(18);
    return testBean;
}

五、对参数进行解密

@Decrypt
@PostMapping("/decryption")
public String Decryption(@RequestBody TestBean testBean){
    return testBean.toString();
}

返回结果加密——运行结果:

Springboot接口返回参数以及入参RSA加密解密_第1张图片

 

 

你可能感兴趣的:(spring,boot,spring,java)