How to Secure Spring Boot APIs with RSA Encryption: A Step‑by‑Step Guide
This article explains RSA encryption fundamentals, illustrates two practical scenarios, and walks through creating a Spring Boot project, adding Maven dependencies, configuring RSA keys, annotating controllers for automatic encryption/decryption, testing the endpoints, and handling client‑side encryption with JavaScript, while highlighting common pitfalls.
Project Overview
The demo encrypts API responses using RSA, ensuring that only holders of the private key can decrypt the data. Spring Boot annotations automate encryption and decryption of request/response bodies.
What Is RSA Encryption?
RSA is an asymmetric encryption algorithm that uses a public‑key/private‑key pair. The public key encrypts data, while only the private key can decrypt it. Because the keys are mathematically linked, breaking the encryption requires factoring a large integer, which is computationally infeasible.
Scenario 1 – Confidentiality
A generates a public/private key pair and keeps the private key secret.
A shares the public key with B.
B encrypts a message with A’s public key and sends it to A.
A decrypts the message with its private key.
Only two transmissions occur (public key and encrypted message), and an interceptor cannot read the content without the private key.
Scenario 2 – Integrity (Signature)
A generates a key pair.
A signs a message with its private key, producing a signature.
A sends the signed message to B.
B verifies the signature using A’s public key; a matching signature proves the message originated from A.
This protects against tampering but does not hide the message content.
Combined Use
In practice, both encryption and signing are applied: A encrypts the payload with B’s public key, then signs the ciphertext with A’s private key, guaranteeing confidentiality and integrity.
Implementation Steps
Create a Spring Boot project (e.g., springboot_api_encryption).
Add Maven dependency for the RSA encryption library:
<dependency>
<groupId>cn.shuibo</groupId>
<artifactId>rsa-encrypt-body-spring-boot</artifactId>
<version>1.0.1.RELEASE</version>
</dependency>Enable the security annotation in the main class:
@SpringBootApplication
@EnableSecurity
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}Configure RSA keys in application.yml (keys are generated separately):
rsa:
encrypt:
open: false # set true to enable encryption
showLog: true
publicKey: YOUR_PUBLIC_KEY
privateKey: YOUR_PRIVATE_KEYEncrypt a controller method by adding @Encrypt:
@Encrypt
@GetMapping("/encryption")
public TestBean encryption() {
TestBean bean = new TestBean();
bean.setName("shuibo.cn");
bean.setAge(18);
return bean;
}Test the endpoint (e.g., http://localhost:8080/encryption). With open: false the response is plain JSON; after setting open: true and restarting, the response is an RSA‑encrypted string, and the log shows encryption details.
Decryption Demo (Client‑Side)
For a front‑end built with Vue or plain JavaScript, use JSEncrypt to encrypt data before sending it to the server.
var PUBLIC_KEY = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A...';
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;
}
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); }
});
}On the server, add a decryption endpoint:
@PostMapping("/decryption")
@Decrypt
@ResponseBody
public String Decryption(@RequestBody User user) {
System.out.println(user);
return user.toString();
}When the client sends the encrypted payload, the server automatically decrypts it (thanks to @Decrypt) and returns the original object.
Key Pitfalls
Ensure contentType: "application/json;charset=utf-8" in AJAX requests; otherwise the server cannot parse the encrypted JSON.
The controller method must annotate the request body with @RequestBody for decryption to work.
Conclusion
By integrating RSA encryption into Spring Boot APIs and using client‑side JavaScript encryption, data transmitted over the network is protected from eavesdropping and tampering, providing a robust security layer for micro‑services and web applications.
Java Architect Handbook
Focused on Java interview questions and practical article sharing, covering algorithms, databases, Spring Boot, microservices, high concurrency, JVM, Docker containers, and ELK-related knowledge. Looking forward to progressing together with you.
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.
