/* * The contents of this file are subject to the terms of the Common Development and * Distribution License (the License). You may not use this file except in compliance with the * License. * * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the * specific language governing permission and limitations under the License. * * When distributing Covered Software, include this CDDL Header Notice in each file and include * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL * Header, with the fields enclosed by brackets [] replaced by your own identifying * information: "Portions Copyright [year] [name of copyright owner]". * * Portions Copyright 2013-2016 ForgeRock AS. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * Portions Copyright 2026 3A Systems, LLC. */ package org.opends.server.extensions; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * SHA2-based Unix crypt implementation. *
* Based on the C implementation released into the Public Domain by Ulrich Drepper <drepper@redhat.com> * http://www.akkadia.org/drepper/SHA-crypt.txt *
* Conversion to Kotlin and from there to Java in 2012 by Christian Hammers <ch@lathspell.de> and likewise put * into the Public Domain. *
* This class is immutable and thread-safe. * *
* Note this class was originally in the
* org.apache.commons.codec.digest package, but was moved into
* org.opends.server.extensions for convenience.
*
* @version $Id$
* @since 1.7
*/
final class Sha2Crypt {
/**
* Base64 like method to convert binary bytes into ASCII chars.
*
*
This class is immutable and thread-safe.
* *
* Note this class was originally in the
* org.apache.commons.codec.digest package, but was moved into an
* inner class here for convenience. It is not compatible with Base64.
*
* @version $Id$
* @since 1.7
*/
private static class B64 {
/**
* Table with characters for Base64 transformation.
*/
static final String B64T =
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
/**
* Base64 like conversion of bytes to ASCII chars.
*
* @param b2
* A byte from the result.
* @param b1
* A byte from the result.
* @param b0
* A byte from the result.
* @param outLen
* The number of expected output chars.
* @param buffer
* Where the output chars is appended to.
*/
static void b64from24bit(byte b2, byte b1, byte b0, int outLen,
StringBuilder buffer) {
// The bit masking is necessary because the JVM byte type is signed!
int w =
((b2 << 16) & 0x00ffffff) | ((b1 << 8) & 0x00ffff) | (b0 & 0xff);
// It's effectively a "for" loop but kept to resemble
// the original C code.
int n = outLen;
while (n-- > 0) {
buffer.append(B64T.charAt(w & 0x3f));
w >>= 6;
}
}
/**
* Generates a string of random chars from the B64T set.
*
* @param num
* Number of chars to generate.
* @return
* a string of random chars from the B64T set
*/
static String getRandomSalt(int num) {
StringBuilder saltString = new StringBuilder();
for (int i = 1; i <= num; i++) {
saltString.append(B64T.charAt(new Random().
nextInt(B64T.length())));
}
return saltString.toString();
}
}
/**
* Default number of rounds if not explicitly specified.
*/
private static final int ROUNDS_DEFAULT = 5000;
/** Maximum number of rounds. */
private static final int ROUNDS_MAX = 999999999;
/** Minimum number of rounds. */
private static final int ROUNDS_MIN = 1000;
/** Prefix for optional rounds specification. */
private static final String ROUNDS_PREFIX = "rounds=";
/** The MessageDigest algorithms. */
private static final String SHA256_ALGORITHM = "SHA-256";
private static final String SHA512_ALGORITHM = "SHA-512";
/** The number of bytes the final hash value will have. */
private static final int SHA256_BLOCKSIZE = 32;
/** The prefixes that can be used to identify this crypt() variant (SHA-256). */
private static final String SHA256_PREFIX = "$5$";
/** The number of bytes the final hash value will have (SHA-512 variant). */
private static final int SHA512_BLOCKSIZE = 64;
/** The prefixes that can be used to identify this crypt() variant (SHA-512). */
private static final String SHA512_PREFIX = "$6$";
/** The pattern to match valid salt values. */
private static final Pattern SALT_PATTERN = Pattern
.compile("^\\$([56])\\$(rounds=(\\d+)\\$)?([\\.\\/a-zA-Z0-9]{1,16}).*");
/**
* Returns the magic string denoting the SHA-256 scheme is being used.
*
* @return the magic string
*/
static String getMagicSHA256Prefix()
{
return SHA256_PREFIX;
}
/**
* Returns the magic string denoting the SHA-512 scheme is being used.
*
* @return the magic string
*/
static String getMagicSHA512Prefix()
{
return SHA512_PREFIX;
}
/**
* Generates a libc crypt() compatible "$5$" hash value with random salt.
*
* See {@link Crypt#crypt(String, String)} for details. * * @param keyBytes * plaintext to hash * @return complete hash value * @throws RuntimeException * when a {@link java.security.NoSuchAlgorithmException} is caught. */ static String sha256Crypt(final byte[] keyBytes) { return sha256Crypt(keyBytes, null); } /** * Generates a libc6 crypt() compatible "$5$" hash value. *
* See {@link Crypt#crypt(String, String)} for details. * * @param keyBytes * plaintext to hash * @param salt * real salt value without prefix or "rounds=" * @return complete hash value including salt * @throws IllegalArgumentException * if the salt does not match the allowed pattern * @throws RuntimeException * when a {@link java.security.NoSuchAlgorithmException} is caught. */ static String sha256Crypt(final byte[] keyBytes, String salt) { if (salt == null) { salt = SHA256_PREFIX + B64.getRandomSalt(8); } return sha2Crypt(keyBytes, salt, SHA256_PREFIX, SHA256_BLOCKSIZE, SHA256_ALGORITHM); } /** * Generates a libc6 crypt() compatible "$5$" or "$6$" SHA2 based hash value. *
* This is a nearly line by line conversion of the original C function. The numbered comments are from the algorithm * description, the short C-style ones from the original C code and the ones with "Remark" from me. *
* See {@link Crypt#crypt(String, String)} for details.
*
* @param keyBytes
* plaintext to hash
* @param salt
* real salt value without prefix or "rounds="
* @param saltPrefix
* either $5$ or $6$
* @param blocksize
* a value that differs between $5$ and $6$
* @param algorithm
* {@link MessageDigest} algorithm identifier string
* @return complete hash value including prefix and salt
* @throws IllegalArgumentException
* if the given salt is
* See {@link Crypt#crypt(String, String)} for details.
*
* @param keyBytes
* plaintext to hash
* @return complete hash value
* @throws RuntimeException
* when a {@link java.security.NoSuchAlgorithmException} is caught.
*/
static String sha512Crypt(final byte[] keyBytes) {
return sha512Crypt(keyBytes, null);
}
/**
* Generates a libc6 crypt() compatible "$6$" hash value.
*
* See {@link Crypt#crypt(String, String)} for details.
*
* @param keyBytes
* plaintext to hash
* @param salt
* real salt value without prefix or "rounds="
* @return complete hash value including salt
* @throws IllegalArgumentException
* if the salt does not match the allowed pattern
* @throws RuntimeException
* when a {@link java.security.NoSuchAlgorithmException} is caught.
*/
static String sha512Crypt(final byte[] keyBytes, String salt) {
if (salt == null) {
salt = SHA512_PREFIX + B64.getRandomSalt(8);
}
return sha2Crypt(keyBytes, salt, SHA512_PREFIX, SHA512_BLOCKSIZE, SHA512_ALGORITHM);
}
private static MessageDigest getDigest(final String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
} catch (final NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
}
}
null or does not match the allowed pattern
* @throws IllegalArgumentException
* when a {@link NoSuchAlgorithmException} is caught
* @see MessageDigestAlgorithms
*/
private static String sha2Crypt(final byte[] keyBytes, final String salt, final String saltPrefix,
final int blocksize, final String algorithm) {
final int keyLen = keyBytes.length;
// Extracts effective salt and the number of rounds from the given salt.
int rounds = ROUNDS_DEFAULT;
boolean roundsCustom = false;
if (salt == null) {
throw new IllegalArgumentException("Salt must not be null");
}
final Matcher m = SALT_PATTERN.matcher(salt);
if (!m.find()) {
throw new IllegalArgumentException("Invalid salt value: " + salt);
}
if (m.group(3) != null) {
rounds = Integer.parseInt(m.group(3));
rounds = Math.max(ROUNDS_MIN, Math.min(ROUNDS_MAX, rounds));
roundsCustom = true;
}
final String saltString = m.group(4);
final byte[] saltBytes = saltString.getBytes(StandardCharsets.UTF_8);
final int saltLen = saltBytes.length;
// 1. start digest A
// Prepare for the real work.
MessageDigest ctx = getDigest(algorithm);
// 2. the password string is added to digest A
/*
* Add the key string.
*/
ctx.update(keyBytes);
// 3. the salt string is added to digest A. This is just the salt string
// itself without the enclosing '$', without the magic salt_prefix $5$ and
// $6$ respectively and without the rounds=