3

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;
    }
Massimo Mannini
  • 98
  • 2
  • 12
  • What issue do you have?and what your Q? – Abdelhak Jan 28 '16 at 15:30
  • Aside: don't rethrow as `throw new RuntimeException(e.getMessage());`: you lose the stack trace. Simply use `throw new RuntimeException(e);`. You can also avoid the `UnsupportedEncodingException` by using `StandardCharsets.UTF_8`. – Andy Turner Jan 28 '16 at 15:30
  • I need to convert a string to SSHA to insert it on the LDAP server @Abdelhak – Massimo Mannini Jan 28 '16 at 15:35

2 Answers2

11

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();
}
Ron McLeod
  • 643
  • 7
  • 12
2

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

Community
  • 1
  • 1
JEY
  • 6,973
  • 1
  • 36
  • 51