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