Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Bruce

Quality Gate Status Security Rating Vulnerabilities Maven Central License

Bruce is an ergonomic, lightweight, pure Java wrapper around the Java Cryptography Architecture (JCA). It makes common cryptographic operations straightforward without adding any runtime dependencies beyond the JDK.

Features

  • Digital signatures — sign and verify data with RSA, DSA, ECDSA, and more
  • Symmetric encryption — AES-CBC, AES-GCM, DES, and other secret-key ciphers
  • Asymmetric encryption — RSA public/private-key encryption and decryption
  • Message digests — SHA-256, SHA-512, MD5, and any JCA-supported algorithm
  • Message Authentication Codes (MAC) — HmacSHA256, HmacSHA512, and more
  • Keystore management — load PKCS12/JKS keystores and serialize them to bytes, text, or files
  • Key generation — generate RSA/DSA/EC key pairs and symmetric keys on the fly
  • PEM support — read and write private keys, public keys, and certificates in PEM format
  • Multiple encodings — HEX, BASE64, URL-safe BASE64, and MIME BASE64
  • Pluggable providers — works with any JCA provider (e.g., Bouncy Castle)
  • Multi-key APIs — select a key by ID at call time for key-rotation scenarios
  • Type-safe algorithm enums — compile-time safety and IDE auto-completion for all algorithm names
  • Zero runtime dependencies — pure JDK, no extra JARs required at runtime

Requirements

  • Java 21 or later

Installation

Maven

<dependency>
    <groupId>com.mirkocaserta.bruce</groupId>
    <artifactId>bruce</artifactId>
    <version>2.1.0</version>
</dependency>

Gradle

implementation 'com.mirkocaserta.bruce:bruce:2.1.0'

Check Maven Central for the latest release version.

Quick Start

All operations are accessed through two static facades. Add these imports once at the top of your file:

import static com.mirkocaserta.bruce.Bruce.*;
import static com.mirkocaserta.bruce.Bruce.Encoding.*;
import static com.mirkocaserta.bruce.Keystores.*;

// Optional: import algorithm enums for type-safe algorithm selection
import com.mirkocaserta.bruce.DigestAlgorithm;
import com.mirkocaserta.bruce.MacAlgorithm;
import com.mirkocaserta.bruce.SignatureAlgorithm;
import com.mirkocaserta.bruce.SymmetricAlgorithm;
import com.mirkocaserta.bruce.SymmetricCipherAlgorithm;
import com.mirkocaserta.bruce.AsymmetricAlgorithm;

Usage Examples

Loading Keys from a Keystore

// Load a PKCS12 keystore from the classpath
KeyStore ks = keystore("classpath:keystore.p12", "password".toCharArray(), "PKCS12");

// Extract keys by alias
PrivateKey privateKey = privateKey(ks, "alice", "password".toCharArray());
PublicKey  publicKey  = publicKey(ks, "alice");

Keystores can be loaded from multiple sources:

PrefixExample
classpath:classpath:keystore.p12
file:file:/etc/ssl/keystore.p12
http://http://config-server/keystore.p12
https://https://config-server/keystore.p12

Keystore Serialization

KeyStore ks = keystore("classpath:keystore.p12", "password", "PKCS12");

// Serialize to raw bytes
byte[] raw = keystoreToBytes(ks, "password");

// Serialize and encode for text transport
String base64 = keystoreToString(ks, "password", BASE64);

// Persist directly to disk
keystoreToFile(ks, "password", Path.of("/tmp/keystore-copy.p12"));

Digital Signatures

KeyStore ks         = keystore("classpath:keystore.p12", "password", "PKCS12");
PrivateKey signKey  = privateKey(ks, "alice", "password");
PublicKey  verifyKey = publicKey(ks, "alice");

// Create a signer and a verifier (string-based)
Signer   signer   = signerBuilder().key(signKey).algorithm("SHA256withRSA").build();
Verifier verifier = verifierBuilder().key(verifyKey).algorithm("SHA256withRSA").build();

// Or use the type-safe enum alternative:
Signer   signer2   = signerBuilder().key(signKey).algorithm(SignatureAlgorithm.SHA256_WITH_RSA).build();
Verifier verifier2 = verifierBuilder().key(verifyKey).algorithm(SignatureAlgorithm.SHA256_WITH_RSA).build();

// Sign
Bytes message   = Bytes.from("Hello, Bob!");
Bytes signature = signer.sign(message);

// Encode signature for transport
String b64Signature = signature.encode(BASE64);

// Verify (decode first, then verify)
Bytes sigFromB64 = Bytes.from(b64Signature, BASE64);
boolean valid    = verifier.verify(message, sigFromB64);

Message Digest (Hashing)

// String-based or enum-based algorithm selection
Digester sha256 = digestBuilder().algorithm("SHA-256").build();
Digester sha256e = digestBuilder().algorithm(DigestAlgorithm.SHA_256).build(); // equivalent
Digester sha512 = digestBuilder().algorithm("SHA-512").build();

Bytes hash    = sha256.digest(Bytes.from("Hello, World!"));
String hexHash = hash.encode(HEX);    // "dffd6021bb2bd5b0af676290809ec3a5..."
String b64Hash = hash.encode(BASE64); // "/fVgIbsr1v..."

// File hashing is streamed in chunks (does not load the full file in memory)
Bytes fileHashFromPath = sha256.digest(Path.of("/var/log/app.log"));
Bytes fileHashFromFile = sha256.digest(new File("/var/log/app.log"));

Symmetric Encryption (AES)

// Generate a random AES key
byte[] keyBytes = symmetricKey("AES");
byte[] ivBytes  = new byte[16];
new SecureRandom().nextBytes(ivBytes);

// Build encryptor and decryptor (string-based)
SymmetricEncryptor encryptor = cipherBuilder()
    .key(keyBytes)
    .algorithms("AES", "AES/CBC/PKCS5Padding")
    .buildSymmetricEncryptor();

SymmetricDecryptor decryptor = cipherBuilder()
    .key(keyBytes)
    .algorithms("AES", "AES/CBC/PKCS5Padding")
    .buildSymmetricDecryptor();

// Or use type-safe enums:
SymmetricEncryptor encryptor2 = cipherBuilder()
    .key(keyBytes)
    .algorithms(SymmetricAlgorithm.AES, SymmetricCipherAlgorithm.AES_CBC_PKCS5)
    .buildSymmetricEncryptor();

Bytes iv         = Bytes.from(ivBytes);
Bytes cipherText = encryptor.encrypt(iv, Bytes.from("Secret message"));
Bytes plainText  = decryptor.decrypt(iv, cipherText);

// Encode for storage/transport
String encoded = cipherText.encode(BASE64);

Asymmetric Encryption (RSA)

// Generate an RSA key pair
KeyPair keyPair = keyPair("RSA", 2048);

AsymmetricEncryptor encryptor = cipherBuilder()
    .key(keyPair.getPublic())
    .algorithm("RSA/ECB/PKCS1Padding")
    .buildAsymmetricEncryptor();

AsymmetricDecryptor decryptor = cipherBuilder()
    .key(keyPair.getPrivate())
    .algorithm("RSA/ECB/PKCS1Padding")
    .buildAsymmetricDecryptor();

Bytes cipherText = encryptor.encrypt(Bytes.from("Top secret"));
Bytes plainText  = decryptor.decrypt(cipherText);

Message Authentication Code (MAC)

// Load a secret key from a keystore
KeyStore ks  = keystore("classpath:keystore.p12", "password");
Key secretKey = secretKey(ks, "hmac-key", "password");

Mac mac = macBuilder()
    .key(secretKey)
    .algorithm("HmacSHA256")
    .build();

Bytes data = Bytes.from("Authenticate me");
Bytes tag  = mac.sign(data);
String hexTag = tag.encode(HEX);

PEM Support

// Read keys from PEM strings
PrivateKey privKey = privateKeyFromPem("""
    -----BEGIN PRIVATE KEY-----
    MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC7...
    -----END PRIVATE KEY-----
    """, "RSA");

PublicKey pubKey = publicKeyFromPem("""
    -----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu7...
    -----END PUBLIC KEY-----
    """, "RSA");

// Convert keys back to PEM
String privatePem = keyToPem(privKey);
String publicPem  = keyToPem(pubKey);

Key Generation

