Java sha加密算法 生成指定位数随机字符串 Ldap中{SSHA}密码加密方式

徘徊边缘 提交于 2020-02-13 22:41:27
public class test01 {
    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String str= RandomStringUtils.randomAlphanumeric(8);
        System.out.println(str);

        String s = generateSSHAPwd(str);
        System.out.println(s);
    }

    /**
     * Openldap 产生SSHA密码的算法
     * 效果等同于 slappasswd -h {ssha} -s password
     * @param password
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String generateSSHAPwd(String password)
            throws NoSuchAlgorithmException, UnsupportedEncodingException {
        final int SALT_LENGTH = 4;
        SecureRandom secureRandom = new SecureRandom();
        byte[] salt = new byte[SALT_LENGTH];
        secureRandom.nextBytes(salt);

        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(password.getBytes("utf-8"));
        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(new String(Base64.encodeBase64(hashPlusSalt), Charset.forName("utf-8")))
                .toString();
    }

}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!