用于LDAP的ssha中的密码加密的Java方法

Mas*_*ini 2 java encryption ssha

我想在ssha中加密密码。存在一种方法吗?我找到了,但是在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;
    }
Run Code Online (Sandbox Code Playgroud)

Ron*_*eod 7

OpenLDAP具有用于生成SSHA密码的命令行实用程序:

# slappasswd -h {SSHA} -s test123
{SSHA}FOJDrfbduQe6mWrz70NKVr3uEBPoUBf9
Run Code Online (Sandbox Code Playgroud)

此代码将生成盐腌的SHA-1密码,并提供OpenLDAP可以使用的输出:

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();
}
Run Code Online (Sandbox Code Playgroud)