Encrypting images and keys - Java examples
-
Install two libraries required to perform the cryptographic operations in 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") } -
Next, 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 the RSA public key required by the next step:
public class CypherPoc { public static void main(String[] args) throws Exception { if (Security.getProvider(PROVIDER_NAME) == null) { Security.insertProviderAt(new BouncyCastleProvider(), 1); } CypherPoc cypherPoc = new CypherPoc(); SecretKey keyToEncrypt = cypherPoc.aesGcmSiv(); // RSAES-OAEP-SHA-256 String keyUsedToEncrypt = """ -----BEGIN PUBLIC KEY----- The public key base64 -----END PUBLIC KEY-----"""; byte[] encryptedKey = cypherPoc.encryptKey(keyUsedToEncrypt, keyToEncrypt); System.out.println("Encrypted Key: " + HexUtils.toHexString(encryptedKey)); } public SecretKey aesGcmSiv() { GCMSIVCrypter crypter = new GCMSIVCrypter(); SecretKey secretKey = crypter.generateKey(new SecureRandom()); return secretKey; } public byte[] encryptKey(String keyUsedToEncrypt, SecretKey keyToEncrypt) throws Exception { PemReader pemReader = new PemReader(new StringReader(keyUsedToEncrypt)); PemObject pemObject = pemReader.readPemObject(); byte[] content = pemObject.getContent(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(content); PublicKey publicKey = keyFactory.generatePublic(keySpec); Cipher instance = Cipher.getInstance("RSA/ECB/OAEPWITHSHA256ANDMGF1PADDING"); instance.init(Cipher.ENCRYPT_MODE, publicKey); return instance.doFinal(keyToEncrypt.getEncoded()); } }