How to Secure Spring Boot APIs with RSA Encryption: A Step‑by‑Step Guide

This article walks through the theory behind RSA, illustrates two battlefield‑style scenarios for encryption and signing, and then shows how to integrate RSA‑based request/response encryption into a Spring Boot application using Maven, annotations, configuration files, and a JavaScript front‑end, complete with code snippets and troubleshooting tips.

Architect
Architect
Architect
How to Secure Spring Boot APIs with RSA Encryption: A Step‑by‑Step Guide

Project Overview

Demo project encrypts API responses using RSA, preventing intercepted data from being read or tampered with. Source repository: https://github.com/pengziliu/GitHub-code-practice

RSA Basics

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, decryption with the private key; signing uses the private key, verification uses the public key. Security relies on the difficulty of factoring a large integer.

Illustrative Scenarios

Scenario 1 – Confidentiality: A generates a key pair, shares the public key with B, B encrypts a command with A’s public key, and A decrypts it with the private key. Even if both transmissions are intercepted, the attacker cannot read the command because only A’s private key can decrypt it.

Scenario 2 – Integrity: A signs a reply with its private key, B verifies the signature with A’s public key. Interception cannot forge a valid signature, so B knows the reply truly originates from A.

In practice, both confidentiality and integrity are needed, so a typical flow encrypts the payload with the receiver’s public key and then signs the ciphertext with the sender’s private key.

Implementation Steps (Spring Boot)

1. Create Maven Project

Project name 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 Security 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 true to enable encryption
    showLog: true
    publicKey: # RSA public key generated by tool
    privateKey: # RSA private key generated by tool

5. Annotate Controller Methods for Encryption

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

When open is true, the response body is automatically encrypted.

6. Annotate Controller Methods for Decryption

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

The @Decrypt annotation tells the framework to decrypt the request payload before binding.

7. Test the Endpoints

Request http://localhost:8080/encryption before enabling encryption returns plain JSON. After setting open: true and restarting, the same request returns an encrypted string.

Front‑End Encryption (JavaScript)

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 a helper function:

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('Plain data:', 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); }
    });
}

Clicking the button that calls tijiao() sends the RSA‑encrypted JSON to the back‑end, which decrypts it and returns the original object.

Common Pitfalls

Set contentType: "application/json;charset=utf-8" in the AJAX request; otherwise the server cannot bind the payload.

The controller method must use @RequestBody to receive the decrypted object.

Conclusion

By integrating RSA encryption/decryption annotations, configuring keys, and using a simple JavaScript library on the client, API data can be protected against eavesdropping and tampering. The approach works for any Spring Boot service that needs secure communication.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring BootRSAencryptionBackend Securityapi-encryption
Architect
Written by

Architect

Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.