我创建了一个实用程序类,用于哈希和salting密码。然后,我将用户的密码存储在用户表的SQL数据库中。我想使用EL从数据库中提取密码,解密并在JSP中显示它。如何解密从数据库中检索的密码?这是实用程序类:
public class PasswordUtil {
/* This code uses SHA-256. If this algorithm isn't available to you,
you can try a weaker level of encryption such as SHA-128.
*/
public static String hashPassword(String password)
throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.reset();
md.update(password.getBytes());
byte[] mdArray = md.digest();
StringBuilder sb = new StringBuilder(mdArray.length * 2);
for (byte b : mdArray) {
int v = b & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString();
}
public static String getSalt() {
Random r = new SecureRandom();
byte[] saltBytes = new byte[32];
r.nextBytes(saltBytes);
return Base64.getEncoder().encodeToString(saltBytes);
}
public static String hashAndSaltPassword(String password)
throws NoSuchAlgorithmException {
String salt = getSalt();
return hashPassword(password + salt);
}
public static void checkPasswordStrength(String password) throws Exception {
if (password == null || password.trim().isEmpty()) {
throw new Exception("Password cannot be empty.");
} else if (password.length() < 8) {
throw new Exception("Password is to short. " +
"Must be at least 8 characters long.");
}
}
public static boolean validatePassword(String password) {
try {
checkPasswordStrength(password);
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
return true;
}
}
这是JSP(为了简洁,只是JSP中的表)我想在以下位置显示解密密码:
<table>
<tr>
<td class="alignRight">First Name:</td>
<td>${user.firstName}</td>
</tr>
<tr>
<td class="alignRight">Last Name:</td>
<td>${user.lastName}</td>
</tr>
<tr>
<td class="alignRight">Phone Number:</td>
<td>${user.phone}</td>
</tr>
<tr>
<td class="alignRight">Address:</td>
<td>${user.address}</td>
</tr>
<tr>
<td class="alignRight">City:</td>
<td>${user.city}</td>
</tr>
<tr>
<td class="alignRight">State:</td>
<td>${user.state}</td>
</tr>
<tr>
<td class="alignRight">Zipcode:</td>
<td>${user.zip}</td>
</tr>
<tr>
<td class="alignRight">Email:</td>
<td>${user.email}</td>
</tr>
<tr>
<td class="alignRight">Your user name is:</td>
<td>${user.userName}</td>
</tr>
<tr>
<td class="alignRight">Temporary password:</td>
<td>${user.password}</td>
</tr>
</table>
答案 0 :(得分:1)
你不能。
在我看来,你正在使用单向散列函数SHA-256。单向散列函数的想法是它只有一种方式;你无法撤消哈希。
如果您希望能够还原存储在数据库中的“消化”密码,则必须查看“双向哈希函数”(加密/解密)。正如Elliott Frisch所说,但对我来说这听起来真是个坏主意。
答案 1 :(得分:0)
无法执行此操作是哈希密码的整个点。 (请注意,您不存储用户的密码;您正在存储哈希值。)
但是如果你已经死了,你可以尝试使用你的盐创建自己的彩虹表。