SoFunction
Updated on 2025-04-05

Practical record of encryption and decryption function built by Spring Boot Security API

1. Description

In the current digital era, data security has become a key area that enterprises must not ignore. In order to ensure the firm security of data transmission, encrypting the API interface has become an indispensable part. This article will explain how to quickly implement API encryption in Spring Boot 3.3 environment, and specifically use RSA asymmetric encryption algorithm to explain it.

1. Choose the right encryption algorithm

  • Symmetric encryption:For example, AES (Advanced Encryption Standard), is suitable for fast encryption and decryption of large amounts of data, but requires the management of keys securely.
  • Asymmetric encryption:For example, RSA (Rivest-Shamir-Adleman), public keys and private key pairs are used, public keys are used for encryption, and private keys are used for decryption, which is suitable for encrypting a small amount of data and key exchange.

2. Key management

  • Generate a strong key:Use a secure random number generator to generate keys to ensure the randomness and strength of the keys.
  • Secure storage:Store the key in a secure place, such as a key management system or an encrypted configuration file. Avoid hard-code the keys in the code.
  • Key Update: Update the key regularly to reduce the risk of the key being cracked.

3. Data encryption

  • Encrypt sensitive data:Such as user passwords, personal information, etc., are encrypted during storage and transmission.
  • End-to-end encryption:If possible, end-to-end encryption is implemented to ensure that the data is encrypted throughout the transmission process and can only be decrypted by the sender and receiver.
  • Encrypted transmission:Use HTTPS to ensure the security of data during network transmission. Spring Boot 3 makes it easy to configure HTTPS.

4. Prevent encryption vulnerabilities

  • Avoid weak encryption algorithms:Do not use cracked or unsafe encryption algorithms.
  • Prevent encryption misconfiguration:Carefully configure encryption libraries and frameworks to avoid security vulnerabilities caused by incorrect configurations.
  • Enter verification:Strict verification of encrypted inputs to prevent malicious input from causing encryption failures or security vulnerabilities.

5. Security logging

  • Log encryption related events:Such as key generation, encryption and decryption operations, etc., for auditing and troubleshooting.
  • Protect log security:Ensure the secure storage of log files and prevent sensitive information from being leaked.

6. Testing and monitoring

  • Safety Test:Perform security testing, including testing of encryption functions, to ensure the correctness and security of encryption.
  • Monitoring exception:Monitor encryption-related abnormal situations, such as encryption failure, key leakage, etc., and take timely measures.

2. RSA encryption and decryption implementation steps

The first way to write

1. Configure Spring Boot's dependencies

Here is a basic file:

<project xmlns="/POM/4.0.0"  
         xmlns:xsi="http:///2001/XMLSchema-instance"  
         xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.">  
    <modelVersion>4.0.0</modelVersion>  
    <groupId></groupId>  
    <artifactId>spring-boot-rsa</artifactId>  
    <version>0.0.1-SNAPSHOT</version>  
    <packaging>jar</packaging>  
    <name>spring-boot-rsa</name>  
    <description>Demo project for Spring Boot RSA encryption and decryption</description>  
    <parent>  
        <groupId></groupId>  
        <artifactId>spring-boot-starter-parent</artifactId>  
        <version>3.0.0</version>  
        <relativePath/> <!-- lookup parent from repository -->  
    </parent>  
    <dependencies>  
        <dependency>  
            <groupId></groupId>  
            <artifactId>spring-boot-starter-web</artifactId>  
        </dependency>  
        <dependency>  
            <groupId></groupId>  
            <artifactId>spring-boot-starter-test</artifactId>  
            <scope>test</scope>  
        </dependency>  
        <!-- Other dependencies can be added as needed -->  
    </dependencies>  
    <build>  
        <plugins>  
            <plugin>  
                <groupId></groupId>  
                <artifactId>spring-boot-maven-plugin</artifactId>  
            </plugin>  
        </plugins>  
    </build>  
</project>

2. Configure the RSA key

