For AES, always use a random IvParameterSpec and AES/GCM/NoPadding for modern security.
In symmetric encryption, the same key is used for both encrypting and decrypting. is the industry standard. Public And Private Key Encryption In Java
Implementing Public Key (Asymmetric) and Private Key (Symmetric) encryption in Java is straightforward using the built-in . 1. Private Key Encryption (Symmetric) For AES, always use a random IvParameterSpec and
Never hardcode keys. Use the Java KeyStore (JKS) or a cloud-based Vault. Use the Java KeyStore (JKS) or a cloud-based Vault
import java.security.KeyPair; import java.security.KeyPairGenerator; import javax.crypto.Cipher; import java.util.Base64; public class AsymmetricExample { public static void main(String[] args) throws Exception { String data = "Secret Message"; // 1. Generate Key Pair KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair pair = keyGen.generateKeyPair(); // 2. Encrypt with Public Key Cipher encryptCipher = Cipher.getInstance("RSA"); encryptCipher.init(Cipher.ENCRYPT_MODE, pair.getPublic()); byte[] encryptedBytes = encryptCipher.doFinal(data.getBytes()); // 3. Decrypt with Private Key Cipher decryptCipher = Cipher.getInstance("RSA"); decryptCipher.init(Cipher.DECRYPT_MODE, pair.getPrivate()); byte[] decryptedBytes = decryptCipher.doFinal(encryptedBytes); System.out.println("Decrypted: " + new String(decryptedBytes)); } } Use code with caution. Key Differences Symmetric (AES) Asymmetric (RSA) One shared key Two keys (Public & Private) Speed Slow (computationally heavy) Use Case Bulk data encryption Secure key exchange & Digital Signatures Security Best Practices
Asymmetric encryption uses a : a Public Key for encryption and a Private Key for decryption. RSA is the most common algorithm for this.
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import java.util.Base64; public class SymmetricExample { public static void main(String[] args) throws Exception { String data = "Hello World"; // 1. Generate a Secret Key SecretKey key = KeyGenerator.getInstance("AES").generateKey(); // 2. Encrypt Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encryptedBytes = cipher.doFinal(data.getBytes()); String encryptedData = Base64.getEncoder().encodeToString(encryptedBytes); // 3. Decrypt cipher.init(Cipher.DECRYPT_MODE, key); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData)); System.out.println("Decrypted: " + new String(decryptedBytes)); } } Use code with caution. 2. Public/Private Key Encryption (Asymmetric)