· 7 years ago · Oct 12, 2018, 11:34 PM
1import csc5055.flatdb.FlatDatabase;
2
3import java.io.*;
4import java.security.NoSuchAlgorithmException;
5import java.security.spec.InvalidKeySpecException;
6import java.util.Scanner;
7import javax.crypto.SecretKey;
8import javax.crypto.SecretKeyFactory;
9import javax.crypto.spec.PBEKeySpec;
10
11public class PasswordKeeper {
12 public static void main(String args[]) throws IOException {
13 //Create an array to hold fields for database file
14 String[] fields = {"Website","Username", "Password"};
15 //Create a database object
16 FlatDatabase passwords = new FlatDatabase();
17 //Create a scanner object to get user input
18 Scanner scan = new Scanner(System.in);
19 //Create a file to store the master password
20 File file = new File("password.txt");
21 FileWriter fw = new FileWriter(file);
22 BufferedWriter writer = new BufferedWriter(fw);
23 BufferedReader reader = new BufferedReader(new FileReader("password.txt"));
24 String masterPass;
25 System.out.println(reader.readLine());
26 //Check if a database file exists if not create a new one
27 if(new File("passwords.db").isFile()==false){
28 passwords.createDatabase("passwords.db", fields);
29 passwords.saveDatabase();
30 file.createNewFile();
31 System.out.println("Please enter a master password: ");
32 masterPass = scan.nextLine();
33 byte[] hashedPass = passData(masterPass);
34 String hashedPassString = hashedPass.toString();
35 System.out.println(hashedPassString);
36 writer.write(hashedPassString);
37
38 }
39 else{
40 System.out.println("Please enter a password: ");
41 String enteredPass = scan.nextLine();
42 byte[] enteredHashPass = passData(enteredPass);
43 System.out.println(reader.readLine());
44
45 }
46 writer.close();
47 fw.close();
48 reader.close();
49
50 }
51 public static byte[] hashedPass(final char[] password, final byte[] salt, final int iterations, final int keyLength){
52 try {
53 SecretKeyFactory skf = SecretKeyFactory.getInstance( "PBKDF2WithHmacSHA512" );
54 PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, keyLength );
55 SecretKey key = skf.generateSecret( spec );
56 byte[] res = key.getEncoded( );
57 return res;
58
59 } catch( NoSuchAlgorithmException | InvalidKeySpecException e ) {
60 throw new RuntimeException( e );
61 }
62 }
63 public static byte[] passData(String pass){
64 char[] passChar = pass.toCharArray();
65 byte[] passSalt = pass.getBytes();
66 byte[] hashed = hashedPass(passChar, passSalt, 1000, 64);
67 return hashed;
68 }
69}