First, inConfiguration in the fileRSAPublic and private keys。 Note that since the keys can be long, you may need to wrap lines properly or use YAML's multi-line string syntax.

rsa:  
    open: true          # Whether to enable encryption    showLog: true       # Whether to print the encrypted and decrypted log    publicKey: 'Your RSA public key'  # RSA public key, software generation    privateKey: 'Your RSA private key'  # RSAPrivate key,Software generation

Note: In practical applications, please do not hardcode the key in configuration files, especially the private key. A more secure way to manage keys, such as environment variables, key management services (KMS), or secure configuration file storage.

3. Read the configuration and initialize the key

Next, read these configurations in the Spring Boot application and initialize the RSA key.

import ;  
import ;  
import ;  
import ;  
import ;  
import ;  
import .PKCS8EncodedKeySpec;  
import .X509EncodedKeySpec;  
import .Base64;  
@Configuration  
public class RsaConfig {  
    @Value("${}")  
    private String publicKey;  
    @Value("${}")  
    private String privateKey;  
    @Bean  
    public PublicKey rsaPublicKey() throws Exception {  
        byte[] keyBytes = ().decode(());  
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);  
        KeyFactory kf = ("RSA");  
        return (spec);  
    }  
    @Bean  
    public PrivateKey rsaPrivateKey() throws Exception {  
        byte[] keyBytes = ().decode(());  
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);  
        KeyFactory kf = ("RSA");  
        return (spec);  
    }  
}

4. Encrypt and decrypt using RSA key

Now you can use these keys in the service class for encryption and decryption operations.

import ;  
import ;  
import ;  
import ;  
import ;  
import .Base64;  
@Service  
public class RsaService {  
    private final PublicKey publicKey;  
    private final PrivateKey privateKey;  
    @Autowired  
    public RsaService(PublicKey publicKey, PrivateKey privateKey) {  
         = publicKey;  
         = privateKey;  
    }  
    public String encrypt(String data) throws Exception {  
        Cipher cipher = ("RSA");  
        (Cipher.ENCRYPT_MODE, publicKey);  
        byte[] encryptedBytes = (());  
        return ().encodeToString(encryptedBytes);  
    }  
    public String decrypt(String encryptedData) throws Exception {  
        Cipher cipher = ("RSA");  
        (Cipher.DECRYPT_MODE, privateKey);  
        byte[] decryptedBytes = (().decode(encryptedData));  
        return new String(decryptedBytes);  
    }  
}

5. Test encryption and decryption

Finally, you can write a simple controller or test class to verify that the encryption and decryption functions work properly.

import ;  
import ;  
import ;  
import ;  
@RestController  
public class RsaController {  
    private final RsaService rsaService;  
    @Autowired  
    public RsaController(RsaService rsaService) {  
         = rsaService;  
    }  
    @GetMapping("/encrypt")  
    public String encrypt(@RequestParam String data) throws Exception {  
        return (data);  
    }  
    @GetMapping("/decrypt")  
    public String decrypt(@RequestParam String encryptedData) throws Exception {  
        return (encryptedData);  
    }  
}

Now you can launch the Spring Boot app and access it through/encryptand/decryptEndpoints to test RSA encryption and decryption capabilities. Make sure to use the appropriate key pair during testing and do not expose the private key in production.

The second way to write

1. Create RSA tool class

Create an RSA tool class to handle encryption and decryption operations. This class will contain methods to generate key pairs, encryption, and decryption.

