【发布时间】:2015-01-06 10:25:47
【问题描述】:
我知道有很多关于散列和加密算法的文章。
我已经从他们那里弄清楚了使用散列函数而不是加密将密码存储在数据库中。
所以我决定使用 SHA-256 算法生成哈希密钥,并将该哈希密钥存储到我的服务器数据库中,而不是普通密码。
现在我真的无法理解我应该如何使用它,因为每次我传递相同的密码来生成 SHA 密钥时,它给我的结果都与之前的不同,而不是我如何将它与我存储的哈希密钥进行比较数据库?
我正在使用 java,所以我的 java 代码是
public class Test {
public static void main(String...arg) throws IOException{
System.out.println("First time");
String string64 = getEncryptedPassword("FenilShah");
System.out.println(string64);
System.out.println(StringUtils.newStringUtf8(Base64.decodeBase64(string64)));
System.out.println("\nSecond time");
string64 = getEncryptedPassword("FenilShah");
System.out.println(string64);
System.out.println(StringUtils.newStringUtf8(Base64.decodeBase64(string64)));
System.out.println("\nThird time");
string64 = getEncryptedPassword("FenilShah");
System.out.println(string64);
System.out.println(StringUtils.newStringUtf8(Base64.decodeBase64(string64)));
}
public static String getEncryptedPassword(String clearTextPassword) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(clearTextPassword.getBytes());
byte pass[] = md.digest();
System.out.println(pass.toString());
return Base64.encodeBase64String(StringUtils.getBytesUtf8(pass.toString()));
} catch (NoSuchAlgorithmException e) {
//_log.error("Failed to encrypt password.", e);
}
return "";
}
}
所以输出是这样的
First time
[B@5bf825cc
W0JANWJmODI1Y2M=
[B@5bf825cc
Second time
[B@1abfb235
W0JAMWFiZmIyMzU=
[B@1abfb235
Third time
[B@1f4cc34b
W0JAMWY0Y2MzNGI=
[B@1f4cc34b
【问题讨论】:
标签: java algorithm encryption hash sha