Skip to main content

Working with Bouncy Castle Library - Encryption & Decryption

CODERZ DUNIYA / ENGINEERING LAB
ENGINEERING INSIGHT

Working with Bouncy Castle Library - Encryption & Decryption

Practical engineering insight from Coderz Duniya.

Why encryption, and why Bouncy Castle?

Encryption turns readable data into ciphertext that only a key holder can reverse. Bouncy Castle is an open-source crypto library that plugs into Java's standard Cipher API as the BC provider. Here we build a small Spring Boot API that encrypts and decrypts text with AES-256-GCM, which also detects tampering.

Step 1: Create the project

Create a Maven project on start.spring.io with Java 17+, Spring Boot 4.1.2 and Spring Web. Then add Bouncy Castle to pom.xml:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk18on</artifactId>
    <version>1.85.2</version>
</dependency>

Step 2: Set the secret key

Generate a 256-bit key and keep it out of your source code:

export APP_CRYPTO_KEY=$(openssl rand -base64 32)

Add this line to application.properties:

app.crypto.key=${APP_CRYPTO_KEY}

Step 3: Write the encryption service

CryptoService.java (keep both classes in the same package as your main application class):

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class CryptoService {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private static final int IV_BYTES = 12;
    private final SecureRandom random = new SecureRandom();
    private final SecretKey key;

    public CryptoService(@Value("${app.crypto.key}") String base64Key) {
        byte[] bytes = Base64.getDecoder().decode(base64Key);
        if (bytes.length != 32) {
            throw new IllegalStateException("Key must be 32 bytes");
        }
        this.key = new SecretKeySpec(bytes, "AES");
    }

    public String encrypt(String text) throws GeneralSecurityException {
        byte[] iv = new byte[IV_BYTES];
        random.nextBytes(iv); // new IV for every message
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
        byte[] data = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
        byte[] out = ByteBuffer.allocate(IV_BYTES + data.length).put(iv).put(data).array();
        return Base64.getEncoder().encodeToString(out);
    }

    public String decrypt(String encoded) throws GeneralSecurityException {
        byte[] in = Base64.getDecoder().decode(encoded);
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
        cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, in, 0, IV_BYTES));
        byte[] plain = cipher.doFinal(in, IV_BYTES, in.length - IV_BYTES);
        return new String(plain, StandardCharsets.UTF_8);
    }
}

Step 4: Expose REST endpoints

CryptoController.java:

