Professional Documents
Culture Documents
Exercise 4
Exercise 4
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
localhost:4649/?mode=clike 2/2