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:
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());
}
}Last updated
Was this helpful?