You are on page 1of 2

12/20/21, 2:20 PM exercise4.

java

1 import javax.crypto.SecretKey;
2 import javax.crypto.SecretKeyFactory;
3 import javax.crypto.spec.PBEKeySpec;
4 import javax.xml.bind.DatatypeConverter;
5 import java.io.ByteArrayOutputStream;
6 import java.io.Console;
7 import java.io.IOException;
8 import java.security.NoSuchAlgorithmException;
9 import java.security.SecureRandom;
10 import java.security.spec.InvalidKeySpecException;
11
12 public class exercise4 {
13    public static void main(String[] args) {
14        Console console = System.console();
15
16        if (console == null) {
17            System.out.print("Console unavailable");
18            return;
19       }
20
21        String password = console.readLine("Enter password:");
22
23        try {
24            SecureRandom salt = new SecureRandom();
25            int salt_len = 32;
26            byte salt_bytes[] = new byte[salt_len];
27            salt.nextBytes(salt_bytes);
28
29            ByteArrayOutputStream data_to_hash = new ByteArrayOutputStream();
30            data_to_hash.write(salt_bytes, 0, salt_len);
31            data_to_hash.write(password.getBytes());
32
33            //#2#: Create an object of type SecretKeyFactory, by using
34            // SecretKeyFactory.getInstance() method. The getInstance() method
takes in a string,
35            //which represents the type of SecretKey that we’d like to
generate. Set it to
36            //"PBKDF2WithHmacSHA512". The result of
SecretKeyFactory.getInstance() is stored
37            //into a variable, called “skf”• and it is of data type
SecretKeyFactory.
38
39            SecretKeyFactory skf =
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
40
41            int keyLength = 256;
42            PBEKeySpec spec = new PBEKeySpec(password.toCharArray(),
salt_bytes, 1000, keyLength);
43            SecretKey key = skf.generateSecret(spec);
44            byte[] digest = key.getEncoded();
45
46            String hash_pwd =
DatatypeConverter.printHexBinary(digest).toUpperCase();
47
48            String salt_str =
DatatypeConverter.printHexBinary(salt_bytes).toUpperCase();
49
50            console.printf("Storing into db hash:" + hash_pwd);
51            console.printf("\n");

localhost:4649/?mode=clike 1/2
12/20/21, 2:20 PM exercise4.java

52            console.printf("Storing into db salt:" + salt_str);


53            console.printf("\n");
54
55       } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
56            System.out.print("MD5 not supported for some reason");
57            return;
58       } catch (IOException e) {
59            System.out.print("Could not prepare data for hashing");
60            return;
61
62       }
63   }
64 }
65

localhost:4649/?mode=clike 2/2

You might also like