Quickly Secure Spring Boot APIs with RSA Encryption
This article walks through the fundamentals of RSA encryption, illustrates two communication scenarios, and provides a step‑by‑step guide to add RSA‑based request/response encryption to a Spring Boot project—including Maven setup, annotation usage, key configuration, front‑end JavaScript encryption, testing, and common pitfalls.
Introduction
In many projects data security is ensured by encrypting the payload transmitted over APIs. This guide demonstrates how to quickly add RSA‑based encryption to a Spring Boot application using a ready‑made library.
What is RSA Encryption
RSA is an asymmetric encryption algorithm that uses a public‑key/private‑key pair. The public key can be shared openly, while the private key remains secret. Encryption is performed with the public key and decryption (or signing) with the private key, making it suitable for protecting API data.
Scenario 1 – Confidential Message
A generates a key pair, publishes the public key, and B encrypts a command with A’s public key.
A receives the ciphertext and decrypts it with the private key.
Only two transmissions occur (public key and encrypted message), and an eavesdropper cannot recover the plaintext.
Scenario 2 – Message Integrity
A signs a message with its private key and sends both the message and signature to B.
B verifies the signature using A’s public key, confirming the message originated from A.
This prevents tampering but does not hide the message content.
Implementation Steps
1. Create a Spring Boot Project
Initialize a new project (e.g., springboot_api_encryption).
2. Add Maven Dependency
<dependency>
<groupId>cn.shuibo</groupId>
<artifactId>rsa-encrypt-body-spring-boot</artifactId>
<version>1.0.1.RELEASE</version>
</dependency>3. Enable Encryption Annotation
@SpringBootApplication
@EnableSecurity
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}4. Configure Keys in application.yml
rsa:
encrypt:
open: false # set to true to enable encryption
showLog: true
publicKey: # RSA public key generated by the tool
privateKey: # RSA private key generated by the tool5. Encrypt Controller Responses
@Encrypt
@GetMapping("/encryption")
public TestBean encryption() {
TestBean bean = new TestBean();
bean.setName("shuibo.cn");
bean.setAge(18);
return bean;
}6. Decrypt Incoming Requests
@PostMapping("/decryption")
@Decrypt
@ResponseBody
public String decryption(@RequestBody User user) {
System.out.println(user);
return user.toString();
}7. Test the Endpoints
When open is false, the /encryption endpoint returns plain JSON. After setting open: true and restarting, the response is encrypted (visible in the log as ciphertext).
8. Front‑End Encryption (JavaScript)
Include jQuery and JSEncrypt libraries, then encrypt data before sending:
var PUBLIC_KEY = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...';
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); }
});
}9. Logs
Both encryption and decryption logs are printed when showLog is enabled, helping to verify the ciphertext and the successful decryption on the server side.
Pitfalls and Tips
Ensure the AJAX request sets contentType: "application/json;charset=utf-8" so the server treats the payload correctly.
The controller method that receives encrypted data must be annotated with @Decrypt and accept the request body via @RequestBody.
The demo project on Gitee may not be directly runnable; the key part is the front‑end encryption flow.
Conclusion
By adding RSA encryption to Spring Boot APIs, data can be protected from eavesdropping and tampering. The combination of server‑side annotations and client‑side JSEncrypt provides a lightweight yet effective security layer for any Java‑based backend.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IoT Full-Stack Technology
Dedicated to sharing IoT cloud services, embedded systems, and mobile client technology, with no spam ads.
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.
