[英]How to store password encrypted in database?
I am trying to store the password into the database in the encrypted form with the help of JSP and Servlets. 我试图在JSP和Servlets的帮助下以加密的形式将密码存储到数据库中。 How I can do that?
我怎么能这样做?
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>
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();
}
You can also use something like below. 你也可以使用下面的东西。 Below is a crypt method which takes a string input and will return and encrypted string.
下面是一个crypt方法,它接受一个字符串输入并返回并加密字符串。 You can pass password to this method.
您可以将密码传递给此方法。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.