JSP简单密码加密解密 [英] JSP simple password encryption decryption
问题描述
我需要加密密码才能插入到数据库中。当我需要密码时,我需要解密这个值。这样做的简单方法是什么?
i need to encrypt password to insert in a database.Also when i need that password i need to decrypt this value.What is the simple way to do this?
注意:此操作不是很安全。
Note : This operation have not to be very safe.
推荐答案
请不要实施您当前的计划,而应该使用 MessageDigest 完成此操作。对用户的密码应用单向加密散列函数(例如SHA-256,SHA-384和SHA-512 [和其他]中的一个)和一个 SALT ,以防止彩虹表发生攻击。最后,为了密码重设,只需更换当前的密码哈希。
Please don't implement your current plans, instead you should use a MessageDigest to accomplish this. Apply a one way cryptographic hash function to the user's password (e.g. one of SHA-256, SHA-384, and SHA-512 [and there are others]) and a SALT to prevent rainbow table based attacks. Finally, for password resets, just replace the current password hash.
例如,
// We need a bytesToHex method first. So, from -
// http://stackoverflow.com/a/9855338/2970947
final protected static char[] hexArray = "0123456789ABCDEF"
.toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
int v;
for (int j = 0; j < bytes.length; j++) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
// Change this to something else.
private static String SALT = "123456";
// A password hashing method.
public static String hashPassword(String in) {
try {
MessageDigest md = MessageDigest
.getInstance("SHA-256");
md.update(SALT.getBytes()); // <-- Prepend SALT.
md.update(in.getBytes());
// md.update(SALT.getBytes()); // <-- Or, append SALT.
byte[] out = md.digest();
return bytesToHex(out); // <-- Return the Hex Hash.
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args) {
System.out.println(hashPassword("Hello"));
System.out.println(hashPassword("Hello"));
System.out.println(hashPassword("Hello1"));
System.out.println(hashPassword("Hello2"));
}
哪个应该输出
60C1E22D18D022F01EEF0CAF999E52FD44C0C8EFD2161E9F4D24120AB0AFC84D
60C1E22D18D022F01EEF0CAF999E52FD44C0C8EFD2161E9F4D24120AB0AFC84D
CAAC2288692DD57BADFAE0225A42E59E1979E0116D009EEF01912E8C75529515
E0A3963BFAF209A17422918CB1FC950A62858993CA9A7BA6F760B8D4688306FD
演示如何巨大不同的一个角色使得产生的散列。
Demonstrating how tremendously different one character makes the resulting hash.
这篇关于JSP简单密码加密解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!