Java hashing passwords

2019-04-16 21:21发布

I am trying to make a loop that gets passwords from an array list, hashes them, and then passes the hashed passwords back into a Person object.

import java.util.ArrayList;

public class CompanyDatabase    {

public ArrayList<Person> getPeople() {
    ArrayList<Person> people = new ArrayList<Person>();
    String[] u = {"Joe","Stan","Leo","John","Sara","Lauren"};
    String[] p = {"pass4321", "asdfjkl", "genericpw", "13579", "helloworld", "companypass"};
    for(int j = 0; j < u.length; j++){
        Person temp = new Person(u[j],p[j]);
        people.add(temp);
    }
    return people;
}
}

import java.util.ArrayList;  
import java.util.Scanner;  
public class CompanyDatabaseDriver {  
    private static Scanner scan = new Scanner( System.in ) );  
    public static void main(String args[]) {  

            CompanyDatabase bcData = new CompanyDatabase();  
            ArrayList<Person> people = bcData.getPeople();    

            Hash_SHA hasher = new Hash_SHA(); 



            for(int i=0;i<people.size();i++){

                 System.out.println(people.get(i).getPassword());   
            }
             // i know i have to use a variation of 
             // String hashString = hasher.getHash(passString); 
             // but do not really know what to do with it



   }  

}

public class Person {

private String username;
private String password;

public Person(String un, String pw){
    username = un;
    password = pw;
}

public void setUsername(String un){
    username = un;
}

public void setPassword(String pw){
    password = pw;
}

public String getUsername(){
    return username;
}

public String getPassword(){
    return password;
}

}

Currently I just have the loop printing out the plain text passwords and then ending the loop. Any help would be amazing. Thank you very much.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-16 21:38

You can use SHA1 diggest. See the example of creating a diggest from plain string below. (You weill need to pass the byte[] of your plain password to the SHAsum(). I assume that you are familiar with String.getBytes() method)

import java.security.MessageDigest;

public static String SHAsum(byte[] convertme) throws NoSuchAlgorithmException{
    MessageDigest md = MessageDigest.getInstance("SHA-1"); 
    return byteArray2Hex(md.digest(convertme));
}

private static String byteArray2Hex(final byte[] hash) {
    Formatter formatter = new Formatter();
    for (byte b : hash) {
        formatter.format("%02x", b);
    }
    return formatter.toString();
}

Use the methods above to hash the passwords and store in the Person class the hashed value (SHA1)

查看更多
乱世女痞
3楼-- · 2019-04-16 21:52

I would suggest to have a look at MessageDigest. Get the instance you want, transform the password into bytes[] (using getBytes("UTF-8");) and retrieve the digested bytes. You can then turn your bytes into a string by converting them to hex values.

查看更多
登录 后发表回答