Java的散列密码 [英] Java hashing passwords
问题描述
我试图做一个循环,它从一个数组列表获取密码,散列它们,然后通过散列密码回Person对象。
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.
推荐答案
您可以使用SHA1 diggest。请参阅创建从下面普通字符串diggest的例子。
(您威尔需要通过字节[]
您的普通密码的 SHAsum()
。我假设你熟悉 String.getBytes( )法)
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();
}
使用上述方法计算散列密码,并在人
类存储散列值(SHA1)
Use the methods above to hash the passwords and store in the Person
class the hashed value (SHA1)
这篇关于Java的散列密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!