Quickly Implement API Encryption in Spring Boot with a Single Library

This article walks through using RSA to encrypt Spring Boot API responses, covering the theory behind RSA, two security scenarios, Maven dependency setup, configuration, controller annotations, encryption/decryption code, a front‑end JavaScript example, common pitfalls, and a final security summary.

Architect's Guide
Architect's Guide
Architect's Guide
Quickly Implement API Encryption in Spring Boot with a Single Library

Project Overview

Demonstrates securing Spring Boot API responses by encrypting payloads with RSA. Encrypted data cannot be read without the private key.

RSA Encryption Basics

RSA is an asymmetric algorithm that uses a public‑key/private‑key pair. The public key encrypts data; only the holder of the private key can decrypt it. The same key pair can be used for digital signatures (private‑key signing, public‑key verification).

Confidentiality Scenario

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 the private key.

Integrity (Signature) Scenario

A generates a public/private key pair.

A signs a message with the private key and sends both the signature and the original message to B.

B retrieves A’s public key and verifies the signature; a matching result proves the message originated from A.

Implementation Steps

1. Create a Spring Boot 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 the security annotation

@SpringBootApplication
@EnableSecurity
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

4. Configure RSA keys (application.yml)

rsa:
  encrypt:
    open: false   # set true to enable encryption
    showLog: true
    publicKey:   # generated public key (PEM format without header/footer)
    privateKey:  # generated private key (PEM format without header/footer)

5. Encrypt a controller method

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

When open is false, the endpoint returns plain JSON. Setting open: true and restarting the application causes the response to be RSA‑encrypted.

6. Decrypt incoming data

@Decrypt
@PostMapping("/decryption")
@ResponseBody
public String decryption(@RequestBody User user) {
    System.out.println(user);
    return user.toString();
}

7. Front‑end JavaScript encryption

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); }
    });
}

Include jQuery and JSEncrypt libraries before the script.

8. Common Pitfalls

Ensure contentType: "application/json;charset=utf-8" is set in the AJAX request.

The controller method must be annotated with @RequestBody to receive the encrypted payload.

Demonstration

Request URL: http://localhost:8080/encryption Before enabling encryption ( open: false) the response is plain JSON, e.g.: {"name":"shuibo.cn","age":18} After setting open: true the response becomes a base64‑encoded RSA ciphertext, e.g.: "Y3J5cHRlZCBlbmNyeXB0ZWQgZGF0YQ==" Encryption and decryption logs are printed when showLog: true.

Source Code

Full source code is available at the following repository URL (plain text, no hyperlink):

https://github.com/pengziliu/GitHub-code-practice

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.

BackendJavaSpring BootSecurityRSAencryptionapi-encryption
Architect's Guide
Written by

Architect's Guide

Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.

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.