java 如何在数据库中存储加密的密码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5310113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store password encrypted in database?
提问by prasanna
I am trying to store the password into the database in the encrypted form with the help of JSP and Servlets. How I can do that?
我试图在 JSP 和 Servlet 的帮助下以加密形式将密码存储到数据库中。我怎么能做到这一点?
回答by Nicolas Raoul
Self-written algorithms are a security risk, and painful to maintain.
MD5 is not secure.
自己编写的算法存在安全风险,维护起来也很痛苦。
MD5不安全。
Use the bcrypt algorithm, provided by jBcrypt(open source):
使用jBcrypt(开源)提供的 bcrypt 算法:
// Hash a password
String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
// Check that an unencrypted password matches or not
if (BCrypt.checkpw(candidate, hashed))
System.out.println("It matches");
else
System.out.println("It does not match");
If you use Maven, you can get the library by inserting the following dependency in your pom.xml (if a newer version is available please let me know):
如果您使用 Maven,则可以通过在 pom.xml 中插入以下依赖项来获取库(如果有更新的版本,请告诉我):
<dependency>
<groupId>de.svenkubiak</groupId>
<artifactId>jBCrypt</artifactId>
<version>0.4.1</version>
</dependency>
回答by user617597
Try something like this to encrypt your data.
尝试这样的事情来加密您的数据。
MessageDigest md = MessageDigest.getInstance("MD5");
......
synchronized (md) {
md.reset();
byte[] hash = md.digest(plainTextPassword.getBytes("CP1252"));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < hash.length; ++i) {
sb.append(Integer.toHexString((hash[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3));
}
String password = sb.toString();
}
回答by ashishjmeshram
You can also use something like below. Below is a crypt method which takes a string input and will return and encrypted string. You can pass password to this method.
您也可以使用如下所示的内容。下面是一个 crypt 方法,它接受一个字符串输入并将返回和加密的字符串。您可以将密码传递给此方法。
public static String crypt(String str) {
if (str == null || str.length() == 0) {
throw new IllegalArgumentException(
"String to encrypt cannot be null or zero length");
}
StringBuffer hexString = new StringBuffer();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte[] hash = md.digest();
for (int i = 0; i < hash.length; i++) {
if ((0xff & hash[i]) < 0x10) {
hexString.append("0"
+ Integer.toHexString((0xFF & hash[i])));
} else {
hexString.append(Integer.toHexString(0xFF & hash[i]));
}
}
} catch (NoSuchAlgorithmException e) {
}
return hexString.toString();
}