我正在尝试创建一个循环,从数组列表中获取密码,对它们进行哈希处理,然后将经过哈希处理的密码传递回 Person 对象。
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;
}
}
目前我只是让循环打印出纯文本密码,然后结束循环。 任何帮助都会很棒。非常感谢。
最佳答案
您可以使用 SHA1 摘要。请参阅下面从纯字符串创建摘要的示例。
(您需要将明文密码的 byte[]
传递给 SHAsum()
。我假设您熟悉 String.getBytes() 方法)
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) 存储在 Person
类中
关于Java 哈希密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9754120/