package ;  
import ;  
import ;  
import ;  
import ;  
import ;  
import ;  
import .PKCS8EncodedKeySpec;  
import .X509EncodedKeySpec;  
import .Base64;  
public class RSAUtil {  
    // Generate key pair    public static KeyPair generateKeyPair() throws Exception {  
        KeyPairGenerator keyGen = ("RSA");  
        (2048);  
        return ();  
    }  
    // Public key encryption    public static String encrypt(String data, PublicKey publicKey) throws Exception {  
        Cipher cipher = ("RSA");  
        (Cipher.ENCRYPT_MODE, publicKey);  
        byte[] encryptedBytes = (("UTF-8"));  
        return ().encodeToString(encryptedBytes);  
    }  
    // Decrypt the private key    public static String decrypt(String encryptedData, PrivateKey privateKey) throws Exception {  
        Cipher cipher = ("RSA");  
        (Cipher.DECRYPT_MODE, privateKey);  
        byte[] decryptedBytes = (().decode(encryptedData));  
        return new String(decryptedBytes, "UTF-8");  
    }  
    // Public key string representation    public static String getPublicKeyString(PublicKey publicKey) {  
        return ().encodeToString(());  
    }  
    // Private key string representation    public static String getPrivateKeyString(PrivateKey privateKey) {  
        return ().encodeToString(());  
    }  
    // Rebuild the public key from the string    public static PublicKey getPublicKeyFromString(String key) throws Exception {  
        byte[] keyBytes = ().decode(key);  
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);  
        KeyFactory keyFactory = ("RSA");  
        return (spec);  
    }  
    // Rebuild the private key from the string    public static PrivateKey getPrivateKeyFromString(String key) throws Exception {  
        byte[] keyBytes = ().decode(key);  
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);  
        KeyFactory keyFactory = ("RSA");  
        return (spec);  
    }  
}

2. Create Spring Boot Controller

Create a simple Spring Boot controller to demonstrate how to use RSA encryption and decryption

package ;  
import ;  
import .*;  
import ;  
@RestController  
@RequestMapping("/api")  
public class RSAController {  
    private KeyPair keyPair;  
    public RSAController() throws Exception {  
         = ();  
    }  
    @GetMapping("/encrypt")  
    public String encrypt(@RequestParam String data) throws Exception {  
        return (data, ());  
    }  
    @GetMapping("/decrypt")  
    public String decrypt(@RequestParam String encryptedData) throws Exception {  
        return (encryptedData, ());  
    }  
    @GetMapping("/publicKey")  
    public String getPublicKey() {  
        try {  
            return (());  
        } catch (Exception e) {  
            ();  
            return null;  
        }  
    }  
    @GetMapping("/privateKey")  
    public String getPrivateKey() {  
        try {  
            return (());  
        } catch (Exception e) {  
            ();  
            return null;  
        }  
    }  
}

3. Test RSA encryption and decryption

Now you can run the Spring Boot application and test RSA encryption and decryption by accessing the following endpoints:

  • Get the public keyGET /api/publicKey
  • Get the private keyGET /api/privateKey(Please note that in production environment, the private key should be kept confidential)
  • Encrypted dataGET /api/encrypt?data=yourData
  • Decrypt the dataGET /api/decrypt?encryptedData=yourEncryptedData

3. AES encryption and decryption implementation steps

1. Create a Spring Boot project

You can use Spring Initializr to create a new Spring Boot project, select the following dependencies:

<project xmlns="/POM/4.0.0"  
         xmlns:xsi="http:///2001/XMLSchema-instance"  
         xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.">  
    <modelVersion>4.0.0</modelVersion>  
    <groupId></groupId>  
    <artifactId>spring-boot-rsa</artifactId>  
    <version>0.0.1-SNAPSHOT</version>  
    <packaging>jar</packaging>  
    <name>spring-boot-rsa</name>  
    <description>Demo project for Spring Boot RSA encryption and decryption</description>  
    <parent>  
        <groupId></groupId>  
        <artifactId>spring-boot-starter-parent</artifactId>  
        <version>3.0.0</version>  
        <relativePath/> <!-- lookup parent from repository -->  
    </parent>  
    <dependencies>  
        <dependency>  
            <groupId></groupId>  
            <artifactId>spring-boot-starter-web</artifactId>  
        </dependency>  
        <dependency>  
            <groupId></groupId>  
            <artifactId>spring-boot-starter-test</artifactId>  
            <scope>test</scope>  
        </dependency>  
        <!-- Other dependencies can be added as needed -->  
    </dependencies>  
    <build>  
        <plugins>  
            <plugin>  
                <groupId></groupId>  
                <artifactId>spring-boot-maven-plugin</artifactId>  
            </plugin>  
        </plugins>  
    </build>  
