How to store a password encrypted in a database?

I am trying to save the password in the database in encrypted form using JSP and Servlets. How can i do this?

+3
source share
3 answers

Self-recording algorithms are a security risk and painful to maintain.
MD5 is not protected .

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, let me know):

<dependency>
    <groupId>de.svenkubiak</groupId>
    <artifactId>jBCrypt</artifactId>
    <version>0.4.1</version>
</dependency>
+8
source

- , .

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();
}
0

You can also use something like below. Below is the crypt method, which takes string input and returns and encrypts the string. You can pass the 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();
}
-1
source

Source: https://habr.com/ru/post/1663719/


All Articles