· 7 years ago · Jun 03, 2018, 07:34 PM
1import java.io.*;
2import java.security.*;
3import java.util.Scanner;
4import javax.crypto.*;
5import javax.crypto.spec.IvParameterSpec;
6
7public class AES2 {
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-CTR.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/CTR/NoPadding");
24 aes.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[16]));
25
26 // cipher message
27 byte[] plainText;
28 System.out.println("Give me message which you want encrypt: ");
29 Scanner sc = new Scanner(System.in);
30 plainText = sc.nextLine().getBytes();
31
32 // byte[] plainText = "hello".getBytes();
33
34 out.println("Message : " + new String(plainText));
35
36 // Encrypt message
37 startTime = System.nanoTime();
38 byte[] textEncrypted = aes.doFinal(plainText);
39 endsTime1 = System.nanoTime() - startTime;
40 out.println("Message encryted: " + textEncrypted);
41
42 // Initialize the same cipher for decryption
43 aes.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(new byte[16]));
44
45 // Decrypt message
46 startTime = System.nanoTime();
47 byte[] textDecrypted = aes.doFinal(textEncrypted);
48 endsTime2 = System.nanoTime() - startTime;
49 out.println("Message decryted: " + new String(textDecrypted));
50
51 out.println("Encryption: " + endsTime1 + " ns");
52 out.println("Decryption: " + endsTime2 + " ns");
53 out.println();
54 System.setOut(out);
55 out.close();
56
57 } catch (NoSuchAlgorithmException e) {
58 e.printStackTrace();
59 } catch (NoSuchPaddingException e) {
60 e.printStackTrace();
61 } catch (InvalidKeyException e) {
62 e.printStackTrace();
63 } catch (IllegalBlockSizeException e) {
64 e.printStackTrace();
65 } catch (BadPaddingException e) {
66 e.printStackTrace();
67 } catch (FileNotFoundException e) {
68 e.printStackTrace();
69 } catch (InvalidAlgorithmParameterException e) {
70 // TODO Auto-generated catch block
71 e.printStackTrace();
72 }
73 }
74
75}