· 7 years ago · Jan 22, 2019, 10:46 PM
1SecretKeySpec secret = getSecret(pPassword, salt, 10000, 512, "HmacSHA1");
2 //String keystring = BinaryToTextEncoders.encode("base64", secret.getEncoded());
3
4 //System.out.println("key:" + keystring);
5 byte[] data = getHashOfPassword(secret, pPassword, "HmacSHA1");
6 Base16Encoder encode = new Base16Encoder();
7 return encode.encode(data);
8 }
9 catch (NoSuchAlgorithmException exc) {
10 exc.printStackTrace();
11 return pPassword;
12 }
13 catch (InvalidKeySpecException exc) {
14 return pPassword;
15 }
16 catch (UnsupportedEncodingException exc) {
17 return pPassword;
18 }
19 catch (InvalidKeyException exc) {}
20 return pPassword;
21 }
22
23 private static SecretKeySpec getSecret(String password, byte[] salt, int iterations, int keyLength, String algorithm)
24 throws UnsupportedEncodingException, InvalidKeySpecException, NoSuchAlgorithmException {
25 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2With" + algorithm);
26
27 KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, keyLength);
28
29 SecretKey tmp = factory.generateSecret(spec);
30 System.out.println("Raw output of keys"+tmp.getEncoded());
31 return new SecretKeySpec(tmp.getEncoded(), algorithm);
32}
33
34private static byte[] getHashOfPassword(SecretKeySpec secret, String plainPassword, String algorithm)
35 throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
36 Mac mac = Mac.getInstance(algorithm);
37
38 mac.init(secret);
39 byte[] password = plainPassword.getBytes("UTF-8");
40
41 byte[] hashedPassword = mac.doFinal(password);
42 return hashedPassword;
43}
44
45System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
46
47
48 byte[] messageBytes = Encoding.UTF8.GetBytes(password);
49 String hashedvalue = "";
50
51
52 var pbkdf2 = new Rfc2898DeriveBytes(messageBytes, salt, 10000);
53 var key = pbkdf2.GetBytes(512);
54
55 Console.WriteLine("key---------:", key);
56 var hmacsha1 = new HMACSHA1(key);
57
58 byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);
59 hashedvalue = Encode(hashmessage);