mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 09:06:51 +08:00
@ -3,6 +3,8 @@ package com.thealgorithms.ciphers;
|
||||
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
|
||||
@ -13,6 +15,7 @@ import javax.crypto.*;
|
||||
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
|
||||
@ -62,7 +65,7 @@ public class AESEncryption {
|
||||
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());
|
||||
}
|
||||
@ -73,11 +76,13 @@ public class AESEncryption {
|
||||
* @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);
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user