· 7 years ago · Mar 14, 2018, 08:54 AM
1import java.security.Key;
2import java.security.KeyPair;
3import java.security.KeyPairGenerator;
4import java.security.SecureRandom;
5import java.security.interfaces.RSAPrivateCrtKey;
6import java.security.interfaces.RSAPrivateKey;
7import java.security.interfaces.RSAPublicKey;
8import java.security.spec.RSAKeyGenParameterSpec;
9import java.util.ArrayList;
10
11import javax.crypto.Cipher;
12import javax.crypto.KeyGenerator;
13import javax.crypto.SecretKey;
14import javax.crypto.SecretKeyFactory;
15import javax.crypto.spec.GCMParameterSpec;
16import javax.crypto.spec.PBEKeySpec;
17import javax.crypto.spec.SecretKeySpec;
18
19import java.awt.List;
20import java.io.BufferedReader;
21import java.io.FileNotFoundException;
22import java.io.FileReader;
23import java.io.IOException;
24import java.math.BigInteger;
25public class Tutorial2 {
26
27 /**
28 * @param args
29 * @throws Exception
30 */
31 public static void main(String[] args) throws Exception {
32
33 String pass = "password";
34 String salty = "0E0A4A729188F12F52C85F692DDAD154";
35 String hexIV = "f8f3abeec32dc69e75d4451093f9bcdb";
36 String encryptedText = "7158C91A594DF409A07819A15F7D663520F07C784C4B2C0E4AFA5CB5FF59";
37 byte [] salt = hexStringToByteArray(salty);
38 //byte [] pswd = hexStringToByteArray(pass);
39 byte [] iv = hexStringToByteArray(hexIV);
40 byte [] cipher = hexStringToByteArray(encryptedText);
41 SecretKey trying = deriveAESkeyfromPbkdf2(pass.toCharArray(),salt,1000,256);
42 byte[] trophy = decryptWithAESGCM(trying, iv, 128, salt, cipher);
43
44 System.out.println(salt);
45 }
46
47 public static byte[] hexStringToByteArray(String s) {
48 int len = s.length();
49 byte[] data = new byte[len / 2];
50 for (int i = 0; i < len; i += 2) {
51 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
52 + Character.digit(s.charAt(i+1), 16));
53 }
54 return data;
55 }
56
57 public static SecretKey deriveAESkeyfromPbkdf2(char[] passwd, byte[] salt, int iteration, int keyLen) throws Exception
58 {
59 //init PBKDF2
60 SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
61 PBEKeySpec keySpec = new PBEKeySpec(passwd, salt, iteration, keyLen);
62
63 // derive secret key
64 SecretKey s = keyFac.generateSecret(keySpec);
65 SecretKey key = new SecretKeySpec(s.getEncoded(),"AES");
66
67 return key;
68 }
69
70 public static byte[] decryptWithAESGCM(SecretKey key, byte[] iv, int tagLen, byte[] aad, byte[] ciphertext) throws Exception
71 {
72 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
73 GCMParameterSpec spec = new GCMParameterSpec(tagLen, iv);
74 cipher.init(Cipher.DECRYPT_MODE, key, spec);
75
76 cipher.updateAAD(aad);
77
78 byte[] plainText = cipher.doFinal(ciphertext);
79
80 return plainText;
81 }
82}