001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.codec.digest;
018
019import java.nio.charset.StandardCharsets;
020import java.security.SecureRandom;
021import java.util.concurrent.ThreadLocalRandom;
022
023/**
024 * GNU libc crypt(3) compatible hash method.
025 * <p>
026 * See {@link #crypt(String, String)} for further details.
027 * </p>
028 * <p>
029 * This class is immutable and thread-safe.
030 * </p>
031 *
032 * @since 1.7
033 */
034public class Crypt {
035
036    /**
037     * Encrypts a password in a crypt(3) compatible way.
038     * <p>
039     * A random salt and the default algorithm (currently SHA-512) are used. See {@link #crypt(String, String)} for
040     * details.
041     * </p>
042     * <p>
043     * A salt is generated for you using {@link ThreadLocalRandom}; for more secure salts consider using
044     * {@link SecureRandom} to generate your own salts and calling {@link #crypt(byte[], String)}.
045     * </p>
046     *
047     * @param keyBytes
048     *            plaintext password
049     * @return hash value
050     * @throws IllegalArgumentException
051     *             when a {@link java.security.NoSuchAlgorithmException} is caught.
052     */
053    public static String crypt(final byte[] keyBytes) {
054        return crypt(keyBytes, null);
055    }
056
057    /**
058     * Encrypts a password in a crypt(3) compatible way.
059     * <p>
060     * If no salt is provided, a random salt and the default algorithm (currently SHA-512) will be used. See
061     * {@link #crypt(String, String)} for details.
062     * </p>
063     *
064     * @param keyBytes
065     *            plaintext password
066     * @param salt
067     *            real salt value without prefix or "rounds=". The salt may be null,
068     *            in which case a salt is generated for you using {@link ThreadLocalRandom};
069     *            for more secure salts consider using {@link SecureRandom} to
070     *            generate your own salts.
071     * @return hash value
072     * @throws IllegalArgumentException
073     *             if the salt does not match the allowed pattern
074     * @throws IllegalArgumentException
075     *             when a {@link java.security.NoSuchAlgorithmException} is caught.
076     */
077    public static String crypt(final byte[] keyBytes, final String salt) {
078        if (salt == null) {
079            return Sha2Crypt.sha512Crypt(keyBytes);
080        }
081        if (salt.startsWith(Sha2Crypt.SHA512_PREFIX)) {
082            return Sha2Crypt.sha512Crypt(keyBytes, salt);
083        }
084        if (salt.startsWith(Sha2Crypt.SHA256_PREFIX)) {
085            return Sha2Crypt.sha256Crypt(keyBytes, salt);
086        }
087        if (salt.startsWith(Md5Crypt.MD5_PREFIX)) {
088            return Md5Crypt.md5Crypt(keyBytes, salt);
089        }
090        return UnixCrypt.crypt(keyBytes, salt);
091    }
092
093    /**
094     * Calculates the digest using the strongest crypt(3) algorithm.
095     * <p>
096     * A random salt and the default algorithm (currently SHA-512) are used.
097     * </p>
098     * <p>
099     * A salt is generated for you using {@link ThreadLocalRandom}; for more secure salts consider using
100     * {@link SecureRandom} to generate your own salts and calling {@link #crypt(String, String)}.
101     * </p>
102     *
103     * @see #crypt(String, String)
104     * @param key
105     *            plaintext password
106     * @return hash value
107     * @throws IllegalArgumentException
108     *             when a {@link java.security.NoSuchAlgorithmException} is caught.
109     */
110    public static String crypt(final String key) {
111        return crypt(key, null);
112    }
113
114    /**
115     * Encrypts a password in a crypt(3) compatible way.
116     * <p>
117     * The exact algorithm depends on the format of the salt string:
118     * </p>
119     * <ul>
120     * <li>SHA-512 salts start with {@code $6$} and are up to 16 chars long.
121     * <li>SHA-256 salts start with {@code $5$} and are up to 16 chars long
122     * <li>MD5 salts start with {@code $1$} and are up to 8 chars long
123     * <li>DES, the traditional UnixCrypt algorithm is used with only 2 chars
124     * <li>Only the first 8 chars of the passwords are used in the DES algorithm!
125     * </ul>
126     * <p>
127     * The magic strings {@code "$apr1$"} and {@code "$2a$"} are not recognized by this method as its output should be
128     * identical with that of the libc implementation.
129     * </p>
130     * <p>
131     * The rest of the salt string is drawn from the set {@code [a-zA-Z0-9./]} and is cut at the maximum length of if a
132     * {@code "$"} sign is encountered. It is therefore valid to enter a complete hash value as salt to e.g. verify a
133     * password with:
134     * </p>
135     * <pre>
136     * storedPwd.equals(crypt(enteredPwd, storedPwd))
137     * </pre>
138     * <p>
139     * The resulting string starts with the marker string ({@code $n$}), where n is the same as the input salt.
140     * The salt is then appended, followed by a {@code "$"} sign.
141     * This is followed by the actual hash value.
142     * For DES the string only contains the salt and actual hash.
143     * The total length is dependent on the algorithm used:
144     * </p>
145     * <ul>
146     * <li>SHA-512: 106 chars
147     * <li>SHA-256: 63 chars
148     * <li>MD5: 34 chars
149     * <li>DES: 13 chars
150     * </ul>
151     * <p>
152     * Example:
153     * </p>
154     * <pre>
155     *      crypt("secret", "$1$xxxx") =&gt; "$1$xxxx$aMkevjfEIpa35Bh3G4bAc."
156     *      crypt("secret", "xx") =&gt; "xxWAum7tHdIUw"
157     * </pre>
158     * <p>
159     * This method comes in a variation that accepts a byte[] array to support input strings that are not encoded in
160     * UTF-8 but e.g. in ISO-8859-1 where equal characters result in different byte values.
161     * </p>
162     *
163     * @see "The man page of the libc crypt (3) function."
164     * @param key
165     *            plaintext password as entered by the used
166     * @param salt
167     *            real salt value without prefix or "rounds=". The salt may be null, in which case a
168     *            salt is generated for you using {@link ThreadLocalRandom}; for more secure salts
169     *            consider using {@link SecureRandom} to generate your own salts.
170     * @return hash value, i.e. encrypted password including the salt string
171     * @throws IllegalArgumentException
172     *             if the salt does not match the allowed pattern
173     * @throws IllegalArgumentException
174     *             when a {@link java.security.NoSuchAlgorithmException} is caught. *
175     */
176    public static String crypt(final String key, final String salt) {
177        return crypt(key.getBytes(StandardCharsets.UTF_8), salt);
178    }
179}