· 7 years ago · Jun 22, 2018, 11:00 PM
1import java.io.*;
2import java.security.*;
3import java.util.Scanner;
4import javax.crypto.*;
5
6
7public class AES {
8 public static void main(String[] argv) throws FileNotFoundException {
9 long startTime = System.nanoTime();
10 long endsTime1 = System.nanoTime() - startTime;
11 long endsTime2 = System.nanoTime() - startTime;
12 SecureRandom rand = new SecureRandom();
13
14 try {
15 // PrintStream out = new PrintStream(new FileOutputStream("AES-ECB.txt", true));
16 PrintStream out = System.out;
17
18 KeyGenerator keyGen = KeyGenerator.getInstance("AES");
19 keyGen.init(128, rand);
20 SecretKey secretKey = keyGen.generateKey();
21
22 Cipher aes;
23 aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
24 aes.init(Cipher.ENCRYPT_MODE, secretKey);
25
26 // cipher message
27 byte[] crypted = null;
28 System.out.println("Give me message which you want encrypt: ");
29 Scanner sc = new Scanner(System.in);
30 String input = sc.nextLine();
31// byte[] plainText = "tomek".getBytes();
32
33 out.println("Message : " + new String(input.getBytes()));
34
35 // Encrypt message
36 startTime = System.nanoTime();
37 crypted = aes.doFinal(input.getBytes());
38 endsTime1 = System.nanoTime() - startTime;
39
40 java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();
41 out.println("Message encryted: " + new String(encoder.encodeToString(crypted)));
42
43 // Initialize the same cipher for decryption
44 aes.init(Cipher.DECRYPT_MODE, secretKey);
45
46 // Decrypt message
47 startTime = System.nanoTime();
48 byte[] textDecrypted = aes.doFinal(crypted);
49 endsTime2 = System.nanoTime() - startTime;
50 out.println("Message decryted: " + new String(textDecrypted));
51
52 out.println("Encryption: " + endsTime1 + " ns");
53 out.println("Decryption: " + endsTime2 + " ns");
54 out.println();
55 System.setOut(out);
56 out.close();
57
58 } catch (NoSuchAlgorithmException e) {
59 e.printStackTrace();
60 } catch (NoSuchPaddingException e) {
61 e.printStackTrace();
62 } catch (InvalidKeyException e) {
63 e.printStackTrace();
64 } catch (IllegalBlockSizeException e) {
65 e.printStackTrace();
66 } catch (BadPaddingException e) {
67 e.printStackTrace();
68 // } catch (FileNotFoundException e) {
69 // e.printStackTrace();
70 }
71 }
72
73}