· 7 years ago · Nov 01, 2018, 10:42 AM
1import java.util.Base64;
2import javax.crypto.Cipher;
3import javax.crypto.KeyGenerator;
4import javax.crypto.SecretKey;
5
6public class EncryptionDecryptionAES {
7 static Cipher cipher;
8
9 public static void main(String[] args) throws Exception {
10 /*
11 create key
12 If we need to generate a new key use a KeyGenerator
13 If we have existing plaintext key use a SecretKeyFactory
14 */
15 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
16 keyGenerator.init(128); // block size is 128bits
17 SecretKey secretKey = keyGenerator.generateKey();
18
19 /*
20 Cipher Info
21 Algorithm : for the encryption of electronic data
22 mode of operation : to avoid repeated blocks encrypt to the same values.
23 padding: ensuring messages are the proper length necessary for certain ciphers
24 mode/padding are not used with stream cyphers.
25 */
26 cipher = Cipher.getInstance("AES"); //SunJCE provider AES algorithm, mode(optional) and padding schema(optional)
27
28 String plainText = "AES Symmetric Encryption Decryption";
29 System.out.println("Plain Text Before Encryption: " + plainText);
30
31 String encryptedText = encrypt(plainText, secretKey);
32 System.out.println("Encrypted Text After Encryption: " + encryptedText);
33
34 String decryptedText = decrypt(encryptedText, secretKey);
35 System.out.println("Decrypted Text After Decryption: " + decryptedText);
36 }
37
38 public static String encrypt(String plainText, SecretKey secretKey)
39 throws Exception {
40 byte[] plainTextByte = plainText.getBytes();
41 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
42 byte[] encryptedByte = cipher.doFinal(plainTextByte);
43 Base64.Encoder encoder = Base64.getEncoder();
44 String encryptedText = encoder.encodeToString(encryptedByte);
45 return encryptedText;
46 }
47
48 public static String decrypt(String encryptedText, SecretKey secretKey)
49 throws Exception {
50 Base64.Decoder decoder = Base64.getDecoder();
51 byte[] encryptedTextByte = decoder.decode(encryptedText);
52 cipher.init(Cipher.DECRYPT_MODE, secretKey);
53 byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
54 String decryptedText = new String(decryptedByte);
55 return decryptedText;
56 }
57}