· 7 years ago · Feb 08, 2018, 02:56 PM
1package www;
2
3
4import java.io.BufferedInputStream;
5import java.io.BufferedOutputStream;
6import java.io.DataInputStream;
7import java.io.File;
8import java.io.FileInputStream;
9import java.io.FileNotFoundException;
10import java.io.FileOutputStream;
11import java.io.IOException;
12import java.io.RandomAccessFile;
13import java.security.InvalidAlgorithmParameterException;
14import java.security.InvalidKeyException;
15import java.security.KeyStore;
16import java.security.KeyStoreException;
17import java.security.MessageDigest;
18import java.security.NoSuchAlgorithmException;
19import java.security.NoSuchProviderException;
20import java.security.PrivateKey;
21import java.security.PublicKey;
22import java.security.Signature;
23import java.security.SignatureException;
24import java.security.UnrecoverableKeyException;
25import java.security.cert.CertificateException;
26import java.security.cert.CertificateFactory;
27import java.security.cert.X509Certificate;
28
29import javax.crypto.BadPaddingException;
30import javax.crypto.Cipher;
31import javax.crypto.IllegalBlockSizeException;
32import javax.crypto.NoSuchPaddingException;
33import javax.crypto.SecretKey;
34import javax.crypto.ShortBufferException;
35import javax.crypto.spec.IvParameterSpec;
36import javax.crypto.spec.SecretKeySpec;
37import javax.xml.bind.DatatypeConverter;
38
39public class Exam {
40
41 // provided method for getting the public key from a X509 certificate file
42 public static PublicKey getCertificateKey(String file) throws FileNotFoundException, CertificateException {
43 FileInputStream fis = new FileInputStream(file);
44
45 CertificateFactory factory = CertificateFactory.getInstance("X509");
46
47 X509Certificate certificate = (X509Certificate) factory.generateCertificate(fis);
48
49 return certificate.getPublicKey();
50 }
51
52 // provided method for checking a signature
53 public static boolean isVeryfied(String fileName, String signatureFileName, PublicKey key)
54 throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, IOException {
55
56 RandomAccessFile f = new RandomAccessFile(fileName, "r");
57 byte[] content = new byte[(int) f.length()];
58 f.readFully(content);
59 f.close();
60
61 RandomAccessFile dsFile = new RandomAccessFile(signatureFileName, "r");
62 byte[] ds = new byte[(int) dsFile.length()];
63 dsFile.readFully(ds);
64 dsFile.close();
65
66 Signature signature = Signature.getInstance("NONEwithRSA");
67 signature.initVerify(key);
68 signature.update(content);
69
70 return signature.verify(ds);
71
72 }
73
74 // method for getting the private key from a keystore
75 public static PrivateKey getPrivateKey(
76 String keyStoreFileName,
77 char[] keyStorePass,
78 String keyAlias,
79 char[] keyPass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
80 UnrecoverableKeyException {
81
82 FileInputStream fis = new FileInputStream(keyStoreFileName);
83 BufferedInputStream bis = new BufferedInputStream(fis);
84
85 KeyStore ks = KeyStore.getInstance("JKS");
86 ks.load(bis, keyStorePass);
87
88 PrivateKey privateKey = (PrivateKey)ks.getKey(keyAlias, keyPass);
89
90 bis.close();
91
92 return privateKey;
93 }
94
95 // method for computing the RSA digital signature
96 public static void generateDigitalSignature(
97 String inputFileName,
98 String signatureFileName,
99 PrivateKey key)
100 throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, IOException {
101
102 //generate and store the RSA digital signature of the inputFileName file
103 //store it in signatureFileName file
104
105 FileInputStream fis = new FileInputStream(inputFileName);
106 FileOutputStream fos = new FileOutputStream(signatureFileName);
107
108 byte[] buffer = new byte[8];
109 int noBytes;
110
111 Signature ds = Signature.getInstance("NONEwithRSA");
112 ds.initSign(key);
113
114 while((noBytes = fis.read(buffer)) != -1) {
115 ds.update(buffer);
116 }
117
118 byte[] signature = ds.sign();
119
120 fos.write(signature);
121
122 fis.close();
123 fos.close();
124 }
125
126 //proposed function for generating the hash value
127 public static byte[] getSHA1Hash(String fileName)
128 throws NoSuchAlgorithmException, NoSuchProviderException, IOException {
129
130 byte hash[] = null;
131 byte buffer[] = new byte[8];
132 FileInputStream fis = new FileInputStream(fileName);
133 int noBytes;
134
135 MessageDigest md = MessageDigest.getInstance("SHA-1");
136
137 while((noBytes = fis.read(buffer)) != -1) {
138 md.update(buffer, 0, noBytes);
139 }
140
141 fis.close();
142 hash = md.digest();
143
144 return hash;
145 }
146
147 //proposed function for decryption
148 public static void decryptAESCBC(
149 String inputFile,
150 String outputFile,
151 byte[] key,
152 byte[] initialIV)
153 throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException,
154 InvalidAlgorithmParameterException, IllegalBlockSizeException, ShortBufferException, BadPaddingException,
155 IOException {
156
157 //decrypt the input file using AES in CBC
158 //the file was encrypted without using padding - didn't need it
159
160 FileInputStream fis = new FileInputStream(inputFile);
161 FileOutputStream fos = new FileOutputStream(outputFile);
162
163 Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
164 SecretKey secretKey = new SecretKeySpec(key, "AES");
165 IvParameterSpec ivSpec = new IvParameterSpec(initialIV);
166 cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
167
168 byte[] buffer = new byte[cipher.getBlockSize()];
169 byte[] encBlock = null;
170 int noBytes = 0;
171
172 while ((noBytes = fis.read(buffer)) != -1) {
173 encBlock = new byte[cipher.getOutputSize(noBytes)];
174 int noEncBytes = cipher.update(buffer, 0, noBytes, encBlock);
175 fos.write(encBlock, 0, noEncBytes);
176 }
177
178 int noLastBytes = cipher.doFinal(encBlock, 0);
179 fos.write(encBlock, 0, noLastBytes);
180
181 fis.close();
182 fos.close();
183 }
184
185 public static void main(String[] args) {
186 try {
187
188
189 // AES CBC - decryption key
190 byte AES_KEY[] = { 0x2A, 0x4D, 0x61, 0x73, 0x74, 0x65, 0x72, 0x20, 0x49, 0x53, 0x4D,
191 0x20, 0x32, 0x30, 0x31, 0x37 };
192 // AES CBC - IV content
193 byte IV[] = new byte[AES_KEY.length];
194
195
196 //init the IV byte array with 1 for each byte
197 //...
198
199 for(int i = 0; i < AES_KEY.length; i++){
200 IV[i] = 1;
201 }
202
203 FileOutputStream fs = new FileOutputStream(new File("C:\\Users\\alexandm\\eclipse-workspace\\www\\www\\asd.txt"));
204 BufferedOutputStream bos = new BufferedOutputStream(fs);
205 bos.write(IV);
206 bos.close();
207 //Write IV to file
208
209 byte[] fileData = new byte[16];
210 DataInputStream dis = null;
211 dis = new DataInputStream(new FileInputStream(new File("C:\\Users\\alexandm\\eclipse-workspace\\www\\www\\asd.txt")));
212 dis.readFully(fileData);
213 // Read IV from file
214
215
216 System.out.println(DatatypeConverter.printHexBinary(fileData));
217 // 1. compute the hash value and print it in Hexadecimal
218
219 byte hashValue[] = getSHA1Hash("C:\\Users\\alexandm\\eclipse-workspace\\www\\www\\EncryptedMessage.cipher");
220 System.out.println(DatatypeConverter.printHexBinary(hashValue));
221
222 byte IV_2[] = new byte[16];
223 for (int i=0; i< IV_2.length; i++)
224 IV_2[i] = hashValue[i];
225 //Extract IV from hash
226
227 System.out.println(DatatypeConverter.printHexBinary(IV_2));
228
229 // 2. call a function to decrypt the input file EncryptedMessage.cipher
230 // there is no need for padding
231 // you should get OriginalMessage.txt file
232
233 decryptAESCBC("C:\\Users\\alexandm\\eclipse-workspace\\www\\www\\EncryptedMessage.cipher", "C:\\Users\\alexandm\\eclipse-workspace\\www\\www\\OriginalMessage.txt", AES_KEY, IV);
234
235
236 // 3. compute the RSA digital signature for the EncryptedMessage.cipher file
237 // store it in the signature.ds file
238
239 String keyStorePassword = "Secret1234ABCDEF"; //is in the OriginalMessage.txt file
240 PrivateKey privKey = getPrivateKey("C:\\Users\\alexandm\\eclipse-workspace\\www\\www\\examkeystore.ks", keyStorePassword.toCharArray(), "ismexam1", "passkey1".toCharArray());
241
242 generateDigitalSignature("C:\\Users\\alexandm\\eclipse-workspace\\www\\www\\OriginalMessage.txt", "C:\\Users\\alexandm\\eclipse-workspace\\www\\www\\FileSignature.ds", privKey);
243
244 // provided code for checking the signature
245 //don't change it
246 PublicKey pubKey = getCertificateKey("C:\\Users\\alexandm\\eclipse-workspace\\www\\www\\ISMExamCert.cer");
247
248 if (isVeryfied("C:\\Users\\alexandm\\eclipse-workspace\\www\\www\\OriginalMessage.txt", "C:\\Users\\alexandm\\eclipse-workspace\\www\\www\\FileSignature.ds", pubKey))
249 System.out.println("The file is ok");
250 else
251 System.out.println("We have a security breach");
252
253 System.out.println("Done");
254
255 } catch (Exception e) {
256 e.printStackTrace();
257 }
258 }
259}