Not a Java developer but had to write a little Java code today at work, and I wasted a lot of time trying to get one of the examples above to work, so I wanted to go ahead and post a complete working example that you can pretty much copy and paste and get working. My plan was to just fix one of the examples above, but I found it was just easier to use this AI generated example from Google instead. I'm still used to looking up answers myself, and so in case someone else stumbles upon this Stack Overflow post, use this AI generated example as it's better than the other "answers" here on this page:
package com.yourpackagename.encryptdecrypt;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Scanner;
public class EncryptDecrypt {
public static SecretKey generateKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);
return keyGenerator.generateKey();
}
public static IvParameterSpec generateIv() {
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
return new IvParameterSpec(iv);
}
public static String encrypt(String algorithm, String input, SecretKey key, IvParameterSpec iv) throws Exception {
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] cipherText = cipher.doFinal(input.getBytes());
return Base64.getEncoder().encodeToString(cipherText);
}
public static String decrypt(String algorithm, String cipherText, SecretKey key, IvParameterSpec iv) throws Exception {
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText));
return new String(plainText);
}
public static void main(String[] args) throws Exception {
SecretKey key = generateKey();
IvParameterSpec iv = generateIv();
String algorithm = "AES/CBC/PKCS5Padding";
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter string to encrypt: ");
String input = scanner.nextLine(); // Read user input
String cipherText = encrypt(algorithm, input, key, iv);
String plainText = decrypt(algorithm, cipherText, key, iv);
System.out.println("Encrypted Text: " + cipherText);
System.out.println("Decrypted Text: " + plainText);
} catch (Exception e) {
System.out.println("ERROR: " + e.getMessage());
}
}
}
?symbol.Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");depending on your default provider.