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
Post a Comment
You are responsible person and please write responsibly