简体   繁体   中英

java method for password encrypt in ssha for LDAP

I want encrypt the password in ssha. Exists a method to do it? I found this but is in sha.

private String encrypt(final String plaintext) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.getMessage());
        }
        try {
            md.update(plaintext.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage());
        }
        byte raw[] = md.digest();
        String hash = (new BASE64Encoder()).encode(raw);
        return hash;
    }

OpenLDAP has a command line utility to generate SSHA passwords:

# slappasswd -h {SSHA} -s test123
{SSHA}FOJDrfbduQe6mWrz70NKVr3uEBPoUBf9

This code will generate salted SHA-1 passwords with an output that OpenLDAP can use:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

private static final int SALT_LENGTH = 4;

public static String generateSSHA(byte[] password)
        throws NoSuchAlgorithmException {
    SecureRandom secureRandom = new SecureRandom();
    byte[] salt = new byte[SALT_LENGTH];
    secureRandom.nextBytes(salt);

    MessageDigest crypt = MessageDigest.getInstance("SHA-1");
    crypt.reset();
    crypt.update(password);
    crypt.update(salt);
    byte[] hash = crypt.digest();

    byte[] hashPlusSalt = new byte[hash.length + salt.length];
    System.arraycopy(hash, 0, hashPlusSalt, 0, hash.length);
    System.arraycopy(salt, 0, hashPlusSalt, hash.length, salt.length);

    return new StringBuilder().append("{SSHA}")
            .append(Base64.getEncoder().encodeToString(hashPlusSalt))
            .toString();
}

SSHA is just SHA with a seed. In the standard java platform there is no possible solution to do so ( https://stackoverflow.com/a/3983415/1976843 ). You need to implement your own or use third party library. I know that in spring security there is LdapPasswordEncoder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM