A .key file, when it contains a symmetric key like an AES key, is typically in binary format. This binary format is not human-readable and cannot be meaningfully viewed or edited with a text editor.
Step 3: Load the key and use it for encryption decryption
Method 1: Using static Initialization Vector (IV)
importjava.util.Base64;importjavax.crypto.Cipher;importjavax.crypto.spec.IvParameterSpec;importjavax.crypto.spec.SecretKeySpec;importjava.nio.file.Files;importjava.nio.file.Paths;importjava.security.Security;importorg.bouncycastle.jce.provider.BouncyCastleProvider;publicclassEncryptionDecryption {publicstaticfinalString TRANSFORMATION ="AES/CBC/PKCS7Padding";publicstaticfinalString AES_ALGORITHM ="AES";publicstaticfinalString PROVIDER ="BC";static {Security.addProvider(newBouncyCastleProvider()); }publicstaticvoidmain(String[] args) throwsException { String storeBasePath = "/Users/pranayp/Documents/Project/Personal/sample-java-project/src/main/resources/store/";
byte[] keyBytes =Files.readAllBytes(Paths.get(storeBasePath +"myaeskey.key"));SecretKeySpec secretKey =newSecretKeySpec(keyBytes, AES_ALGORITHM);String originalText ="123456";System.out.println("Original Text: "+ originalText);// A static IV is used here for simplicity.// In a real application, we should use a securely generated random IV for each encryption operation.byte[] iv =newbyte[16];IvParameterSpec ivParameterSpec =newIvParameterSpec(iv);byte[] encryptedText =encrypt(originalText.getBytes(), secretKey, ivParameterSpec);System.out.println("Encrypted Text: "+newString(encryptedText));String encryptedTextBase64 =Base64.getEncoder().encodeToString(encryptedText);System.out.println("Encrypted Text (Base64): "+ encryptedTextBase64);byte[] decryptedText =decrypt(encryptedText, secretKey, ivParameterSpec);System.out.println("Decrypted Text: "+newString(decryptedText)); }publicstaticbyte[] encrypt(byte[] plaintext,SecretKeySpec key,IvParameterSpec iv) throwsException {Cipher cipher =Cipher.getInstance(TRANSFORMATION, PROVIDER);cipher.init(Cipher.ENCRYPT_MODE, key, iv);returncipher.doFinal(plaintext); }publicstaticbyte[] decrypt(byte[] ciphertext,SecretKeySpec key,IvParameterSpec iv) throwsException {Cipher cipher =Cipher.getInstance(TRANSFORMATION, PROVIDER);cipher.init(Cipher.DECRYPT_MODE, key, iv);returncipher.doFinal(ciphertext); }}
Usually, Base64 excrypted text is shared among applications (say Web/Mobile Application sending to Backend in an API or vice versa)
Method 2: Using dynamic Initialization Vector (IV) with key in hex format
Always ensure that the IV used for encryption is the same one used for decryption. Proper handling and storage of the IV are essential for secure cryptographic operations.
Note that default blocksize of AES is 16 byte (128 bits)
importstaticorg.bouncycastle.util.encoders.Base64.encode;importjava.io.ByteArrayOutputStream;importjava.security.SecureRandom;importjava.security.Security;importjava.util.Arrays;importjavax.crypto.Cipher;importjavax.crypto.SecretKey;importjavax.crypto.spec.IvParameterSpec;importjavax.crypto.spec.SecretKeySpec;importorg.bouncycastle.jce.provider.BouncyCastleProvider;importorg.bouncycastle.util.encoders.Base64;importorg.bouncycastle.util.encoders.Hex;publicclassEncryptionDecryptionWithHexKey {publicstaticfinalString TRANSFORMATION ="AES/CBC/PKCS7Padding";publicstaticfinalString AES_ALGORITHM ="AES";publicstaticfinalString PROVIDER ="BC";static {Security.addProvider(newBouncyCastleProvider()); }publicstaticvoidmain(String[] args) throwsException {String keyInHexFormat ="b5928408ed8d846e5a12f5642d94808dd52c1b74bdfb6365a84f606fc1574cd0";String originalText ="123456";System.out.println("Original Text: "+ originalText);String encryptedText =encrypt(originalText, keyInHexFormat);System.out.println("Encrypted Text: "+ encryptedText);String decryptedText =decrypt(encryptedText, keyInHexFormat);System.out.println("Decrypted Text: "+ decryptedText); }publicstaticStringencrypt(String plainText,String secretKeyInHex) throwsException {SecretKey secret =newSecretKeySpec(Hex.decode(secretKeyInHex), AES_ALGORITHM);Cipher cipher =Cipher.getInstance(TRANSFORMATION, PROVIDER);// Generate IVbyte[] iv =newbyte[cipher.getBlockSize()];newSecureRandom().nextBytes(iv);// Initialize the cipher in encryption mode with the secret key and the IV.cipher.init(Cipher.ENCRYPT_MODE, secret,newIvParameterSpec(iv));// Prepend IV to the ciphertext so that it can be extracted during decryptionByteArrayOutputStream os =newByteArrayOutputStream();os.write(iv);os.write(cipher.doFinal(plainText.getBytes()));byte[] encodedBytes =os.toByteArray();// Encode to Base64 and returnbyte[] encodedBase64Bytes =encode(encodedBytes);returnnewString(encodedBase64Bytes); }publicstaticStringdecrypt(String ivAndCipherBase64Text,String secretKeyInHex) throwsException {byte[] ivAndCipherText =Base64.decode(ivAndCipherBase64Text);byte[] secretKey =Hex.decode(secretKeyInHex);SecretKey secret =newSecretKeySpec(secretKey, AES_ALGORITHM);Cipher cipher =Cipher.getInstance(TRANSFORMATION, PROVIDER);// Extract IV from the beginning of the ciphertextbyte[] iv =Arrays.copyOfRange(ivAndCipherText,0,cipher.getBlockSize());// Extract the actual ciphertextbyte[] cipherText =Arrays.copyOfRange(ivAndCipherText,cipher.getBlockSize(),ivAndCipherText.length);// Initialize the cipher in decryption mode with the secret key and the extracted IV.cipher.init(Cipher.DECRYPT_MODE, secret,newIvParameterSpec(iv));// Decrypt the actual ciphertextbyte[] decryptedBytes =cipher.doFinal(cipherText);returnnewString(decryptedBytes); }}