Skip to content

Instantly share code, notes, and snippets.

@raidery
Created June 26, 2023 08:23
Show Gist options
  • Save raidery/506b14de5e90a135a7b0246dd817fe38 to your computer and use it in GitHub Desktop.
Save raidery/506b14de5e90a135a7b0246dd817fe38 to your computer and use it in GitHub Desktop.
Java code for using IvParameterSpec, AES/CFB/PKCS5Padding with SecureRandom for encryption and decryption
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM = "AES/CFB/PKCS5Padding";
private static final int KEY_SIZE = 128;
private static final int IV_SIZE = 16;
public static String encrypt(String key, String plainText) throws Exception {
byte[] keyBytes = key.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);
SecureRandom secureRandom = new SecureRandom();
byte[] iv = new byte[IV_SIZE];
secureRandom.nextBytes(iv);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes());
byte[] encryptedWithIV = new byte[iv.length + encrypted.length];
System.arraycopy(iv, 0, encryptedWithIV, 0, iv.length);
System.arraycopy(encrypted, 0, encryptedWithIV, iv.length, encrypted.length);
return Base64.getEncoder().encodeToString(encryptedWithIV);
}
public static String decrypt(String key, String encryptedText) throws Exception {
byte[] encryptedWithIV = Base64.getDecoder().decode(encryptedText);
byte[] iv = new byte[IV_SIZE];
System.arraycopy(encryptedWithIV, 0, iv, 0, iv.length);
byte[] encrypted = new byte[encryptedWithIV.length - iv.length];
System.arraycopy(encryptedWithIV, iv.length, encrypted, 0, encrypted.length);
byte[] keyBytes = key.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decrypted = cipher.doFinal(encrypted);
return new String(decrypted);
}
}
public static void main(String[] args) throws Exception {
String key = "1234567890123456";
String plainText = "Hello, world!";
String encryptedText = AESUtil.encrypt(key, plainText);
String decryptedText = AESUtil.decrypt(key, encryptedText);
System.out.println("Plain text: " + plainText);
System.out.println("Encrypted text: " + encryptedText);
System.out.println("Decrypted text: " + decryptedText);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment