Information Security 12 min read

RSA Encryption and Decryption in Spring Boot – A Practical Guide

This article explains the principles of RSA asymmetric encryption, illustrates two communication scenarios, and provides a step‑by‑step Spring Boot implementation with Maven dependencies, configuration, annotations, and front‑end JavaScript code to encrypt API requests and decrypt responses, helping developers secure their APIs.

Top Architect
Top Architect
Top Architect
RSA Encryption and Decryption in Spring Boot – A Practical Guide

In modern projects data security often relies on encryption, and RSA is a widely used asymmetric algorithm. The article first introduces RSA, describing its public‑key/private‑key mechanism and the mathematical difficulty of factoring large integers that guarantees security.

Project Overview

The demo uses a Spring Boot application to encrypt API responses and decrypt incoming requests automatically via annotations.

RSA Basics

RSA uses a key pair: the public key encrypts data, while the private key decrypts it. It can also be used for digital signatures, where the private key signs and the public key verifies, ensuring both confidentiality and integrity.

Two Communication Scenarios

Scenario 1: A sends a public key to B, B encrypts a command with the public key, and A decrypts it with the private key.

Scenario 2: A signs a reply with its private key; B verifies the signature with A’s public key.

Both scenarios highlight the need to combine encryption and signing for full protection.

Practical Implementation

1. Create a Spring Boot project

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 RSA keys in application.yml

rsa:
  encrypt:
    open: true
    showLog: true
    publicKey: # RSA public key generated by tool
    privateKey: # RSA private key generated by tool

5. Annotate controller methods

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

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

6. Front‑end JavaScript encryption using JSEncrypt

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 submit() {
    var data = {name: '1223334', password: 'asd', age: 1};
    $.ajax({
        url: '/decryption',
        type: 'POST',
        contentType: 'application/json;charset=utf-8',
        data: RSA_encryption(data),
        success: function(res) { alert(res); }
    });
}

After setting open: true in the configuration, the API returns encrypted JSON; disabling it returns plain data. Logs show the encryption process.

Summary

The guide demonstrates that without the RSA key pair an attacker cannot decrypt or forge API traffic, providing strong protection against packet sniffing and tampering. Combining encryption with digital signatures further ensures data integrity.

JavaSpring BootRSAencryptionAPI securitydecryption
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login 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.