import java.security.GeneralSecurityException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class CryptoController {
    record Payload(String text) {}

    private final CryptoService crypto;

    public CryptoController(CryptoService crypto) {
        this.crypto = crypto;
    }

    @PostMapping("/encrypt")
    Payload encrypt(@RequestBody Payload body) throws GeneralSecurityException {
        return new Payload(crypto.encrypt(body.text()));
    }

    @PostMapping("/decrypt")
    Payload decrypt(@RequestBody Payload body) throws GeneralSecurityException {
        return new Payload(crypto.decrypt(body.text()));
    }

    @ExceptionHandler({GeneralSecurityException.class, IllegalArgumentException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    String badInput() {
        return "Invalid or tampered input";
    }
}

Step 5: Run and test

./mvnw spring-boot:run

In a second terminal:

curl -X POST localhost:8080/api/encrypt \
  -H "Content-Type: application/json" -d '{"text":"Hello CoderzDuniya"}'

curl -X POST localhost:8080/api/decrypt \
  -H "Content-Type: application/json" -d '{"text":"PASTE_ENCRYPTED_TEXT"}'

Best practices

  • Never reuse an IV with the same key.
  • Store keys in a secrets manager or KMS in production.
  • Secure these endpoints with authentication and HTTPS. An open decrypt API defeats the encryption.
  • Hash user passwords (Argon2 or bcrypt) instead of encrypting them.
  • Keep Bouncy Castle updated for security fixes.

I'd love to hear your experience in the comments.


𝐼𝒻 π“Žπ‘œπ“Š π“Œπ‘œπ“Šπ“π’Ή 𝓁𝒾𝓀𝑒 π“‰π‘œ π’Έπ‘œπ“ƒπ“‰π“‡π’Ύπ’·π“Šπ“‰π‘’, 𝓅𝓁𝓏 π“Œπ“‡π’Ύπ“‰π‘’ & E𝓂𝒢𝒾𝓁 π“Žπ‘œπ“Šπ“‡ 𝒢𝓇𝓉𝒾𝒸𝓁𝑒 π“‰π‘œ π’Ήπ“‡π‘œπ’Ύπ’Ήπ’Άπ“‚π’Άπ“‡πŸ’πŸ’πŸ©@𝑔𝓂𝒢𝒾𝓁.π’Έπ‘œπ“‚.  π’΄π‘œπ“Š 𝒸𝒢𝓃 π“ˆπ‘’π‘’ π“Žπ‘œπ“Šπ“‡ 𝒢𝓇𝓉𝒾𝒸𝓁𝑒 𝒢𝓅𝓅𝑒𝒢𝓇𝒾𝓃𝑔 π‘œπ“ƒ 𝓉𝒽𝑒 𝓂𝒢𝒾𝓃 𝓅𝒢𝑔𝑒 𝒢𝓃𝒹 𝒽𝑒𝓁𝓅𝒾𝓃𝑔 π‘œπ“‰π’½π‘’π“‡π“ˆ. 

꧁༺ π»π‘œπ“…π‘’ π“‰π’½π’Ύπ“ˆ π“Œπ’Ύπ“π“ 𝒽𝑒𝓁𝓅 π“Žπ‘œπ“Š. 𝒦𝑒𝑒𝓅 π“‹π’Ύπ“ˆπ’Ύπ“‰π’Ύπ“ƒπ‘” π“‚π“Ž π’·π“π‘œπ‘” :) ༻꧂ 



Comments

Popular posts from this blog

app-policy

PRIVACY POLICY Last updated April 19, 2023 This privacy notice for Team CoderzDuniya ( " Company ," " we ," " us ," or " our " ), describes how and why we might collect, store, use, and/or share ( " process " ) your information when you use our services ( " Services " ), such as when you: Download and use our mobile application ( Revenue Calculator) , or any other application of ours that links to this privacy notice Engage with us in other related ways, including any sales, marketing, or events Questions or concerns?  Reading this privacy notice will help you understand your privacy rights and choices. If you do not agree with our policies and practices, please do not use our Services. If you still have any questions or concerns, please contact us at droidamar007@gmail.com . SUMMARY OF KEY POINTS This summary provides key points from our privacy notice, but you can find out more details about any of these t...

Java Socket Basics(Socket Programming in Java) Part-2(UDP)

Hi friends, We are going to discuss about UDP Socket Programming . In previous post  we discussed about the differences between TCP & UDP and the sample example of TCP Socket Programming. Below is the sample example of chat application using UDP  Socket Programming . UDP Sample :-  We are going to create an small example which contains two classes. UdpServer.java:-  This is a server class. Means this class will serve the purpose of socket connection. DatagramSocket is the java class and serve the purpose of Server and Client both. The overloaded constructor of DatagramSocket class matters. DatagramPacket is the java class which is responsible to transmit the data/packet over the network from server to client and vice-versa. UdpClient.java:-  This is client class. This serves the purpose of client which will communicate to server and send data to server and receive the data sent by server. UdpServer.java import java.net.DatagramPac...

Amazon Bedrock - Creating a AI Agent

Creating an AI agent using Amazon Bedrock involves configuring foundation models, defining tools, and deploying an agent capable of interacting with users and systems. Below is a step-by-step guide with visual references and a clear explanation . Step 1: Understand Amazon Bedrock Architecture Core components: Foundation Model (FM) – Claude, Titan, Llama, etc. Agent – Orchestrates reasoning and actions Knowledge Base – Connects to your data (S3, PDFs, databases) Action Groups – Lambda functions for performing tasks Client Application – Web app, chatbot, or API Step 2: Enable Amazon Bedrock To enable the Amazon Bedrock -  Login to AWS Console Search → Amazon Bedrock Click → Model access Enable models like: Claude (best for agents) Titan Llama Step 3: Create Knowledge Base (Optional but Recommended) A knowledge base allows agents to use your custom data. To create a Knowledge Base -  Steps: Go to Bedrock Console Click → Knowledge Bases ...