Public And Private Key Encryption In Java Apr 2026
For AES, always use a random IvParameterSpec and AES/GCM/NoPadding for modern security.
Asymmetric encryption uses a : a Public Key for encryption and a Private Key for decryption. RSA is the most common algorithm for this. Public And Private Key Encryption In Java
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 For AES, always use a random IvParameterSpec and
In symmetric encryption, the same key is used for both encrypting and decrypting. is the industry standard. import java
Never hardcode keys. Use the Java KeyStore (JKS) or a cloud-based Vault.
Use at least 256-bit for AES and 2048-bit (or 3072-bit) for RSA.
