java method for password encrypt in ssha for LDAP

9.9k views Asked by At

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;
    }
2

There are 2 answers

0
JEY On

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

0
Ron McLeod On

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