// Generate key pairs
KeyPair rsaKeyPair = keyPair("RSA", 2048);
KeyPair ecKeyPair  = keyPair("EC", 256);
KeyPair dsaKeyPair = keyPair("DSA", 2048);

// Generate symmetric keys
byte[] aesKey    = symmetricKey("AES");
String b64AesKey = symmetricKey("AES", BASE64); // encoded for storage

Multi-Key APIs

Bruce supports selecting a key by ID at runtime, which is useful for key-rotation scenarios:

Map<String, PrivateKey> privateKeys = Map.of(
    "key-2023", privateKey(ks, "alice-2023", "password"),
    "key-2024", privateKey(ks, "alice-2024", "password")
);

SignerByKey signer = signerBuilder()
    .keys(privateKeys)
    .algorithm("SHA256withRSA")
    .buildByKey();

// Select the key to use at call time
Bytes signature = signer.sign("key-2024", Bytes.from("Hello"));

Type-Safe Algorithm Enums

All builder methods that accept a raw algorithm string also accept a type-safe enum constant. This provides compile-time validation and IDE auto-completion as an alternative to remembering JCA algorithm name strings.

// DigestAlgorithm
digestBuilder().algorithm(DigestAlgorithm.SHA_256).build();

// MacAlgorithm
macBuilder().key(key).algorithm(MacAlgorithm.HMAC_SHA_256).build();

// SignatureAlgorithm
signerBuilder().key(privateKey).algorithm(SignatureAlgorithm.SHA256_WITH_RSA).build();
verifierBuilder().key(publicKey).algorithm(SignatureAlgorithm.SHA256_WITH_RSA).build();

// SymmetricAlgorithm + SymmetricCipherAlgorithm
cipherBuilder()
    .key(keyBytes)
    .algorithms(SymmetricAlgorithm.AES, SymmetricCipherAlgorithm.AES_CBC_PKCS5)
    .buildSymmetricEncryptor();

// AsymmetricAlgorithm
cipherBuilder()
    .key(publicKey)
    .algorithm(AsymmetricAlgorithm.RSA_ECB_PKCS1)
    .buildAsymmetricEncryptor();

All enum types implement the AlgorithmId interface, which exposes the underlying JCA name via algorithmName(). The string-based overloads remain fully supported for custom or provider-specific algorithms not covered by the built-in enums.

Using a Custom Provider

// Use Bouncy Castle for extended algorithm support
Security.addProvider(new BouncyCastleProvider());

Digester digester = digestBuilder()
    .algorithm("BLAKE2b-256")
    .provider("BC")
    .build();

The Bytes Type

Bytes is Bruce’s universal currency type. It wraps a raw byte array and provides convenient conversions:

// Construction
Bytes b1 = Bytes.from(new byte[]{1, 2, 3});       // raw bytes
Bytes b2 = Bytes.from("Hello");                    // UTF-8 text
Bytes b3 = Bytes.from("cafebabe", HEX);            // decode HEX
Bytes b4 = Bytes.from("c2lnbg==", BASE64);         // decode BASE64
Bytes b5 = Bytes.from(Path.of("secret.bin"));      // file contents
Bytes b6 = Bytes.fromPem("-----BEGIN ...");        // PEM-encoded DER

// Consumption
byte[] raw   = b2.asBytes();
String hex   = b2.encode(HEX);
String b64   = b2.encode(BASE64);
String text  = b2.asString();       // UTF-8
int    len   = b2.length();
boolean empty = b2.isEmpty();

Building from Source

git clone https://github.com/mcaserta/bruce.git
cd bruce
./gradlew build

Run tests:

./gradlew test

Generate Javadoc:

./gradlew javadoc

Contributing

Contributions are welcome. See CONTRIBUTING.md for the issue and pull request workflow.

License

Bruce is released under the Apache License, Version 2.0.

Features

  • All cryptographic operations are exposed through a small set of entry points:
    • Bruce — builder factories (cipherBuilder(), signerBuilder(), verifierBuilder(), digestBuilder(), macBuilder())
    • Keystores — keystore loading, serialization, key and certificate retrieval, key generation
    • Bytes — universal I/O type for passing data in and getting results out
  • No checked exceptions cluttering your code.
  • No transitive dependencies. Zero. Zilch.
  • Out of the box support for:
    • key stores
    • public, private and secret keys
    • certificates
    • digital signatures
    • symmetric and asymmetric encryption
    • message digesters
    • message authentication codes
    • different encodings: Base64, Url, Mime, Hex
    • custom providers such as Bouncy Castle
  • Massively unit tested and documented.
  • Open Source: you don’t need to trust Bruce: you can see for yourself if you like what Bruce does.

Getting Started

Requirements

Bruce requires Java 21. That’s it. That’s the whole requirement.

You also need to understand basic cryptography concepts. If you need a refresher, I suggest Cryptography Engineering and Applied Cryptography, both by Bruce Schneier.

Setup

Bruce 2.1.0 is available on Maven Central.

Maven

Add the following dependency to your pom.xml:

<dependency>
    <groupId>com.mirkocaserta.bruce</groupId>
    <artifactId>bruce</artifactId>
    <version>2.1.0</version>
</dependency>

Gradle (Kotlin DSL)

Add the following to your build.gradle.kts:

implementation("com.mirkocaserta.bruce:bruce:2.1.0")

Gradle (Groovy DSL)

Add the following to your build.gradle:

implementation 'com.mirkocaserta.bruce:bruce:2.1.0'

Scala SBT

libraryDependencies += "com.mirkocaserta.bruce" % "bruce" % "2.1.0"

Apache Ivy

<dependency org="com.mirkocaserta.bruce" name="bruce" rev="2.1.0"/>

General Concepts


description: Some general concepts apply to all functionalities in Bruce.

General Concepts

Algorithms

Algorithms supported by the default JCA provider are listed here.

Algorithms supported by the Bouncy Castle JCA provider are listed here.

Static Imports

Static imports are used throughout all examples. Keystore and key helpers live in Keystores:

import static com.mirkocaserta.bruce.Keystores.*;

KeyStore keystore = keystore("classpath:keystore.p12", "password".toCharArray(), "PKCS12");
PrivateKey key    = privateKey(keystore, "alice", "password".toCharArray());

Builder factories and encoding constants live in Bruce:

import static com.mirkocaserta.bruce.Bruce.*;
import static com.mirkocaserta.bruce.Bruce.Encoding.*;

Digester digester = digestBuilder().algorithm("SHA-256").build();
Bytes hash = digester.digest(Bytes.from("hello"));
String hex = hash.encode(HEX);

You are of course free not to use static imports.

Passwords

Bruce provides two options for password handling to balance security and convenience:

For maximum security: Use char[] arrays. String instances might be stored in permanent memory areas, and depending on implementation specifics, this could potentially be accessed by attackers. Character arrays can be explicitly cleared from memory after use.

For convenience: Use String passwords. Bruce provides convenient overloads that accept String passwords and internally convert them to char arrays for you.

// Maximum security approach with char arrays
KeyStore keystore = keystore("classpath:keystore.p12", "password".toCharArray());
PrivateKey key    = privateKey(keystore, "alias", "password".toCharArray());

// Convenience approach with Strings
KeyStore keystore = keystore("classpath:keystore.p12", "password");
PrivateKey key    = privateKey(keystore, "alias", "password");

The Bytes Type

Bytes is the universal currency type for all Bruce cryptographic operations. It is an immutable wrapper around a raw byte array that can be constructed from and converted to a variety of representations on demand.

Raw byte arrays

At the most basic level, computers work with bits. In Java, cryptographic operations typically produce or consume arrays of bytes:

Digester digester = digestBuilder().algorithm("SHA1").build();
Bytes hash = digester.digest(Bytes.from("message"));
byte[] rawBytes = hash.asBytes();

Encodings

Raw byte arrays are not always a practical representation format — you cannot directly use them in a text file, an email message or a JSON payload. Use Bytes to encode the output:

Digester digester = digestBuilder().algorithm("SHA1").build();
Bytes hash = digester.digest(Bytes.from("message"));

String base64 = hash.encode(BASE64); // "b5ua881ui4pzws3O03/p9ZIm4n0="
String hex    = hash.encode(HEX);
String url    = hash.encode(URL);    // URL-safe Base64
String mime   = hash.encode(MIME);   // line-broken Base64

Supported encodings are Base64, Url, Mime, Hex.

To reconstruct Bytes from an encoded string, use Bytes.from(encoded, encoding):

