Implementing RSA Encryption for Spring Boot API Requests and Responses
This article demonstrates how to secure Spring Boot API data using RSA asymmetric encryption, covering the theory of RSA, step‑by‑step project setup, Maven dependencies, annotations for automatic encryption/decryption, Java and JavaScript client implementations, and practical testing of encrypted endpoints.
In many projects data security is achieved by encrypting transmitted data; common algorithms include symmetric AES and asymmetric RSA. This tutorial uses a simple RSA‑encryption Spring Boot project from Gitee to illustrate the whole process.
Project Overview – The project encrypts API responses with RSA, making the data unreadable without the private key. Encryption and decryption are applied automatically via custom annotations.
What is RSA? – RSA is an asymmetric encryption scheme that uses a public‑key/private‑key pair. The public key encrypts data, while only the matching private key can decrypt it. RSA also supports digital signatures, where the private key signs and the public key verifies.
Two illustrative scenarios are described: (1) a sender encrypts a message with the receiver’s public key; (2) a sender signs a message with its private key and the receiver verifies the signature with the sender’s public key. The guide explains why combining encryption and signing provides both confidentiality and integrity.
Encryption Practice
Preparation
1. Create a Spring Boot project named springboot_api_encryption .
2. Add the following Maven dependency:
<dependency>
<groupId>cn.shuibo</groupId>
<artifactId>rsa-encrypt-body-spring-boot</artifactId>
<version>1.0.1.RELEASE</version>
</dependency>3. Add @EnableSecurity to the main application class:
@SpringBootApplication
@EnableSecurity
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}4. Configure RSA keys in application.yml (keys are generated separately):
rsa:
encrypt:
open: false # set true to enable encryption
showLog: true
publicKey: # RSA public key generated by a tool
privateKey: # RSA private key generated by a tool5. Annotate controller methods with @Encrypt to encrypt responses:
@Encrypt
@GetMapping("/encryption")
public TestBean encryption() {
TestBean testBean = new TestBean();
testBean.setName("shuibo.cn");
testBean.setAge(18);
return testBean;
}6. Annotate methods with @Decrypt to decrypt incoming payloads:
@Decrypt
@PostMapping("/decryption")
public String Decryption(@RequestBody TestBean testBean) {
return testBean.toString();
}After setting open: true in the YAML file and restarting the application, the /encryption endpoint returns encrypted data.
Front‑end Decryption
Include jQuery and JSEncrypt libraries:
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jsencrypt/3.0.0-rc.1/jsencrypt.js"></script>Define the RSA public key and an encryption helper:
var PUBLIC_KEY = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAobhGH4WM...';
function RSA_encryption(jsonData) {
var encrypt = new JSEncrypt();
encrypt.setPublicKey('-----BEGIN PUBLIC KEY-----' + PUBLIC_KEY + '-----END PUBLIC KEY-----');
var encrypted = encrypt.encrypt(JSON.stringify(jsonData));
console.log('Encrypted data:', encrypted);
return encrypted;
}Submit encrypted data via AJAX:
function tijiao() {
var str = {"name":"1223334","password":"asd",age:1};
$.ajax({
url: "/decryption",
type: "POST",
contentType: "application/json;charset=utf-8",
data: RSA_encryption(str),
success: function(data) { alert(data); }
});
}A minimal HTML page ties everything together:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>RSA Demo</title>
</head>
<body>
加密传后端,后端解密
<button id="jiami" onclick="tijiao()">加密传后端</button>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jsencrypt/3.0.0-rc.1/jsencrypt.js"></script>
<script>
// JavaScript code from above (PUBLIC_KEY, RSA_encryption, tijiao)
</script>
</body>
</html>Testing the endpoints shows that without the public/private keys the data cannot be read, confirming that RSA encryption effectively protects API traffic.
Conclusion
The tutorial proves that by adding RSA public and private keys and using the provided annotations, Spring Boot APIs can be secured against eavesdropping and tampering. It also highlights practical tips such as setting the correct contentType for AJAX requests and ensuring the controller method uses @RequestBody for decryption.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.