· 5 years ago · Nov 21, 2019, 01: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
7
8
9package lab7;
10
11
12
13import java.security.SecureRandom;
14import java.util.Scanner;
15import javax.crypto.spec.IvParameterSpec;
16import java.security.Key;
17import java.security.KeyPair;
18import java.security.KeyPairGenerator;
19import java.security.NoSuchAlgorithmException;
20import java.security.Security;
21import java.security.SecureRandom;
22import javax.crypto.Cipher;
23import javax.crypto.NoSuchPaddingException;
24import javax.crypto.SecretKey;
25import javax.crypto.SecretKeyFactory;
26import javax.crypto.spec.PBEKeySpec;
27import javax.crypto.spec.SecretKeySpec;
28
29import java.math.BigInteger;
30import java.security.NoSuchAlgorithmException;
31import java.security.SecureRandom;
32import java.security.spec.InvalidKeySpecException;
33import javax.crypto.SecretKey;
34import javax.crypto.SecretKeyFactory;
35import javax.crypto.spec.PBEKeySpec;
36import javax.crypto.spec.SecretKeySpec;
37/**
38 *
39 * @author student
40 */
41public class Lab7 {
42
43 /**
44 * @param args the command line arguments
45 */
46
47 static byte[] salt = new byte[16];
48 static int iterations = 1000;
49 static IvParameterSpec iv;
50 static Cipher myAES;
51
52 static void init_params() throws NoSuchAlgorithmException, NoSuchPaddingException {
53 SecureRandom rng = new SecureRandom();
54 rng.nextBytes(salt);
55 byte[] myiv = new byte[16];
56 rng.nextBytes(myiv);
57 Lab7.iv = new IvParameterSpec(myiv);
58
59
60 // set salt values to random
61 rng.nextBytes(Lab7.salt);
62
63
64
65 Lab7.myAES = Cipher.getInstance("AES/CBC/NoPadding");
66
67 }
68
69 static void encrypt(String message, String password) throws Exception {
70 Lab7.init_params();
71 // plaintext must be a multiple of 16 when initialized
72 //byte[] plaintext = new byte[R1.myAES.getOutputSize(message.length())*16];
73 byte[] plaintext = new byte[message.length() * 16];
74
75 byte[] raw_message = message.getBytes();
76 for(int i = 0; i < raw_message.length; i++)
77 plaintext[i] = raw_message[i];
78
79
80 // TODO: derive AES key from password
81
82 // initialize key factory for HMAC-SHA1 derivation
83 SecretKeyFactory keyFactory =SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
84 // set key specification
85 int key_size = 128;
86 PBEKeySpec pbekSpec = new PBEKeySpec(password.toCharArray(), Lab7.salt, Lab7.iterations,key_size);
87 // generate the key
88 SecretKey myAESPBKey = new SecretKeySpec(keyFactory.generateSecret(pbekSpec).getEncoded(), "AES");
89
90
91 // TODO: encrypt the message
92 // Note: the encryption should work for any message size
93 // initialize AES objecy to encrypt mode
94 //initialize ciphertext
95 // byte[] ciphertext = new byte[R1.myAES.getOutputSize(message.length())*16];
96 byte[] ciphertext = new byte[16];
97
98 Lab7.myAES.init(Cipher.ENCRYPT_MODE, myAESPBKey,Lab7.iv);
99 plaintext = new byte[Lab7.myAES.getOutputSize(plaintext.length)];
100 ciphertext = new byte[Lab7.myAES.getOutputSize(plaintext.length)];
101 int cLength = Lab7.myAES.update(plaintext, 0, plaintext.length, ciphertext, 0);
102 // process remaining blocks of plaintext
103 cLength += Lab7.myAES.doFinal(ciphertext, cLength);
104
105 System.out.println("ciphertext: " + javax.xml.bind.DatatypeConverter.printHexBinary(ciphertext));
106 // TODO: print the encrypted message as HEX string
107
108 }
109
110 static void decrypt(String message, String password) throws Exception {
111 Lab7.init_params();
112 // use helper function to convert hex string to byte array
113 byte[] ciphertext = hexStringToByteArray(message);
114
115 // TODO: derive key from password
116 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
117 // set key specification
118 int key_size = 128;
119 PBEKeySpec pbekSpec = new PBEKeySpec(password.toCharArray(), Lab7.salt, Lab7.iterations,key_size);
120 // generate the key
121 SecretKey myAESPBKey = new SecretKeySpec(keyFactory.generateSecret(pbekSpec).getEncoded(), "AES");
122
123 // TODO: decrypt the ciphertext
124 // Note: the decryption should work for any message size
125
126 // initialize AES for decryption
127 Lab7.myAES.init(Cipher.DECRYPT_MODE, myAESPBKey,Lab7.iv);
128 // initialize a new array of bytes to place the decryption
129 // byte[] dec_plaintext = new byte[R1.myAES.getOutputSize(message.length())*16];
130 byte[] dec_plaintext = new byte[16];
131 dec_plaintext = new byte[Lab7.myAES.getOutputSize(ciphertext.length)];
132 int cLength = Lab7.myAES.update(ciphertext, 0, ciphertext.length, dec_plaintext, 0);
133 // process remaining blocks of ciphertext
134 cLength += Lab7.myAES.doFinal(dec_plaintext, cLength);
135
136 // TODO: print the recovered message
137 // print the new plaintext (hopefully identical to the initial one)
138 System.out.println("decrypted: " +javax.xml.bind.DatatypeConverter.printHexBinary(dec_plaintext));
139
140 }
141
142 static void run() throws Exception {
143 Scanner sc = new Scanner(System.in);
144 String mode;
145 String message;
146 String password;
147
148 init_params();
149
150 for(int i = 0; i < 5; i++) {
151
152 mode = sc.nextLine();
153 message = sc.nextLine();
154 password = sc.nextLine();
155
156 if(mode.equals("0")) {
157 encrypt(message, password);
158 }
159 else if(mode.equals("1"))
160 decrypt(message, password);
161 }
162 sc.close();
163 }
164
165 public static byte[] hexStringToByteArray(String s) {
166 int len = s.length();
167 byte[] data = new byte[len / 2];
168 for (int i = 0; i < len; i += 2) {
169 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
170 + Character.digit(s.charAt(i+1), 16));
171 }
172 return data;
173 }
174
175
176 public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
177 // TODO code application logic here
178 char[] password = "short_password".toCharArray();
179 byte[] salt = new byte[16];
180 int iteration_count = 10000;
181 int key_size = 32;
182 SecureRandom myPRNG = new SecureRandom();
183 myPRNG.nextBytes(salt);
184
185 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
186 PBEKeySpec pbekSpec = new PBEKeySpec(password, salt, iteration_count, key_size);
187 SecretKey myAESPBKey = new SecretKeySpec(keyFactory.generateSecret(pbekSpec).getEncoded(), "AES");
188 System.out.println("AES key: " +javax.xml.bind.DatatypeConverter.printHexBinary(myAESPBKey.getEncoded()));
189 }
190
191}