Bytes restored = Bytes.from("b5ua881ui4pzws3O03/p9ZIm4n0=", BASE64);

See the Bytes page for the complete API.

Providers

All builders support both .provider(String) and .provider(Bruce.Provider).

import static com.mirkocaserta.bruce.Bruce.Provider.*;

Digester digester = digestBuilder()
    .algorithm("SHA-1")
    .provider(BOUNCY_CASTLE)
    .build();

Built-in provider enum values are:

  • JCA (default provider chain)
  • BOUNCY_CASTLE (BC)
  • CONSCRYPT (Conscrypt)

You can still use .provider("...") for custom provider names. Ensure the provider jar is on the classpath before selecting it.

Error Handling

There is a single exception in Bruce that wraps all kinds of errors: the BruceException. As it is a RuntimeException, you are not forced to catch it.

Initialization and configuration errors are raised as soon as possible.

Wherever possible, the originating exception is wrapped and can be accessed through the getCause() method.

Roadmap

Please see the GitHub issue tracker for more info.

Cheat Sheet

Complete list of available builder methods and functional interfaces.

  • Keystore / key helpers → static imports from com.mirkocaserta.bruce.Keystores
  • Builder factories → static imports from com.mirkocaserta.bruce.Bruce
  • Encoding constants → static imports from com.mirkocaserta.bruce.Bruce.Encoding
  • Universal I/O type → com.mirkocaserta.bruce.Bytes
// ─── Encoding enum (Bruce.Encoding) ─────────────────────────────────────────
public enum Encoding { HEX, BASE64, URL, MIME }

// ─── Provider enum (Bruce.Provider) ─────────────────────────────────────────
public enum Provider { JCA, BOUNCY_CASTLE, CONSCRYPT }

// ─── Algorithm enums (AlgorithmId) ──────────────────────────────────────────
// All implement AlgorithmId: String algorithmName()

DigestAlgorithm          // MD5, SHA_1, SHA_224, SHA_256, SHA_384, SHA_512,
                         // SHA_512_224, SHA_512_256,
                         // SHA3_224, SHA3_256, SHA3_384, SHA3_512

MacAlgorithm             // HMAC_MD5, HMAC_SHA_1, HMAC_SHA_224, HMAC_SHA_256,
                         // HMAC_SHA_384, HMAC_SHA_512, HMAC_SHA_512_224,
                         // HMAC_SHA_512_256,
                         // HMAC_SHA3_224, HMAC_SHA3_256, HMAC_SHA3_384, HMAC_SHA3_512

SignatureAlgorithm       // *_WITH_RSA, *_WITH_DSA, *_WITH_ECDSA, RSASSA_PSS
                         // (MD5, SHA1, SHA224, SHA256, SHA384, SHA512,
                         //  SHA512_224, SHA512_256, SHA3_256, SHA3_384, SHA3_512)

SymmetricAlgorithm       // AES, DES, DESEDE, BLOWFISH, RC2, RC4, CHACHA20

SymmetricCipherAlgorithm // AES_CBC_PKCS5, AES_CBC_NO_PADDING, AES_CTR_NO_PADDING,
                         // AES_ECB_PKCS5, AES_ECB_NO_PADDING, AES_GCM_NO_PADDING,
                         // DES_CBC_PKCS5, DES_ECB_PKCS5,
                         // DESEDE_CBC_PKCS5, DESEDE_ECB_PKCS5,
                         // BLOWFISH_CBC_PKCS5, BLOWFISH_ECB_PKCS5

AsymmetricAlgorithm      // RSA, RSA_ECB_PKCS1, RSA_ECB_OAEP_SHA1_MGF1,
                         // RSA_ECB_OAEP_SHA256_MGF1, RSA_ECB_OAEP_SHA384_MGF1,
                         // RSA_ECB_OAEP_SHA512_MGF1, RSA_ECB_NO_PADDING

// ─── Bytes ───────────────────────────────────────────────────────────────────
// Construction
Bytes.from(byte[]);
Bytes.from(String);                         // UTF-8
Bytes.from(String, Charset);
Bytes.from(String, Encoding);               // decode encoded string
Bytes.from(Path);
Bytes.from(File);
Bytes.from(InputStream);
Bytes.fromPem(String);

// Consumption
byte[]  b.asBytes();
String  b.encode(Encoding);
String  b.toPem(PemType type);              // e.g. PemType.CERTIFICATE
String  b.asString();                       // UTF-8
String  b.asString(Charset);
int     b.length();
boolean b.isEmpty();

// ─── Keystore (com.mirkocaserta.bruce.Keystores) ─────────────────────────────
KeyStore keystore();
KeyStore keystore(String type);
KeyStore keystore(String location, char[] password);
KeyStore keystore(String location, String password);
KeyStore keystore(String location, char[] password, String type);
KeyStore keystore(String location, String password, String type);
KeyStore keystore(String location, char[] password, String type, String provider);
KeyStore keystore(String location, char[] password, String type, Provider provider);
KeyStore keystore(String location, String password, String type, String provider);
KeyStore keystore(String location, String password, String type, Provider provider);
byte[]   keystoreToBytes(KeyStore keystore, char[] password);
byte[]   keystoreToBytes(KeyStore keystore, String password);
String   keystoreToString(KeyStore keystore, char[] password, Encoding encoding);
String   keystoreToString(KeyStore keystore, String password, Encoding encoding);
void     keystoreToFile(KeyStore keystore, char[] password, Path path);
void     keystoreToFile(KeyStore keystore, String password, Path path);
void     keystoreToFile(KeyStore keystore, char[] password, File file);
void     keystoreToFile(KeyStore keystore, String password, File file);

// ─── Certificates (com.mirkocaserta.bruce.Keystores) ─────────────────────────
Certificate certificate(KeyStore keystore, String alias);
Certificate certificateFromPem(String pem);
Certificate certificateFromDer(byte[] der);
String      certificateToPem(Certificate certificate);
byte[]      certificateToDer(Certificate certificate);

// ─── Keys (com.mirkocaserta.bruce.Keystores) ─────────────────────────────────
PublicKey  publicKey(KeyStore keystore, String alias);
PrivateKey privateKey(KeyStore keystore, String alias, char[] password);
PrivateKey privateKey(KeyStore keystore, String alias, String password);
Key        secretKey(KeyStore keystore, String alias, char[] password);
Key        secretKey(KeyStore keystore, String alias, String password);
PrivateKey privateKeyFromPem(String pem, String algorithm);
PublicKey  publicKeyFromPem(String pem, String algorithm);
PrivateKey privateKeyFromDer(byte[] der, String algorithm);
PublicKey  publicKeyFromDer(byte[] der, String algorithm);
String     keyToPem(Key key);
byte[]     keyToDer(Key key);
byte[]     pemToDer(String pem);
String     derToPem(byte[] der, PemType type);
PrivateKey rsaPrivateKeyFromPkcs1(byte[] pkcs1Der);
PrivateKey rsaPrivateKeyFromPkcs1Pem(String pem);
byte[]     rsaPrivateKeyToPkcs1(PrivateKey privateKey);
String     rsaPrivateKeyToPkcs1Pem(PrivateKey privateKey);
PublicKey  rsaPublicKeyFromPkcs1(byte[] pkcs1Der);
PublicKey  rsaPublicKeyFromPkcs1Pem(String pem);
byte[]     rsaPublicKeyToPkcs1(PublicKey publicKey);
String     rsaPublicKeyToPkcs1Pem(PublicKey publicKey);
KeyPair    keyPair(String algorithm, int keySize);
KeyPair    keyPair(String algorithm, String provider, int keySize);
KeyPair    keyPair(String algorithm, Provider provider, int keySize);
KeyPair    keyPair(String algorithm, int keySize, SecureRandom random);
KeyPair    keyPair(String algorithm, String provider, int keySize, SecureRandom random);
KeyPair    keyPair(String algorithm, Provider provider, int keySize, SecureRandom random);
byte[]     symmetricKey(String algorithm);
byte[]     symmetricKey(String algorithm, String provider);
byte[]     symmetricKey(String algorithm, Provider provider);
String     symmetricKey(String algorithm, Encoding encoding);
String     symmetricKey(String algorithm, String provider, Encoding encoding);
String     symmetricKey(String algorithm, Provider provider, Encoding encoding);

