Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions src/main/java/com/thealgorithms/ciphers/AESEncryption.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import java.security.InvalidAlgorithmParameterException;

/**
* This example program shows how AES encryption and decryption can be done in
Expand All @@ -13,6 +15,7 @@
public class AESEncryption {

private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
private static Cipher aesCipher;

/**
* 1. Generate a plain text for encryption 2. Get a secret key (printed in
Expand Down Expand Up @@ -62,7 +65,7 @@ public static SecretKey getSecretEncryptionKey()
public static byte[] encryptText(String plainText, SecretKey secKey)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
return aesCipher.doFinal(plainText.getBytes());
}
Expand All @@ -73,11 +76,13 @@ public static byte[] encryptText(String plainText, SecretKey secKey)
* @return plainText
*/
public static String decryptText(byte[] byteCipherText, SecretKey secKey)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.DECRYPT_MODE, secKey);
byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, aesCipher.getIV());
decryptionCipher.init(Cipher.DECRYPT_MODE, secKey, gcmParameterSpec);
byte[] bytePlainText = decryptionCipher.doFinal(byteCipherText);
return new String(bytePlainText);
}

Expand Down