View Javadoc

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  
19  import java.security.MessageDigest;
20  import java.util.Arrays;
21  import java.util.regex.Matcher;
22  import java.util.regex.Pattern;
23  
24  import org.apache.commons.codec.Charsets;
25  
26  /**
27   * The libc crypt() "$1$" and Apache "$apr1$" MD5-based hash algorithm.
28   * <p>
29   * Based on the public domain ("beer-ware") C implementation from Poul-Henning Kamp which was found at: <a
30   * href="http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libcrypt/crypt-md5.c?rev=1.1;content-type=text%2Fplain">
31   * crypt-md5.c @ freebsd.org</a><br/>
32   * <p>
33   * Source:
34   *
35   * <pre>
36   * $FreeBSD: src/lib/libcrypt/crypt-md5.c,v 1.1 1999/01/21 13:50:09 brandon Exp $
37   * </pre>
38   * <p>
39   * Conversion to Kotlin and from there to Java in 2012.
40   * <p>
41   * The C style comments are from the original C code, the ones with "//" from the port.
42   * <p>
43   * This class is immutable and thread-safe.
44   *
45   * @version $Id: Md5Crypt.html 891688 2013-12-24 20:49:46Z ggregory $
46   * @since 1.7
47   */
48  public class Md5Crypt {
49  
50      /** The Identifier of the Apache variant. */
51      static final String APR1_PREFIX = "$apr1$";
52  
53      /** The number of bytes of the final hash. */
54      private static final int BLOCKSIZE = 16;
55  
56      /** The Identifier of this crypt() variant. */
57      static final String MD5_PREFIX = "$1$";
58  
59      /** The number of rounds of the big loop. */
60      private static final int ROUNDS = 1000;
61  
62      /**
63       * See {@link #apr1Crypt(String, String)} for details.
64       *
65       * @param keyBytes
66       *            plaintext string to hash.
67       * @return the hash value
68       * @throws RuntimeException
69       *             when a {@link java.security.NoSuchAlgorithmException} is caught. *
70       */
71      public static String apr1Crypt(final byte[] keyBytes) {
72          return apr1Crypt(keyBytes, APR1_PREFIX + B64.getRandomSalt(8));
73      }
74  
75      /**
76       * See {@link #apr1Crypt(String, String)} for details.
77       *
78       * @param keyBytes
79       *            plaintext string to hash.
80       * @param salt An APR1 salt.
81       * @return the hash value
82       * @throws IllegalArgumentException
83       *             if the salt does not match the allowed pattern
84       * @throws RuntimeException
85       *             when a {@link java.security.NoSuchAlgorithmException} is caught.
86       */
87      public static String apr1Crypt(final byte[] keyBytes, String salt) {
88          // to make the md5Crypt regex happy
89          if (salt != null && !salt.startsWith(APR1_PREFIX)) {
90              salt = APR1_PREFIX + salt;
91          }
92          return Md5Crypt.md5Crypt(keyBytes, salt, APR1_PREFIX);
93      }
94  
95      /**
96       * See {@link #apr1Crypt(String, String)} for details.
97       *
98       * @param keyBytes
99       *            plaintext string to hash.
100      * @return the hash value
101      * @throws RuntimeException
102      *             when a {@link java.security.NoSuchAlgorithmException} is caught.
103      */
104     public static String apr1Crypt(final String keyBytes) {
105         return apr1Crypt(keyBytes.getBytes(Charsets.UTF_8));
106     }
107 
108     /**
109      * Generates an Apache htpasswd compatible "$apr1$" MD5 based hash value.
110      * <p>
111      * The algorithm is identical to the crypt(3) "$1$" one but produces different outputs due to the different salt
112      * prefix.
113      *
114      * @param keyBytes
115      *            plaintext string to hash.
116      * @param salt
117      *            salt string including the prefix and optionally garbage at the end. Will be generated randomly if
118      *            null.
119      * @return the hash value
120      * @throws IllegalArgumentException
121      *             if the salt does not match the allowed pattern
122      * @throws RuntimeException
123      *             when a {@link java.security.NoSuchAlgorithmException} is caught.
124      */
125     public static String apr1Crypt(final String keyBytes, final String salt) {
126         return apr1Crypt(keyBytes.getBytes(Charsets.UTF_8), salt);
127     }
128 
129     /**
130      * Generates a libc6 crypt() compatible "$1$" hash value.
131      * <p>
132      * See {@link Crypt#crypt(String, String)} for details.
133      *
134      * @param keyBytes
135      *            plaintext string to hash.
136      * @return the hash value
137      * @throws RuntimeException
138      *             when a {@link java.security.NoSuchAlgorithmException} is caught.
139      */
140     public static String md5Crypt(final byte[] keyBytes) {
141         return md5Crypt(keyBytes, MD5_PREFIX + B64.getRandomSalt(8));
142     }
143 
144     /**
145      * Generates a libc crypt() compatible "$1$" MD5 based hash value.
146      * <p>
147      * See {@link Crypt#crypt(String, String)} for details.
148      *
149      * @param keyBytes
150      *            plaintext string to hash.
151      * @param salt
152      *            salt string including the prefix and optionally garbage at the end. Will be generated randomly if
153      *            null.
154      * @return the hash value
155      * @throws IllegalArgumentException
156      *             if the salt does not match the allowed pattern
157      * @throws RuntimeException
158      *             when a {@link java.security.NoSuchAlgorithmException} is caught.
159      */
160     public static String md5Crypt(final byte[] keyBytes, final String salt) {
161         return md5Crypt(keyBytes, salt, MD5_PREFIX);
162     }
163 
164     /**
165      * Generates a libc6 crypt() "$1$" or Apache htpasswd "$apr1$" hash value.
166      * <p>
167      * See {@link Crypt#crypt(String, String)} or {@link #apr1Crypt(String, String)} for details.
168      * 
169      * @param keyBytes
170      *            plaintext string to hash.
171      * @param salt May be null.
172      * @param prefix salt prefix
173      * @return the hash value
174      * @throws IllegalArgumentException
175      *             if the salt does not match the allowed pattern
176      * @throws RuntimeException
177      *             when a {@link java.security.NoSuchAlgorithmException} is caught.
178      */
179     public static String md5Crypt(final byte[] keyBytes, final String salt, final String prefix) {
180         final int keyLen = keyBytes.length;
181 
182         // Extract the real salt from the given string which can be a complete hash string.
183         String saltString;
184         if (salt == null) {
185             saltString = B64.getRandomSalt(8);
186         } else {
187             final Pattern p = Pattern.compile("^" + prefix.replace("$", "\\$") + "([\\.\\/a-zA-Z0-9]{1,8}).*");
188             final Matcher m = p.matcher(salt);
189             if (m == null || !m.find()) {
190                 throw new IllegalArgumentException("Invalid salt value: " + salt);
191             }
192             saltString = m.group(1);
193         }
194         final byte[] saltBytes = saltString.getBytes(Charsets.UTF_8);
195 
196         final MessageDigest ctx = DigestUtils.getMd5Digest();
197 
198         /*
199          * The password first, since that is what is most unknown
200          */
201         ctx.update(keyBytes);
202 
203         /*
204          * Then our magic string
205          */
206         ctx.update(prefix.getBytes(Charsets.UTF_8));
207 
208         /*
209          * Then the raw salt
210          */
211         ctx.update(saltBytes);
212 
213         /*
214          * Then just as many characters of the MD5(pw,salt,pw)
215          */
216         MessageDigest ctx1 = DigestUtils.getMd5Digest();
217         ctx1.update(keyBytes);
218         ctx1.update(saltBytes);
219         ctx1.update(keyBytes);
220         byte[] finalb = ctx1.digest();
221         int ii = keyLen;
222         while (ii > 0) {
223             ctx.update(finalb, 0, ii > 16 ? 16 : ii);
224             ii -= 16;
225         }
226 
227         /*
228          * Don't leave anything around in vm they could use.
229          */
230         Arrays.fill(finalb, (byte) 0);
231 
232         /*
233          * Then something really weird...
234          */
235         ii = keyLen;
236         final int j = 0;
237         while (ii > 0) {
238             if ((ii & 1) == 1) {
239                 ctx.update(finalb[j]);
240             } else {
241                 ctx.update(keyBytes[j]);
242             }
243             ii >>= 1;
244         }
245 
246         /*
247          * Now make the output string
248          */
249         final StringBuilder passwd = new StringBuilder(prefix + saltString + "$");
250         finalb = ctx.digest();
251 
252         /*
253          * and now, just to make sure things don't run too fast On a 60 Mhz Pentium this takes 34 msec, so you would
254          * need 30 seconds to build a 1000 entry dictionary...
255          */
256         for (int i = 0; i < ROUNDS; i++) {
257             ctx1 = DigestUtils.getMd5Digest();
258             if ((i & 1) != 0) {
259                 ctx1.update(keyBytes);
260             } else {
261                 ctx1.update(finalb, 0, BLOCKSIZE);
262             }
263 
264             if (i % 3 != 0) {
265                 ctx1.update(saltBytes);
266             }
267 
268             if (i % 7 != 0) {
269                 ctx1.update(keyBytes);
270             }
271 
272             if ((i & 1) != 0) {
273                 ctx1.update(finalb, 0, BLOCKSIZE);
274             } else {
275                 ctx1.update(keyBytes);
276             }
277             finalb = ctx1.digest();
278         }
279 
280         // The following was nearly identical to the Sha2Crypt code.
281         // Again, the buflen is not really needed.
282         // int buflen = MD5_PREFIX.length() - 1 + salt_string.length() + 1 + BLOCKSIZE + 1;
283         B64.b64from24bit(finalb[0], finalb[6], finalb[12], 4, passwd);
284         B64.b64from24bit(finalb[1], finalb[7], finalb[13], 4, passwd);
285         B64.b64from24bit(finalb[2], finalb[8], finalb[14], 4, passwd);
286         B64.b64from24bit(finalb[3], finalb[9], finalb[15], 4, passwd);
287         B64.b64from24bit(finalb[4], finalb[10], finalb[5], 4, passwd);
288         B64.b64from24bit((byte) 0, (byte) 0, finalb[11], 2, passwd);
289 
290         /*
291          * Don't leave anything around in vm they could use.
292          */
293         // Is there a better way to do this with the JVM?
294         ctx.reset();
295         ctx1.reset();
296         Arrays.fill(keyBytes, (byte) 0);
297         Arrays.fill(saltBytes, (byte) 0);
298         Arrays.fill(finalb, (byte) 0);
299 
300         return passwd.toString();
301     }
302 }