// ─── Digests (Bruce.digestBuilder) ──────────────────────────────────────────
DigestBuilder digestBuilder()
  .algorithm(String)           // e.g. "SHA-256"
  .algorithm(DigestAlgorithm)  // type-safe alternative
  .provider(String)            // optional
  .provider(Provider)          // optional
  .build()                     // → Digester

// Digester interface
Bytes  Digester.digest(Bytes input)
Bytes  Digester.digest(Path file)     // streaming
Bytes  Digester.digest(File file)     // delegates to Path variant

// ─── Signatures (Bruce.signerBuilder / verifierBuilder) ─────────────────────
SignerBuilder signerBuilder()
  .key(PrivateKey)                    // single key
  .keys(Map<String, PrivateKey>)      // multi-key
  .algorithm(String)                  // e.g. "SHA256withRSA"
  .algorithm(SignatureAlgorithm)      // type-safe alternative
  .provider(String)                   // optional
  .provider(Provider)                 // optional
  .build()                            // → Signer
  .buildByKey()                       // → SignerByKey

VerifierBuilder verifierBuilder()
  .key(PublicKey)                     // single key
  .keys(Map<String, PublicKey>)       // multi-key
  .algorithm(String)                  // e.g. "SHA256withRSA"
  .algorithm(SignatureAlgorithm)      // type-safe alternative
  .provider(String)                   // optional
  .provider(Provider)                 // optional
  .build()                            // → Verifier
  .buildByKey()                       // → VerifierByKey

// Signer / SignerByKey interfaces
Bytes  Signer.sign(Bytes message)
Bytes  SignerByKey.sign(String keyId, Bytes message)

// Verifier / VerifierByKey interfaces
boolean  Verifier.verify(Bytes message, Bytes signature)
boolean  VerifierByKey.verify(String keyId, Bytes message, Bytes signature)

// ─── Ciphers (Bruce.cipherBuilder) ──────────────────────────────────────────
CipherBuilder cipherBuilder()
  // symmetric fixed-key
  .key(byte[])                        // raw bytes
  .key(Bytes)                         // or Bytes
  .keyAlgorithm(String)               // e.g. "AES"
  .keyAlgorithm(SymmetricAlgorithm)   // type-safe alternative
  .algorithm(String)                  // e.g. "AES/CBC/PKCS5Padding"
  .algorithm(SymmetricCipherAlgorithm) // type-safe alternative
  .algorithms(String, String)         // convenience: keyAlgo + cipherAlgo
  .algorithms(SymmetricAlgorithm, SymmetricCipherAlgorithm) // type-safe convenience
  .provider(String)                   // optional
  .provider(Provider)                 // optional
  .buildSymmetricEncryptor()          // → SymmetricEncryptor
  .buildSymmetricDecryptor()          // → SymmetricDecryptor
  .buildSymmetricEncryptorByKey()     // → SymmetricEncryptorByKey (no fixed key)
  .buildSymmetricDecryptorByKey()     // → SymmetricDecryptorByKey

  // asymmetric fixed-key
  .key(Key)                           // PublicKey or PrivateKey
  .algorithm(String)                  // e.g. "RSA/ECB/PKCS1Padding"
  .algorithm(AsymmetricAlgorithm)     // type-safe alternative
  .provider(String)                   // optional
  .provider(Provider)                 // optional
  .buildAsymmetricEncryptor()         // → AsymmetricEncryptor
  .buildAsymmetricDecryptor()         // → AsymmetricDecryptor

  // asymmetric by-key
  .keys(Map<String, Key>)
  .buildAsymmetricEncryptorByKey()    // → AsymmetricEncryptorByKey
  .buildAsymmetricDecryptorByKey()    // → AsymmetricDecryptorByKey

// Symmetric interfaces
Bytes  SymmetricEncryptor.encrypt(Bytes iv, Bytes plaintext)
Bytes  SymmetricDecryptor.decrypt(Bytes iv, Bytes ciphertext)
Bytes  SymmetricEncryptorByKey.encrypt(Bytes key, Bytes iv, Bytes plaintext)
Bytes  SymmetricDecryptorByKey.decrypt(Bytes key, Bytes iv, Bytes ciphertext)

// Asymmetric interfaces
Bytes  AsymmetricEncryptor.encrypt(Bytes plaintext)
Bytes  AsymmetricDecryptor.decrypt(Bytes ciphertext)
Bytes  AsymmetricEncryptorByKey.encrypt(String keyId, Bytes plaintext)
Bytes  AsymmetricDecryptorByKey.decrypt(String keyId, Bytes ciphertext)

// ─── Message Authentication Codes (Bruce.macBuilder) ─────────────────────────
MacBuilder macBuilder()
  .key(Key)
  .algorithm(String)                 // e.g. "HmacSHA256"
  .algorithm(MacAlgorithm)           // type-safe alternative
  .provider(String)                  // optional
  .provider(Provider)                // optional
  .build()                           // → Mac

// Mac interface
Bytes  Mac.get(Bytes message)

Bytes

com.mirkocaserta.bruce.Bytes is the universal currency type for all Bruce cryptographic operations. It is an immutable wrapper around a raw byte array that can be constructed from — and converted to — a variety of representations on demand.

Raw bytes are the canonical form; every other representation is simply a view.

Construction

// from a raw byte array
Bytes b = Bytes.from(new byte[]{0, 1, 2});

// from UTF-8 text
Bytes b = Bytes.from("Hello");

// from text with an explicit charset
Bytes b = Bytes.from("Hello", ISO_8859_1);

// by decoding a HEX-encoded string
Bytes b = Bytes.from("cafebabe", HEX);

// by decoding a BASE64-encoded string
Bytes b = Bytes.from("c2lnbg==", BASE64);

// from a file's full contents
Bytes b = Bytes.from(Path.of("secret.bin"));
Bytes b = Bytes.from(new File("secret.bin"));

// from an input stream
Bytes b = Bytes.from(inputStream);

// by decoding a PEM-encoded string
Bytes b = Bytes.fromPem("-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----");

Consumption

// get a defensive copy of the underlying byte array
byte[] raw    = b.asBytes();

// encode to a string representation
String base64 = b.encode(BASE64);
String hex    = b.encode(HEX);
String url    = b.encode(URL);
String mime   = b.encode(MIME);

// encode as PEM string
String pem    = b.toPem(PemType.CERTIFICATE);

// decode as UTF-8 string
String text   = b.asString();

// decode as string with explicit charset
String latin1 = b.asString(ISO_8859_1);

// utility
int     len   = b.length();
boolean empty = b.isEmpty();

Equality

Bytes implements equals and hashCode based on the underlying byte array content, so two Bytes instances wrapping identical bytes will be equal:

Bytes a = Bytes.from("hello");
Bytes b = Bytes.from("hello");
assertEquals(a, b);  // true

Why Bytes?

Previous Bruce versions provided dozens of overloaded methods — one for each combination of input charset, output encoding, raw bytes, and text. Bytes collapses all of that into a single type:

  • Builders are simpler — no .charset() or .encoding() on builders.
  • Interfaces are single-method functional interfaces — easy to lambda-ify.
  • You choose how to interpret inputs and outputs at the call site, not at configuration time.

Key Stores

For managing Java key stores, I suggest using KeyStore Explorer.

All methods below are available as static imports from com.mirkocaserta.bruce.Keystores.

Default

KeyStore keystore();

Returns the default key store using configuration from the following system properties:

  • javax.net.ssl.keyStore
  • javax.net.ssl.keyStorePassword

The key store location supports the following protocols:

  • classpath:
  • http:
  • https:
  • file:

If no protocol is specified, file is assumed. The default key store type is PKCS12.

Usage Example

KeyStore keystore = keystore();

Default with Type

KeyStore keystore(String type);

Same as above but the key store type can be specified. For instance, valid types include: JKS, PKCS12.

Usage Example

KeyStore keystore = keystore("JKS");

From Location

KeyStore keystore(String location, char[] password);
KeyStore keystore(String location, String password);

Loads a key store from the given location.

The location parameter supports the protocols described in the default key store section.

The key store is opened with the given password. The key store type is assumed to be the default: PKCS12.

Usage Examples

// load key store from classpath
KeyStore keystore = keystore("classpath:keystore.p12", "password".toCharArray());

// load key store from file
KeyStore keystore = keystore("file:/etc/myapp/keystore.p12", "password".toCharArray());

// load key store from https
KeyStore keystore = keystore("https://acme.com/sec/keystore.p12", "password".toCharArray());

