Md5Crypt.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.  *      http://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.security.MessageDigest;
  19. import java.util.Arrays;
  20. import java.util.regex.Matcher;
  21. import java.util.regex.Pattern;

  22. import org.apache.commons.codec.Charsets;

  23. /**
  24.  * The libc crypt() "$1$" and Apache "$apr1$" MD5-based hash algorithm.
  25.  * <p>
  26.  * Based on the public domain ("beer-ware") C implementation from Poul-Henning Kamp which was found at: <a
  27.  * href="http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libcrypt/crypt-md5.c?rev=1.1;content-type=text%2Fplain">
  28.  * crypt-md5.c @ freebsd.org</a><br>
  29.  * <p>
  30.  * Source:
  31.  *
  32.  * <pre>
  33.  * $FreeBSD: src/lib/libcrypt/crypt-md5.c,v 1.1 1999/01/21 13:50:09 brandon Exp $
  34.  * </pre>
  35.  * <p>
  36.  * Conversion to Kotlin and from there to Java in 2012.
  37.  * <p>
  38.  * The C style comments are from the original C code, the ones with "//" from the port.
  39.  * <p>
  40.  * This class is immutable and thread-safe.
  41.  *
  42.  * @version $Id: Md5Crypt.java 1744746 2016-05-20 14:19:43Z sebb $
  43.  * @since 1.7
  44.  */
  45. public class Md5Crypt {

  46.     /** The Identifier of the Apache variant. */
  47.     static final String APR1_PREFIX = "$apr1$";

  48.     /** The number of bytes of the final hash. */
  49.     private static final int BLOCKSIZE = 16;

  50.     /** The Identifier of this crypt() variant. */
  51.     static final String MD5_PREFIX = "$1$";

  52.     /** The number of rounds of the big loop. */
  53.     private static final int ROUNDS = 1000;

  54.     /**
  55.      * See {@link #apr1Crypt(String, String)} for details.
  56.      *
  57.      * @param keyBytes
  58.      *            plaintext string to hash.
  59.      * @return the hash value
  60.      * @throws RuntimeException
  61.      *             when a {@link java.security.NoSuchAlgorithmException} is caught. *
  62.      */
  63.     public static String apr1Crypt(final byte[] keyBytes) {
  64.         return apr1Crypt(keyBytes, APR1_PREFIX + B64.getRandomSalt(8));
  65.     }

  66.     /**
  67.      * See {@link #apr1Crypt(String, String)} for details.
  68.      *
  69.      * @param keyBytes
  70.      *            plaintext string to hash.
  71.      * @param salt An APR1 salt.
  72.      * @return the hash value
  73.      * @throws IllegalArgumentException
  74.      *             if the salt does not match the allowed pattern
  75.      * @throws RuntimeException
  76.      *             when a {@link java.security.NoSuchAlgorithmException} is caught.
  77.      */
  78.     public static String apr1Crypt(final byte[] keyBytes, String salt) {
  79.         // to make the md5Crypt regex happy
  80.         if (salt != null && !salt.startsWith(APR1_PREFIX)) {
  81.             salt = APR1_PREFIX + salt;
  82.         }
  83.         return Md5Crypt.md5Crypt(keyBytes, salt, APR1_PREFIX);
  84.     }

  85.     /**
  86.      * See {@link #apr1Crypt(String, String)} for details.
  87.      *
  88.      * @param keyBytes
  89.      *            plaintext string to hash.
  90.      * @return the hash value
  91.      * @throws RuntimeException
  92.      *             when a {@link java.security.NoSuchAlgorithmException} is caught.
  93.      */
  94.     public static String apr1Crypt(final String keyBytes) {
  95.         return apr1Crypt(keyBytes.getBytes(Charsets.UTF_8));
  96.     }

  97.     /**
  98.      * Generates an Apache htpasswd compatible "$apr1$" MD5 based hash value.
  99.      * <p>
  100.      * The algorithm is identical to the crypt(3) "$1$" one but produces different outputs due to the different salt
  101.      * prefix.
  102.      *
  103.      * @param keyBytes
  104.      *            plaintext string to hash.
  105.      * @param salt
  106.      *            salt string including the prefix and optionally garbage at the end. Will be generated randomly if
  107.      *            null.
  108.      * @return the hash value
  109.      * @throws IllegalArgumentException
  110.      *             if the salt does not match the allowed pattern
  111.      * @throws RuntimeException
  112.      *             when a {@link java.security.NoSuchAlgorithmException} is caught.
  113.      */
  114.     public static String apr1Crypt(final String keyBytes, final String salt) {
  115.         return apr1Crypt(keyBytes.getBytes(Charsets.UTF_8), salt);
  116.     }

  117.     /**
  118.      * Generates a libc6 crypt() compatible "$1$" hash value.
  119.      * <p>
  120.      * See {@link Crypt#crypt(String, String)} for details.
  121.      *
  122.      * @param keyBytes
  123.      *            plaintext string to hash.
  124.      * @return the hash value
  125.      * @throws RuntimeException
  126.      *             when a {@link java.security.NoSuchAlgorithmException} is caught.
  127.      */
  128.     public static String md5Crypt(final byte[] keyBytes) {
  129.         return md5Crypt(keyBytes, MD5_PREFIX + B64.getRandomSalt(8));
  130.     }

  131.     /**
  132.      * Generates a libc crypt() compatible "$1$" MD5 based hash value.
  133.      * <p>
  134.      * See {@link Crypt#crypt(String, String)} for details.
  135.      *
  136.      * @param keyBytes
  137.      *            plaintext string to hash.
  138.      * @param salt
  139.      *            salt string including the prefix and optionally garbage at the end. Will be generated randomly if
  140.      *            null.
  141.      * @return the hash value
  142.      * @throws IllegalArgumentException
  143.      *             if the salt does not match the allowed pattern
  144.      * @throws RuntimeException
  145.      *             when a {@link java.security.NoSuchAlgorithmException} is caught.
  146.      */
  147.     public static String md5Crypt(final byte[] keyBytes, final String salt) {
  148.         return md5Crypt(keyBytes, salt, MD5_PREFIX);
  149.     }

  150.     /**
  151.      * Generates a libc6 crypt() "$1$" or Apache htpasswd "$apr1$" hash value.
  152.      * <p>
  153.      * See {@link Crypt#crypt(String, String)} or {@link #apr1Crypt(String, String)} for details.
  154.      *
  155.      * @param keyBytes
  156.      *            plaintext string to hash.
  157.      * @param salt May be null.
  158.      * @param prefix salt prefix
  159.      * @return the hash value
  160.      * @throws IllegalArgumentException
  161.      *             if the salt does not match the allowed pattern
  162.      * @throws RuntimeException
  163.      *             when a {@link java.security.NoSuchAlgorithmException} is caught.
  164.      */
  165.     public static String md5Crypt(final byte[] keyBytes, final String salt, final String prefix) {
  166.         final int keyLen = keyBytes.length;

  167.         // Extract the real salt from the given string which can be a complete hash string.
  168.         String saltString;
  169.         if (salt == null) {
  170.             saltString = B64.getRandomSalt(8);
  171.         } else {
  172.             final Pattern p = Pattern.compile("^" + prefix.replace("$", "\\$") + "([\\.\\/a-zA-Z0-9]{1,8}).*");
  173.             final Matcher m = p.matcher(salt);
  174.             if (!m.find()) {
  175.                 throw new IllegalArgumentException("Invalid salt value: " + salt);
  176.             }
  177.             saltString = m.group(1);
  178.         }
  179.         final byte[] saltBytes = saltString.getBytes(Charsets.UTF_8);

  180.         final MessageDigest ctx = DigestUtils.getMd5Digest();

  181.         /*
  182.          * The password first, since that is what is most unknown
  183.          */
  184.         ctx.update(keyBytes);

  185.         /*
  186.          * Then our magic string
  187.          */
  188.         ctx.update(prefix.getBytes(Charsets.UTF_8));

  189.         /*
  190.          * Then the raw salt
  191.          */
  192.         ctx.update(saltBytes);

  193.         /*
  194.          * Then just as many characters of the MD5(pw,salt,pw)
  195.          */
  196.         MessageDigest ctx1 = DigestUtils.getMd5Digest();
  197.         ctx1.update(keyBytes);
  198.         ctx1.update(saltBytes);
  199.         ctx1.update(keyBytes);
  200.         byte[] finalb = ctx1.digest();
  201.         int ii = keyLen;
  202.         while (ii > 0) {
  203.             ctx.update(finalb, 0, ii > 16 ? 16 : ii);
  204.             ii -= 16;
  205.         }

  206.         /*
  207.          * Don't leave anything around in vm they could use.
  208.          */
  209.         Arrays.fill(finalb, (byte) 0);

  210.         /*
  211.          * Then something really weird...
  212.          */
  213.         ii = keyLen;
  214.         final int j = 0;
  215.         while (ii > 0) {
  216.             if ((ii & 1) == 1) {
  217.                 ctx.update(finalb[j]);
  218.             } else {
  219.                 ctx.update(keyBytes[j]);
  220.             }
  221.             ii >>= 1;
  222.         }

  223.         /*
  224.          * Now make the output string
  225.          */
  226.         final StringBuilder passwd = new StringBuilder(prefix + saltString + "$");
  227.         finalb = ctx.digest();

  228.         /*
  229.          * and now, just to make sure things don't run too fast On a 60 Mhz Pentium this takes 34 msec, so you would
  230.          * need 30 seconds to build a 1000 entry dictionary...
  231.          */
  232.         for (int i = 0; i < ROUNDS; i++) {
  233.             ctx1 = DigestUtils.getMd5Digest();
  234.             if ((i & 1) != 0) {
  235.                 ctx1.update(keyBytes);
  236.             } else {
  237.                 ctx1.update(finalb, 0, BLOCKSIZE);
  238.             }

  239.             if (i % 3 != 0) {
  240.                 ctx1.update(saltBytes);
  241.             }

  242.             if (i % 7 != 0) {
  243.                 ctx1.update(keyBytes);
  244.             }

  245.             if ((i & 1) != 0) {
  246.                 ctx1.update(finalb, 0, BLOCKSIZE);
  247.             } else {
  248.                 ctx1.update(keyBytes);
  249.             }
  250.             finalb = ctx1.digest();
  251.         }

  252.         // The following was nearly identical to the Sha2Crypt code.
  253.         // Again, the buflen is not really needed.
  254.         // int buflen = MD5_PREFIX.length() - 1 + salt_string.length() + 1 + BLOCKSIZE + 1;
  255.         B64.b64from24bit(finalb[0], finalb[6], finalb[12], 4, passwd);
  256.         B64.b64from24bit(finalb[1], finalb[7], finalb[13], 4, passwd);
  257.         B64.b64from24bit(finalb[2], finalb[8], finalb[14], 4, passwd);
  258.         B64.b64from24bit(finalb[3], finalb[9], finalb[15], 4, passwd);
  259.         B64.b64from24bit(finalb[4], finalb[10], finalb[5], 4, passwd);
  260.         B64.b64from24bit((byte) 0, (byte) 0, finalb[11], 2, passwd);

  261.         /*
  262.          * Don't leave anything around in vm they could use.
  263.          */
  264.         // Is there a better way to do this with the JVM?
  265.         ctx.reset();
  266.         ctx1.reset();
  267.         Arrays.fill(keyBytes, (byte) 0);
  268.         Arrays.fill(saltBytes, (byte) 0);
  269.         Arrays.fill(finalb, (byte) 0);

  270.         return passwd.toString();
  271.     }
  272. }