· 7 years ago · Oct 22, 2018, 08:36 PM
1/*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6
7package pod;
8import java.nio.charset.StandardCharsets;
9import javax.crypto.Cipher;
10import javax.crypto.spec.SecretKeySpec;
11/**
12 *
13 * @author Lukasz
14 */
15public class AdvancedEncryptionStandard {
16
17 private byte[] key;
18
19 private static final String ALGORITHM = "AES";
20
21 public AdvancedEncryptionStandard(byte[] key)
22 {
23 this.key = key;
24 }
25
26 /**
27 * Encrypts the given plain text
28 *
29 * @param plainText The plain text to encrypt
30 */
31 public byte[] encrypt(byte[] plainText) throws Exception
32 {
33 SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
34 Cipher cipher = Cipher.getInstance(ALGORITHM);
35 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
36
37 return cipher.doFinal(plainText);
38 }
39
40 /**
41 * Decrypts the given byte array
42 *
43 * @param cipherText The data to decrypt
44 */
45 public byte[] decrypt(byte[] cipherText) throws Exception
46 {
47 SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
48 Cipher cipher = Cipher.getInstance(ALGORITHM);
49 cipher.init(Cipher.DECRYPT_MODE, secretKey);
50
51 return cipher.doFinal(cipherText);
52 }
53
54 /**
55 * @param args the command line arguments
56 */
57 public static void main(String[] args) throws Exception {
58 // TODO code application logic here
59 byte[] encryptionKey = "MZygpewJsCpRrfOr".getBytes(StandardCharsets.UTF_8);
60 byte[] plainText = "Hello world!".getBytes(StandardCharsets.UTF_8);
61 AdvancedEncryptionStandard advancedEncryptionStandard = new AdvancedEncryptionStandard(
62 encryptionKey);
63 byte[] cipherText = advancedEncryptionStandard.encrypt(plainText);
64 byte[] decryptedCipherText = advancedEncryptionStandard.decrypt(cipherText);
65
66 System.out.println(new String(plainText));
67 System.out.println(new String(cipherText));
68 System.out.println(new String(decryptedCipherText));
69 }
70
71}