// convenience String password overload
KeyStore keystore = keystore("classpath:keystore.p12", "password");

From Location with Type

KeyStore keystore(String location, char[] password, String type);
KeyStore keystore(String location, String password, String type);

Same as from location but allows you to specify a key store type.

Usage Examples

// use JKS as the key store type
KeyStore keystore = keystore("classpath:keystore.jks", "password".toCharArray(), "JKS");

// use PKCS12 as the key store type
KeyStore keystore = keystore("classpath:keystore.p12", "password".toCharArray(), "PKCS12");

From Location with Type and Provider

KeyStore keystore(String location, char[] password, String type, String provider);
KeyStore keystore(String location, String password, String type, String provider);

Same as above but allows specifying an explicit JCA provider.

Usage Example

KeyStore keystore = keystore("classpath:keystore.p12", "password".toCharArray(), "PKCS12", "BC");

Serialization

byte[] keystoreToBytes(KeyStore keystore, char[] password);
byte[] keystoreToBytes(KeyStore keystore, String password);

String keystoreToString(KeyStore keystore, char[] password, Bruce.Encoding encoding);
String keystoreToString(KeyStore keystore, String password, Bruce.Encoding encoding);

void keystoreToFile(KeyStore keystore, char[] password, Path path);
void keystoreToFile(KeyStore keystore, String password, Path path);
void keystoreToFile(KeyStore keystore, char[] password, File file);
void keystoreToFile(KeyStore keystore, String password, File file);

Serializes an in-memory key store so you can persist it in different forms:

  • raw bytes for transport or custom storage
  • encoded text using HEX, BASE64, URL, or MIME
  • direct file output to Path or File

Usage Examples

KeyStore ks = keystore("classpath:keystore.p12", "password");

byte[] raw = keystoreToBytes(ks, "password");
String base64 = keystoreToString(ks, "password", Bruce.Encoding.BASE64);

keystoreToFile(ks, "password", Path.of("/tmp/keystore-copy.p12"));
keystoreToFile(ks, "password", new File("/tmp/keystore-copy-2.p12"));

Certificates

All methods below are available as static imports from com.mirkocaserta.bruce.Keystores.

Certificate

Certificate certificate(KeyStore keystore, String alias);

Loads a certificate from a given key store.

Usage example

KeyStore keystore = keystore("classpath:keystore.p12", "password".toCharArray(), "PKCS12");
Certificate certificate = certificate(keystore, "alice");

Certificate Format Conversions

Bruce supports certificate format conversions without Bouncy Castle.

// PEM -> Certificate (X.509)
Certificate certificateFromPem(String pem);

// DER -> Certificate (X.509)
Certificate certificateFromDer(byte[] der);

// Certificate -> PEM
String certificateToPem(Certificate certificate);

// Certificate -> DER
byte[] certificateToDer(Certificate certificate);

// Generic PEM <-> DER conversion helpers
byte[] pemToDer(String pem);
String derToPem(byte[] der, PemType type);

Usage example

KeyStore ks = keystore("classpath:/keystore.p12", "password".toCharArray(), "PKCS12");
Certificate cert = certificate(ks, "test");

String pem = certificateToPem(cert);
byte[] der = certificateToDer(cert);

Certificate fromPem = certificateFromPem(pem);
Certificate fromDer = certificateFromDer(der);

assertEquals(cert, fromPem);
assertEquals(cert, fromDer);

Keys

All methods below are available as static imports from com.mirkocaserta.bruce.Keystores.

Public Key

PublicKey publicKey(KeyStore keystore, String alias);

Loads a public key from a key store.

Usage Example

KeyStore keystore = keystore("classpath:keystore.p12", "password".toCharArray(), "PKCS12");

PublicKey publicKey = publicKey(keystore, "alice");

Private Key

PrivateKey privateKey(KeyStore keystore, String alias, char[] password);
PrivateKey privateKey(KeyStore keystore, String alias, String password);

Loads a private key from a key store. The password parameter is the private key’s password.

Usage Example

KeyStore keystore = keystore("classpath:keystore.p12", "password".toCharArray(), "PKCS12");

PrivateKey privateKey = privateKey(keystore, "alice", "password".toCharArray());
// or with String convenience overload:
PrivateKey privateKey = privateKey(keystore, "alice", "password");

Secret Key

Key secretKey(KeyStore keystore, String alias, char[] password);
Key secretKey(KeyStore keystore, String alias, String password);

Loads a secret key from a key store. The password parameter is the secret key’s password.

Usage Example

KeyStore keystore = keystore("classpath:/keystore.p12", "password".toCharArray(), "PKCS12");

Key key = secretKey(keystore, "hmac", "password".toCharArray());
// or with String convenience overload:
Key key = secretKey(keystore, "hmac", "password");

Symmetric Key

byte[]  symmetricKey(String algorithm);
byte[]  symmetricKey(SymmetricKeyAlgorithm algorithm);
byte[]  symmetricKey(String algorithm, String provider);
byte[]  symmetricKey(SymmetricKeyAlgorithm algorithm, String provider);
byte[]  symmetricKey(String algorithm, Provider provider);
byte[]  symmetricKey(SymmetricKeyAlgorithm algorithm, Provider provider);
String  symmetricKey(String algorithm, Encoding encoding);
String  symmetricKey(SymmetricKeyAlgorithm algorithm, Encoding encoding);
String  symmetricKey(String algorithm, String provider, Encoding encoding);
String  symmetricKey(SymmetricKeyAlgorithm algorithm, String provider, Encoding encoding);
String  symmetricKey(String algorithm, Provider provider, Encoding encoding);
String  symmetricKey(SymmetricKeyAlgorithm algorithm, Provider provider, Encoding encoding);

Generates a random symmetric key using the given algorithm.

Usage Examples

// generate raw bytes
byte[] rawKey = symmetricKey(SymmetricKeyAlgorithm.AES);

// generate BASE64-encoded key string
String b64Key = symmetricKey(SymmetricKeyAlgorithm.AES, BASE64);

// use key as Bytes for the CipherBuilder
Bytes key = Bytes.from(b64Key, BASE64);

Key Pair

KeyPair keyPair(String algorithm, int keySize);
KeyPair keyPair(AsymmetricKeyAlgorithm algorithm, int keySize);
KeyPair keyPair(String algorithm, String provider, int keySize);
KeyPair keyPair(AsymmetricKeyAlgorithm algorithm, String provider, int keySize);
KeyPair keyPair(String algorithm, Provider provider, int keySize);
KeyPair keyPair(AsymmetricKeyAlgorithm algorithm, Provider provider, int keySize);

Generates a pair of keys for asymmetric cryptography.

Usage Example

KeyPair keyPair = keyPair(AsymmetricKeyAlgorithm.RSA, 4096);

Signer signer   = signerBuilder().key(keyPair.getPrivate()).algorithm("SHA512withRSA").build();
Verifier verifier = verifierBuilder().key(keyPair.getPublic()).algorithm("SHA512withRSA").build();

Bytes message   = Bytes.from("Hello");
Bytes signature = signer.sign(message);
assertTrue(verifier.verify(message, signature));

Key Pair with Custom PRNG

KeyPair keyPair(String algorithm, int keySize, SecureRandom random);
KeyPair keyPair(AsymmetricKeyAlgorithm algorithm, int keySize, SecureRandom random);
KeyPair keyPair(String algorithm, String provider, int keySize, SecureRandom random);
KeyPair keyPair(AsymmetricKeyAlgorithm algorithm, String provider, int keySize, SecureRandom random);
KeyPair keyPair(String algorithm, Provider provider, int keySize, SecureRandom random);
KeyPair keyPair(AsymmetricKeyAlgorithm algorithm, Provider provider, int keySize, SecureRandom random);

Same as key pair but allows passing a SecureRandom instance for custom initialization of the pseudo random number generator.

Usage Example

SecureRandom random = SecureRandom.getInstanceStrong();
random.setSeed(new byte[]{0, 1, 2, 3, 4, 5});
KeyPair keyPair = keyPair(AsymmetricKeyAlgorithm.RSA, 4096, random);

