Encrypting images and Keys - Java examples

First of all, we need to install two libraries in order to perform the cryptographic operations required by this flow:

// build.gradle.kts
dependencies {
    // if you're using a JDK version older than 8, check the docs at https://www.bouncycastle.org/documentation/documentation-java/#bouncy-castle-java-documentation
    implementation("org.bouncycastle:bcprov-jdk18on:1.78.1")
	implementation("org.apache.wicket:wicket-core:10.2.0")
}

Then, here’s how to encrypt images with AES-GCM-SIV:

public class CypherPoc {
    public static void main(String[] args) {
        // Important: make Bouncycastle available as the primary security provider
        if (Security.getProvider(PROVIDER_NAME) == null) {
            Security.insertProviderAt(new BouncyCastleProvider(), 1);
        }

        CypherPoc cypherPoc = new CypherPoc();
        cypherPoc.aesGcmSiv();
    }

    public void aesGcmSiv() {
        // defaults to AES-256-GCM-SIV
        GCMSIVCrypter crypter = new GCMSIVCrypter();
        SecretKey secretKey = crypter.generateKey(new SecureRandom());
        byte[] encrypt = crypter.encrypt("Hello, AES-GCM-SIV!".getBytes(), secretKey, new SecureRandom());
        byte[] decrypt = crypter.decrypt(encrypt, secretKey);
        System.out.println("Decrypted Text: " + new String(decrypt));
    }
}

Finally, here's an example of how to encrypt with RSA Public Key which is required next:

Last updated

Was this helpful?