</project>

2. Add AES encryption and decryption tool class

First, we need a tool class to handle AES encryption and decryption operations.

package ;  
import ;  
import ;  
import ;  
import ;  
import .Base64;  
public class AESUtil {  
    // Generate AES key    public static SecretKey generateKey(int n) throws Exception {  
        KeyGenerator keyGenerator = ("AES");  
        (n);  
        SecretKey secretKey = ();  
        return secretKey;  
    }  
    // Convert key to string    public static String encodeKey(SecretKey key) {  
        return ().encodeToString(());  
    }  
    // Convert string to key    public static SecretKey decodeKey(String encodedKey) {  
        byte[] decodedKey = ().decode(encodedKey);  
        return new SecretKeySpec(decodedKey, 0, , "AES");  
    }  
    // Encryption    public static String encrypt(String data, SecretKey key) throws Exception {  
        Cipher cipher = ("AES");  
        (Cipher.ENCRYPT_MODE, key);  
        byte[] encryptedData = (("UTF-8"));  
        return ().encodeToString(encryptedData);  
    }  
    // Decrypt    public static String decrypt(String encryptedData, SecretKey key) throws Exception {  
        Cipher cipher = ("AES");  
        (Cipher.DECRYPT_MODE, key);  
        byte[] decodedData = ().decode(encryptedData);  
        byte[] decryptedData = (decodedData);  
        return new String(decryptedData, "UTF-8");  
    }  
}

3. Create a controller to handle encryption and decryption requests

Next, we create a Spring Boot controller to handle encryption and decryption requests.

package ;  
import ;  
import .*;  
import ;  
import ;  
import ;  
@RestController  
@RequestMapping("/api")  
public class AESController {  
    // Variables used to store keys (in actual applications, the keys should be stored securely)    private static SecretKey secretKey;  
    static {  
        try {  
            secretKey = (256); // 256-bit AES key        } catch (Exception e) {  
            ();  
        }  
    }  
    @GetMapping("/encrypt")  
    public Map<String, String> encrypt(@RequestParam String data) {  
        Map<String, String> response = new HashMap<>();  
        try {  
            String encryptedData = (data, secretKey);  
            ("encryptedData", encryptedData);  
        } catch (Exception e) {  
            ("error", ());  
        }  
        return response;  
    }  
    @GetMapping("/decrypt")  
    public Map<String, String> decrypt(@RequestParam String encryptedData) {  
        Map<String, String> response = new HashMap<>();  
        try {  
            String decryptedData = (encryptedData, secretKey);  
            ("decryptedData", decryptedData);  
        } catch (Exception e) {  
            ("error", ());  
        }  
        return response;  
    }  
    @GetMapping("/key")  
    public Map<String, String> getKey() {  
        Map<String, String> response = new HashMap<>();  
        try {  
            String encodedKey = (secretKey);  
            ("encodedKey", encodedKey);  
        } catch (Exception e) {  
            ("error", ());  
        }  
        return response;  
    }  
}

4. Launch the Spring Boot application

Make sure yoursorThe file is configured correctly and then run the Spring Boot application.

5. Test API

You can use a browser or tool such as Postman to test these APIs.

  • Get the key: GET http://localhost:8080/api/key
  • Encrypted data: GET http://localhost:8080/api/encrypt?data=HelloWorld
  • Decrypted data: GET http://localhost:8080/api/decrypt?encryptedData=<Base64EncodedEncryptedData>

Things to note

  • Key Management: In practical applications, keys should be stored and managed safely, and should not be hard-coded in code.
  • Exception handling: In production code, there should be a more complete exception handling mechanism.
  • HTTPS: Make sure your API communicates over HTTPS to protect the data in transit.

This is the article about Spring Boot Security API Construction: Excellent Practice of Encryption and Decryption Function. For more relevant Spring Boot API encryption and decryption content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!