网上有好多通过aop切面以及自定义的RSA工具类进行加密解密的方法,期中的过程繁琐也不好用,博主研究了一天从网上到了超好用的基于Springboot框架实现的接口RSA加密解密方式,通过rsa-encrypt-body-spring-boot实现了对Spring Boot接口返回值、参数值通过注解的方式自动加解密。注意:rsa-encrypt-body-spring-boot是某一个大神写的工具类上传到了maven库中,大家引用即可
一、引入rsa-encrypt-body-spring-boot
<dependency>
<groupid>cn.shuibo</groupid>
<artifactid>rsa-encrypt-body-spring-boot</artifactid>
<version>1.0.1.RELEASE</version>
</dependency>
二、启动类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.<init>(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();
}
返回结果加密——运行结果:
文章来源地址https://www.toymoban.com/news/detail-535307.html文章来源:https://www.toymoban.com/news/detail-535307.html
到了这里,关于Springboot接口返回参数以及入参RSA加密解密的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!