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