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?
Asked
Active
Viewed 1.3k times
3 Answers
9
Self-written algorithms are a security risk, and painful to maintain.
MD5 is not secure.
Use the bcrypt algorithm, provided by jBcrypt (open source):
// 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):
<dependency>
<groupId>de.svenkubiak</groupId>
<artifactId>jBCrypt</artifactId>
<version>0.4.1</version>
</dependency>
Nicolas Raoul
- 58,567
- 58
- 222
- 373
-
@VedPrakash: I added a paragraph about getting it from Maven, does that help? – Nicolas Raoul Mar 01 '17 at 03:10
-
@Nicolass Raoul Thank you sir – Onic Team Mar 01 '17 at 06:28
0
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();
}
jmj
- 237,923
- 42
- 401
- 438
user617597
- 788
- 3
- 9
- 21
-
-1 for advising to use fast hash function. See http://security.stackexchange.com/a/242/5501 – Andrei Botalov Jun 28 '12 at 14:39
-1
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.
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();
}
ajm
- 12,863
- 58
- 163
- 234
-
-1 for advising to use fast hash function. See http://security.stackexchange.com/a/242/5501 – Andrei Botalov Jun 28 '12 at 14:38