Key Format Conversions (PEM / DER / PKCS#1)

Bruce supports key format conversions without Bouncy Castle.

// Generic key PEM/DER exports
String keyToPem(Key key);
byte[] keyToDer(Key key);

// PKCS#8 PEM/DER -> key
PrivateKey privateKeyFromPem(String pem, String algorithm);
PublicKey publicKeyFromPem(String pem, String algorithm);
PrivateKey privateKeyFromDer(byte[] der, String algorithm);
PublicKey publicKeyFromDer(byte[] der, String algorithm);

// Generic PEM <-> DER helpers
byte[] pemToDer(String pem);
String derToPem(byte[] der, PemType type);

// RSA PKCS#1 support
PrivateKey rsaPrivateKeyFromPkcs1(byte[] pkcs1Der);
PrivateKey rsaPrivateKeyFromPkcs1Pem(String pem);
byte[] rsaPrivateKeyToPkcs1(PrivateKey privateKey);
String rsaPrivateKeyToPkcs1Pem(PrivateKey privateKey);

PublicKey rsaPublicKeyFromPkcs1(byte[] pkcs1Der);
PublicKey rsaPublicKeyFromPkcs1Pem(String pem);
byte[] rsaPublicKeyToPkcs1(PublicKey publicKey);
String rsaPublicKeyToPkcs1Pem(PublicKey publicKey);

Usage Example

KeyPair kp = keyPair("RSA", 2048);

// PKCS#8 / SPKI PEM
String privatePem = keyToPem(kp.getPrivate());
String publicPem  = keyToPem(kp.getPublic());

PrivateKey privateFromPem = privateKeyFromPem(privatePem, "RSA");
PublicKey publicFromPem   = publicKeyFromPem(publicPem, "RSA");

// RSA PKCS#1
String rsaPrivatePkcs1Pem = rsaPrivateKeyToPkcs1Pem(kp.getPrivate());
String rsaPublicPkcs1Pem  = rsaPublicKeyToPkcs1Pem(kp.getPublic());

PrivateKey rsaPrivateRestored = rsaPrivateKeyFromPkcs1Pem(rsaPrivatePkcs1Pem);
PublicKey rsaPublicRestored   = rsaPublicKeyFromPkcs1Pem(rsaPublicPkcs1Pem);

Digests

Digester

Returns a Digester for the given algorithm. All input and output use the Bytes universal type.

Usage examples

// Build once
Digester digester = digestBuilder().algorithm("SHA-256").build();

// raw bytes → Bytes
Bytes raw = digester.digest(Bytes.from("hello".getBytes(UTF_8)));

// UTF-8 text → BASE64 string
String b64 = digester.digest(Bytes.from("hello")).encode(BASE64);

// UTF-8 text → HEX string
String hex = digester.digest(Bytes.from("hello")).encode(HEX);

// explicit charset → BASE64 string
String b64_2 = digester.digest(Bytes.from("hello 👋🏻", UTF_16)).encode(BASE64);

// file path → BASE64 string (streaming, no full file load)
String fileHash = digester.digest(Path.of("src/test/resources/test-file-1"))
                          .encode(BASE64);

// java.io.File → HEX string (delegates to digest(Path), same streaming behavior)
String fileHex = digester.digest(new File("src/test/resources/test-file-1"))
                         .encode(HEX);

Builder options

import static com.mirkocaserta.bruce.Bruce.Provider.*;

// String-based algorithm (open-ended, supports any JCA algorithm)
Digester digester = digestBuilder()
    .algorithm("SHA-256")
    .provider(BOUNCY_CASTLE)  // optional, defaults to JCA
    // .provider("BC")        // string-based alternative
    .build();

// Enum-based algorithm (type-safe, IDE auto-completion)
Digester digester2 = digestBuilder()
    .algorithm(DigestAlgorithm.SHA_256)
    .provider(BOUNCY_CASTLE)  // optional
    .build();

Available DigestAlgorithm constants: MD5, SHA_1, SHA_224, SHA_256, SHA_384, SHA_512, SHA_512_224, SHA_512_256, SHA3_224, SHA3_256, SHA3_384, SHA3_512.

Interface

public interface Digester {
    Bytes digest(Bytes input);
    Bytes digest(Path file);                // streaming file read
    default Bytes digest(File file) { ... } // delegates to digest(Path)
}

Input / output combinations

InputHow to constructConsume output
raw byte[]Bytes.from(rawBytes).asBytes()
UTF-8 textBytes.from("text").encode(HEX) / .encode(BASE64) / .asString()
custom charsetBytes.from("text", charset).encode(...)
encoded stringBytes.from("abc…", Encoding.HEX).encode(...)
filepass Path / File directly.encode(...)

Signatures

Signer

Returns a Signer for the given private key and algorithm. All input and output use the Bytes universal type — wrap your plaintext with Bytes.from(...) and call .encode(...) or .asString() on the result.

Usage examples

KeyStore keystore = keystore("classpath:keystore.p12", "password".toCharArray(), "PKCS12");
PrivateKey privateKey = privateKey(keystore, "alice", "password".toCharArray());

Signer signer = signerBuilder()
    .key(privateKey)
    .algorithm("SHA512withRSA")
    .build();

// raw bytes → raw bytes
Bytes rawSig = signer.sign(Bytes.from("Hello Bob".getBytes(UTF_8)));

// UTF-8 text → BASE64 signature string
Bytes sig    = signer.sign(Bytes.from("Hello Bob"));
String b64   = sig.encode(BASE64);

// UTF-8 text → HEX signature string
String hex   = signer.sign(Bytes.from("Hello Bob")).encode(HEX);

// ISO-8859-1 text → BASE64 signature string
Bytes sig2   = signer.sign(Bytes.from("Hello Bob", ISO_8859_1));

Builder options

import static com.mirkocaserta.bruce.Bruce.Provider.*;

// String-based algorithm (open-ended, supports any JCA algorithm)
Signer signer = signerBuilder()
    .key(privateKey)
    .algorithm("SHA512withRSA")
    .provider(BOUNCY_CASTLE)  // optional, defaults to JCA
    // .provider("BC")        // string-based alternative
    .build();

// Enum-based algorithm (type-safe, IDE auto-completion)
Signer signer2 = signerBuilder()
    .key(privateKey)
    .algorithm(SignatureAlgorithm.SHA512_WITH_RSA)
    .provider(BOUNCY_CASTLE)  // optional
    .build();

Common SignatureAlgorithm constants: SHA256_WITH_RSA, SHA512_WITH_RSA, SHA256_WITH_ECDSA, SHA512_WITH_ECDSA, SHA256_WITH_DSA, RSASSA_PSS.

Interface

@FunctionalInterface
public interface Signer {
    Bytes sign(Bytes message);
}

Use Bytes factory methods to construct the message and .encode() / .asString() to consume the returned signature.


Signer by Key

Returns a SignerByKey that resolves the private key at runtime from a preconfigured map.

Usage examples

Map<String, PrivateKey> keys = Map.of("alice", aliceKey, "bob", bobKey);

SignerByKey signer = signerBuilder()
    .keys(keys)
    .algorithm("SHA512withRSA")
    .buildByKey();

// raw bytes → raw bytes
Bytes sig    = signer.sign("alice", Bytes.from("Hello Bob".getBytes(UTF_8)));

// UTF-8 text → BASE64 signature string
String b64   = signer.sign("alice", Bytes.from("Hello Bob")).encode(BASE64);

// UTF-8 text → HEX signature string
String hex   = signer.sign("bob", Bytes.from("Hello Alice")).encode(HEX);

Interface

@FunctionalInterface
public interface SignerByKey {
    Bytes sign(String privateKeyId, Bytes message);
}

Verification

Verifier

Returns a Verifier for the given public key and algorithm. Both the message and signature are passed as Bytes; construct signatures from encoded strings with Bytes.from(encoded, encoding).

Usage examples

KeyStore keystore = keystore("classpath:keystore.p12", "password".toCharArray(), "PKCS12");
PublicKey publicKey = publicKey(keystore, "alice");

Verifier verifier = verifierBuilder()
    .key(publicKey)
    .algorithm("SHA512withRSA")
    .build();

// raw bytes + raw bytes → boolean
boolean ok = verifier.verify(
    Bytes.from("Hello Bob".getBytes(UTF_8)),
    rawSignature);

// UTF-8 text + BASE64 signature → boolean
boolean ok2 = verifier.verify(
    Bytes.from("Hello Bob"),
    Bytes.from(base64Signature, BASE64));

// UTF-8 text + HEX signature → boolean
boolean ok3 = verifier.verify(
    Bytes.from("Hello Bob"),
    Bytes.from(hexSignature, HEX));

// ISO-8859-1 text + BASE64 signature → boolean
boolean ok4 = verifier.verify(
    Bytes.from("Hello Bob", ISO_8859_1),
    Bytes.from(base64Signature, BASE64));

Builder options

import static com.mirkocaserta.bruce.Bruce.Provider.*;

// String-based algorithm (open-ended, supports any JCA algorithm)
Verifier verifier = verifierBuilder()
    .key(publicKey)
    .algorithm("SHA512withRSA")
    .provider(BOUNCY_CASTLE)  // optional, defaults to JCA
    // .provider("BC")        // string-based alternative
    .build();

// Enum-based algorithm (type-safe, IDE auto-completion)
Verifier verifier2 = verifierBuilder()
    .key(publicKey)
    .algorithm(SignatureAlgorithm.SHA512_WITH_RSA)
    .provider(BOUNCY_CASTLE)  // optional
    .build();

Common SignatureAlgorithm constants: SHA256_WITH_RSA, SHA512_WITH_RSA, SHA256_WITH_ECDSA, SHA512_WITH_ECDSA, SHA256_WITH_DSA, RSASSA_PSS.

Interface

@FunctionalInterface
public interface Verifier {
    boolean verify(Bytes message, Bytes signature);
}

Verifier by Key

Returns a VerifierByKey that resolves the public key at runtime from a preconfigured map.

Usage examples

Map<String, PublicKey> keys = Map.of("alice", alicePublicKey, "bob", bobPublicKey);

VerifierByKey verifier = verifierBuilder()
    .keys(keys)
    .algorithm("SHA512withRSA")
    .buildByKey();

// raw bytes + raw bytes → boolean
boolean ok = verifier.verify("alice",
    Bytes.from("Hello Bob".getBytes(UTF_8)), rawSignature);

// UTF-8 text + BASE64 signature → boolean
boolean ok2 = verifier.verify("alice",
    Bytes.from("Hello Bob"),
    Bytes.from(base64Signature, BASE64));

// UTF-8 text + HEX signature → boolean
boolean ok3 = verifier.verify("bob",
    Bytes.from("Hello Alice"),
    Bytes.from(hexSignature, HEX));

Interface

@FunctionalInterface
public interface VerifierByKey {
    boolean verify(String publicKeyId, Bytes message, Bytes signature);
}

Symmetric Ciphers

All symmetric cipher instances are created via cipherBuilder() (static import from Bruce). Input and output use the Bytes universal type.

Encryptor

Returns a SymmetricEncryptor that encrypts messages with a fixed symmetric key.

Usage examples

// Generate a key and IV
byte[] keyBytes = symmetricKey("AES");
byte[] ivBytes  = new byte[16];
new SecureRandom().nextBytes(ivBytes);

SymmetricEncryptor encryptor = cipherBuilder()
    .key(keyBytes)
    .keyAlgorithm("AES")
    .algorithm("AES/CBC/PKCS5Padding")
    .buildSymmetricEncryptor();

Bytes iv         = Bytes.from(ivBytes);
Bytes ciphertext = encryptor.encrypt(iv, Bytes.from("Hello World"));

// serialize to BASE64 for transport
String ivB64  = iv.encode(BASE64);
String encB64 = ciphertext.encode(BASE64);

Builder options

import static com.mirkocaserta.bruce.Bruce.Provider.*;
import static com.mirkocaserta.bruce.Bruce.SymmetricKeyAlgorithm.*;
import static com.mirkocaserta.bruce.Bruce.CipherAlgorithm.*;

// String-based algorithms (open-ended, supports any JCA algorithm)
SymmetricEncryptor encryptor = cipherBuilder()
    .key(keyBytes)               // raw byte[] or Bytes
    .keyAlgorithm(AES)
    .algorithm(AES_CBC_PKCS5PADDING)
    .provider(BOUNCY_CASTLE)      // optional, defaults to JCA
    // .provider("BC")            // string-based alternative
    .buildSymmetricEncryptor();

// Enum-based algorithms (type-safe, IDE auto-completion)
SymmetricEncryptor encryptor2 = cipherBuilder()
    .key(keyBytes)
    .algorithms(SymmetricAlgorithm.AES, SymmetricCipherAlgorithm.AES_CBC_PKCS5)
    .provider(BOUNCY_CASTLE)      // optional
    .buildSymmetricEncryptor();

Common SymmetricAlgorithm key constants: AES, DES, DESEDE, BLOWFISH.

Common SymmetricCipherAlgorithm transformation constants: AES_CBC_PKCS5, AES_CBC_NO_PADDING, AES_GCM_NO_PADDING, AES_CTR_NO_PADDING, AES_ECB_PKCS5, DES_CBC_PKCS5, DESEDE_CBC_PKCS5.


Decryptor

Returns a SymmetricDecryptor that decrypts messages with a fixed symmetric key.

Usage examples

SymmetricDecryptor decryptor = cipherBuilder()
    .key(keyBytes)
    .keyAlgorithm("AES")
    .algorithm("AES/CBC/PKCS5Padding")
    .buildSymmetricDecryptor();

// raw bytes → Bytes
Bytes plaintext = decryptor.decrypt(iv, ciphertext);
String text     = plaintext.asString();   // UTF-8

// BASE64 strings → String
Bytes ivFromB64  = Bytes.from(ivB64, BASE64);
Bytes encFromB64 = Bytes.from(encB64, BASE64);
String decrypted = decryptor.decrypt(ivFromB64, encFromB64).asString();

Full round-trip

byte[] keyBytes = symmetricKey("DESede");
SymmetricEncryptor enc = cipherBuilder()
    .key(keyBytes).keyAlgorithm("DESede").algorithm("DESede/CBC/PKCS5Padding")
    .buildSymmetricEncryptor();
SymmetricDecryptor dec = cipherBuilder()
    .key(keyBytes).keyAlgorithm("DESede").algorithm("DESede/CBC/PKCS5Padding")
    .buildSymmetricDecryptor();

byte[] rawIv    = new byte[8];
new SecureRandom().nextBytes(rawIv);
Bytes iv        = Bytes.from(rawIv);

Bytes clearText    = Bytes.from("Hi there");
Bytes cipherText   = enc.encrypt(iv, clearText);
Bytes decryptedText = dec.decrypt(iv, cipherText);
assertEquals(clearText, decryptedText);

Encryptor / Decryptor by Key

For use-cases where the key is supplied at call time (e.g., per-user keys):

SymmetricEncryptorByKey encByKey = cipherBuilder()
    .keyAlgorithm("AES")
    .algorithm("AES/CBC/PKCS5Padding")
    .buildSymmetricEncryptorByKey();

SymmetricDecryptorByKey decByKey = cipherBuilder()
    .keyAlgorithm("AES")
    .algorithm("AES/CBC/PKCS5Padding")
    .buildSymmetricDecryptorByKey();

Bytes key        = Bytes.from(keyBytes);
Bytes iv         = Bytes.from(ivBytes);
Bytes ciphertext = encByKey.encrypt(key, iv, Bytes.from("Hello World"));
Bytes plaintext  = decByKey.decrypt(key, iv, ciphertext);

Interfaces

@FunctionalInterface
public interface SymmetricEncryptor {
    Bytes encrypt(Bytes iv, Bytes plaintext);
}

@FunctionalInterface
public interface SymmetricDecryptor {
    Bytes decrypt(Bytes iv, Bytes ciphertext);
}

@FunctionalInterface
public interface SymmetricEncryptorByKey {
    Bytes encrypt(Bytes key, Bytes iv, Bytes plaintext);
}

@FunctionalInterface
public interface SymmetricDecryptorByKey {
    Bytes decrypt(Bytes key, Bytes iv, Bytes ciphertext);
}

Asymmetric Ciphers

All asymmetric cipher instances are created via cipherBuilder() (static import from Bruce). Input and output use the Bytes universal type.

Encryptor

Returns an AsymmetricEncryptor that encrypts messages with an asymmetric public key.

Usage examples

KeyStore bobKeystore = keystore("classpath:/keystore-bob.p12", "password".toCharArray(), "PKCS12");
PublicKey bobPublicKey = publicKey(bobKeystore, "bob");

AsymmetricEncryptor encryptor = cipherBuilder()
    .key(bobPublicKey)
    .algorithm("RSA/ECB/PKCS1Padding")
    .buildAsymmetricEncryptor();

// raw bytes → Bytes
Bytes encrypted = encryptor.encrypt(Bytes.from("Hello Bob".getBytes(UTF_8)));

// UTF-8 text → BASE64 string
String enc64 = encryptor.encrypt(Bytes.from("Hello Bob")).encode(BASE64);

// UTF-8 text → HEX string
String encHex = encryptor.encrypt(Bytes.from("Hello Bob")).encode(HEX);

Builder options

import static com.mirkocaserta.bruce.Bruce.Provider.*;
import static com.mirkocaserta.bruce.Bruce.CipherAlgorithm.*;

// String-based algorithm (open-ended, supports any JCA algorithm)
AsymmetricEncryptor encryptor = cipherBuilder()
    .key(publicKey)
    .algorithm(RSA_ECB_PKCS1PADDING)
    .provider(BOUNCY_CASTLE)  // optional, defaults to JCA
    // .provider("BC")        // string-based alternative
    .buildAsymmetricEncryptor();

// Enum-based algorithm (type-safe, IDE auto-completion)
AsymmetricEncryptor encryptor2 = cipherBuilder()
    .key(publicKey)
    .algorithm(AsymmetricAlgorithm.RSA_ECB_PKCS1)
    .provider(BOUNCY_CASTLE)  // optional
    .buildAsymmetricEncryptor();

Available AsymmetricAlgorithm constants: RSA, RSA_ECB_PKCS1, RSA_ECB_OAEP_SHA1_MGF1, RSA_ECB_OAEP_SHA256_MGF1, RSA_ECB_OAEP_SHA384_MGF1, RSA_ECB_OAEP_SHA512_MGF1, RSA_ECB_NO_PADDING.


Decryptor

Returns an AsymmetricDecryptor that decrypts messages with an asymmetric private key.

Usage examples

KeyStore bobKeystore = keystore("classpath:/keystore-bob.p12", "password".toCharArray(), "PKCS12");
PrivateKey bobPrivateKey = privateKey(bobKeystore, "bob", "password".toCharArray());

AsymmetricDecryptor decryptor = cipherBuilder()
    .key(bobPrivateKey)
    .algorithm("RSA/ECB/PKCS1Padding")
    .buildAsymmetricDecryptor();

// Bytes → Bytes
Bytes plain = decryptor.decrypt(encrypted);
String text = plain.asString();

// BASE64 string → String
String plain2 = decryptor.decrypt(Bytes.from(enc64, BASE64)).asString();

// HEX string → String
String plain3 = decryptor.decrypt(Bytes.from(encHex, HEX)).asString();

Full Alice ↔ Bob round-trip

KeyStore aliceKs = keystore("classpath:/keystore-alice.p12", "password".toCharArray(), "PKCS12");
KeyStore bobKs   = keystore("classpath:/keystore-bob.p12",   "password".toCharArray(), "PKCS12");

AsymmetricEncryptor encryptForBob   = cipherBuilder().key(publicKey(bobKs, "bob")).algorithm("RSA/ECB/PKCS1Padding").buildAsymmetricEncryptor();
AsymmetricDecryptor decryptAsBob    = cipherBuilder().key(privateKey(bobKs, "bob", "password".toCharArray())).algorithm("RSA/ECB/PKCS1Padding").buildAsymmetricDecryptor();
AsymmetricEncryptor encryptForAlice = cipherBuilder().key(publicKey(aliceKs, "alice")).algorithm("RSA/ECB/PKCS1Padding").buildAsymmetricEncryptor();
AsymmetricDecryptor decryptAsAlice  = cipherBuilder().key(privateKey(aliceKs, "alice", "password".toCharArray())).algorithm("RSA/ECB/PKCS1Padding").buildAsymmetricDecryptor();

// Alice → Bob (raw bytes)
Bytes aliceMsg  = Bytes.from("Hello Bob");
Bytes encrypted = encryptForBob.encrypt(aliceMsg);
Bytes decrypted = decryptAsBob.decrypt(encrypted);
assertEquals(aliceMsg, decrypted);

// Bob → Alice (via BASE64 strings)
String bobMsg  = "Hey Alice!";
String enc64   = encryptForAlice.encrypt(Bytes.from(bobMsg)).encode(BASE64);
String dec64   = decryptAsAlice.decrypt(Bytes.from(enc64, BASE64)).asString();
assertEquals(bobMsg, dec64);

Encryptor / Decryptor by Key

For runtime key selection:

Map<String, Key> pubKeys  = Map.of("alice", alicePub, "bob", bobPub);
Map<String, Key> privKeys = Map.of("alice", alicePriv, "bob", bobPriv);

AsymmetricEncryptorByKey encryptors = cipherBuilder().keys(pubKeys).algorithm("RSA/ECB/PKCS1Padding").buildAsymmetricEncryptorByKey();
AsymmetricDecryptorByKey decryptors = cipherBuilder().keys(privKeys).algorithm("RSA/ECB/PKCS1Padding").buildAsymmetricDecryptorByKey();

Bytes enc = encryptors.encrypt("bob", Bytes.from("Hello Bob"));
Bytes dec = decryptors.decrypt("bob", enc);

Interfaces

@FunctionalInterface
public interface AsymmetricEncryptor {
    Bytes encrypt(Bytes plaintext);
}

@FunctionalInterface
public interface AsymmetricDecryptor {
    Bytes decrypt(Bytes ciphertext);
}

@FunctionalInterface
public interface AsymmetricEncryptorByKey {
    Bytes encrypt(String keyId, Bytes plaintext);
}

@FunctionalInterface
public interface AsymmetricDecryptorByKey {
    Bytes decrypt(String keyId, Bytes ciphertext);
}

Message Authentication Codes

Mac

Returns a Mac for the given key and algorithm. All input and output use the Bytes universal type.

Usage examples

KeyStore keystore = keystore("classpath:/keystore.p12", "password".toCharArray(), "PKCS12");
Key key = secretKey(keystore, "hmac", "password".toCharArray());

Mac mac = macBuilder().key(key).algorithm("HmacSHA256").build();

// raw bytes → Bytes
Bytes rawMac = mac.get(Bytes.from("Hello there".getBytes(UTF_8)));

// UTF-8 text → BASE64 string
String b64 = mac.get(Bytes.from("Hello there")).encode(BASE64);

// UTF-8 text → HEX string
String hex = mac.get(Bytes.from("Hello there")).encode(HEX);

// explicit charset → BASE64 string
String b64_2 = mac.get(Bytes.from("Hello 👋🏻", UTF_16)).encode(BASE64);

// Verify both parties produce the same MAC
Mac alice = macBuilder().key(key).algorithm("HmacSHA256").build();
Mac bob   = macBuilder().key(key).algorithm("HmacSHA256").build();

Bytes aliceMac = alice.get(Bytes.from("Hi Bob"));
Bytes bobMac   = bob.get(Bytes.from("Hi Bob"));
assertEquals(aliceMac, bobMac);

// compare as encoded strings
assertEquals(aliceMac.encode(BASE64), bobMac.encode(BASE64));

Builder options

import static com.mirkocaserta.bruce.Bruce.Provider.*;

// String-based algorithm (open-ended, supports any JCA algorithm)
Mac mac = macBuilder()
    .key(secretKey)
    .algorithm("HmacSHA256")
    .provider(BOUNCY_CASTLE)  // optional, defaults to JCA
    // .provider("BC")        // string-based alternative
    .build();

// Enum-based algorithm (type-safe, IDE auto-completion)
Mac mac2 = macBuilder()
    .key(secretKey)
    .algorithm(MacAlgorithm.HMAC_SHA_256)
    .provider(BOUNCY_CASTLE)  // optional
    .build();

Available MacAlgorithm constants: HMAC_MD5, HMAC_SHA_1, HMAC_SHA_224, HMAC_SHA_256, HMAC_SHA_384, HMAC_SHA_512, HMAC_SHA_512_224, HMAC_SHA_512_256, HMAC_SHA3_224, HMAC_SHA3_256, HMAC_SHA3_384, HMAC_SHA3_512.

Interface

@FunctionalInterface
public interface Mac {
    Bytes get(Bytes message);
}

Input / output combinations

InputHow to constructConsume output
raw byte[]Bytes.from(rawBytes).asBytes()
UTF-8 textBytes.from("text").encode(HEX) / .encode(BASE64)
custom charsetBytes.from("text", charset).encode(...)
encoded stringBytes.from("abc…", Encoding.BASE64).encode(...)