Crypt.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      https://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.codec.digest;

  18. import java.nio.charset.StandardCharsets;
  19. import java.security.SecureRandom;

  20. /**
  21.  * GNU libc crypt(3) compatible hash method.
  22.  * <p>
  23.  * See {@link #crypt(String, String)} for further details.
  24.  * </p>
  25.  * <p>
  26.  * This class is immutable and thread-safe.
  27.  * </p>
  28.  *
  29.  * @since 1.7
  30.  */
  31. public class Crypt {

  32.     /**
  33.      * Encrypts a password in a crypt(3) compatible way.
  34.      * <p>
  35.      * A random salt and the default algorithm (currently SHA-512) are used. See {@link #crypt(String, String)} for
  36.      * details.
  37.      * </p>
  38.      * <p>
  39.      * A salt is generated for you using {@link SecureRandom}.
  40.      * </p>
  41.      *
  42.      * @param keyBytes
  43.      *            plaintext password
  44.      * @return hash value
  45.      * @throws IllegalArgumentException
  46.      *             when a {@link java.security.NoSuchAlgorithmException} is caught.
  47.      */
  48.     public static String crypt(final byte[] keyBytes) {
  49.         return crypt(keyBytes, null);
  50.     }

  51.     /**
  52.      * Encrypts a password in a crypt(3) compatible way.
  53.      * <p>
  54.      * If no salt is provided, a random salt and the default algorithm (currently SHA-512) will be used. See
  55.      * {@link #crypt(String, String)} for details.
  56.      * </p>
  57.      *
  58.      * @param keyBytes
  59.      *            plaintext password
  60.      * @param salt
  61.      *            the salt, which is used to select the algorithm, see {@link #crypt(String, String)}
  62.      *            The salt may be null,
  63.      *            in which case the method delegates to {@link Sha2Crypt#sha512Crypt(byte[])}
  64.      *
  65.      * @return hash value
  66.      * @throws IllegalArgumentException
  67.      *             if the salt does not match the allowed pattern
  68.      * @throws IllegalArgumentException
  69.      *             when a {@link java.security.NoSuchAlgorithmException} is caught.
  70.      */
  71.     public static String crypt(final byte[] keyBytes, final String salt) {
  72.         if (salt == null) {
  73.             return Sha2Crypt.sha512Crypt(keyBytes);
  74.         }
  75.         if (salt.startsWith(Sha2Crypt.SHA512_PREFIX)) {
  76.             return Sha2Crypt.sha512Crypt(keyBytes, salt);
  77.         }
  78.         if (salt.startsWith(Sha2Crypt.SHA256_PREFIX)) {
  79.             return Sha2Crypt.sha256Crypt(keyBytes, salt);
  80.         }
  81.         if (salt.startsWith(Md5Crypt.MD5_PREFIX)) {
  82.             return Md5Crypt.md5Crypt(keyBytes, salt);
  83.         }
  84.         return UnixCrypt.crypt(keyBytes, salt);
  85.     }

  86.     /**
  87.      * Calculates the digest using the strongest crypt(3) algorithm.
  88.      * <p>
  89.      * A random salt and the default algorithm (currently SHA-512) are used.
  90.      * </p>
  91.      * <p>
  92.      * A salt is generated for you using {@link SecureRandom}.
  93.      * </p>
  94.      *
  95.      * @see #crypt(String, String)
  96.      * @param key
  97.      *            plaintext password
  98.      * @return hash value
  99.      * @throws IllegalArgumentException
  100.      *             when a {@link java.security.NoSuchAlgorithmException} is caught.
  101.      */
  102.     public static String crypt(final String key) {
  103.         return crypt(key, null);
  104.     }

  105.     /**
  106.      * Encrypts a password in a crypt(3) compatible way.
  107.      * <p>
  108.      * The exact algorithm depends on the format of the salt string:
  109.      * </p>
  110.      * <ul>
  111.      * <li>SHA-512 salts start with {@code $6$} and are up to 16 chars long.
  112.      * <li>SHA-256 salts start with {@code $5$} and are up to 16 chars long
  113.      * <li>MD5 salts start with {@code $1$} and are up to 8 chars long
  114.      * <li>DES, the traditional UnixCrypt algorithm is used with only 2 chars
  115.      * <li>Only the first 8 chars of the passwords are used in the DES algorithm!
  116.      * </ul>
  117.      * <p>
  118.      * The magic strings {@code "$apr1$"} and {@code "$2a$"} are not recognized by this method as its output should be
  119.      * identical with that of the libc implementation.
  120.      * </p>
  121.      * <p>
  122.      * The rest of the salt string is drawn from the set {@code [a-zA-Z0-9./]} and is cut at the maximum length or if a
  123.      * {@code "$"} sign is encountered. It is therefore valid to enter a complete hash value as salt to for example verify a
  124.      * password with:
  125.      * </p>
  126.      * <pre>
  127.      * storedPwd.equals(crypt(enteredPwd, storedPwd))
  128.      * </pre>
  129.      * <p>
  130.      * The resulting string starts with the marker string ({@code $n$}), where n is the same as the input salt.
  131.      * The salt is then appended, followed by a {@code "$"} sign.
  132.      * This is followed by the actual hash value.
  133.      * For DES the string only contains the salt and actual hash.
  134.      * The total length is dependent on the algorithm used:
  135.      * </p>
  136.      * <ul>
  137.      * <li>SHA-512: 106 chars
  138.      * <li>SHA-256: 63 chars
  139.      * <li>MD5: 34 chars
  140.      * <li>DES: 13 chars
  141.      * </ul>
  142.      * <p>
  143.      * Example:
  144.      * </p>
  145.      * <pre>
  146.      *      crypt("secret", "$1$xxxx") =&gt; "$1$xxxx$aMkevjfEIpa35Bh3G4bAc."
  147.      *      crypt("secret", "xx") =&gt; "xxWAum7tHdIUw"
  148.      * </pre>
  149.      * <p>
  150.      * This method comes in a variation that accepts a byte[] array to support input strings that are not encoded in
  151.      * UTF-8 but for example in ISO-8859-1 where equal characters result in different byte values.
  152.      * </p>
  153.      *
  154.      * @see "The man page of the libc crypt (3) function."
  155.      * @param key
  156.      *            plaintext password as entered by the used
  157.      * @param salt
  158.      *            real salt value without prefix or "rounds=". The salt may be null, in which case a
  159.      *            salt is generated for you using {@link SecureRandom}
  160.      * @return hash value, i.e. encrypted password including the salt string
  161.      * @throws IllegalArgumentException
  162.      *             if the salt does not match the allowed pattern
  163.      * @throws IllegalArgumentException
  164.      *             when a {@link java.security.NoSuchAlgorithmException} is caught. *
  165.      */
  166.     public static String crypt(final String key, final String salt) {
  167.         return crypt(key.getBytes(StandardCharsets.UTF_8), salt);
  168.     }

  169.     /**
  170.      * TODO Make private in 2.0.
  171.      *
  172.      * @deprecated TODO Make private in 2.0.
  173.      */
  174.     @Deprecated
  175.     public Crypt() {
  176.         // empty
  177.     }
  178. }