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.security.MessageDigest;
020import java.security.SecureRandom;
021import java.util.Arrays;
022import java.util.Random;
023import java.util.concurrent.ThreadLocalRandom;
024import java.util.regex.Matcher;
025import java.util.regex.Pattern;
026
027import org.apache.commons.codec.Charsets;
028
029/**
030 * The libc crypt() "$1$" and Apache "$apr1$" MD5-based hash algorithm.
031 * <p>
032 * Based on the public domain ("beer-ware") C implementation from Poul-Henning Kamp which was found at: <a
033 * href="http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libcrypt/crypt-md5.c?rev=1.1;content-type=text%2Fplain">
034 * crypt-md5.c @ freebsd.org</a><br>
035 * <p>
036 * Source:
037 *
038 * <pre>
039 * $FreeBSD: src/lib/libcrypt/crypt-md5.c,v 1.1 1999/01/21 13:50:09 brandon Exp $
040 * </pre>
041 * <p>
042 * Conversion to Kotlin and from there to Java in 2012.
043 * <p>
044 * The C style comments are from the original C code, the ones with "//" from the port.
045 * <p>
046 * This class is immutable and thread-safe.
047 *
048 * @version $Id$
049 * @since 1.7
050 */
051public class Md5Crypt {
052
053    /** The Identifier of the Apache variant. */
054    static final String APR1_PREFIX = "$apr1$";
055
056    /** The number of bytes of the final hash. */
057    private static final int BLOCKSIZE = 16;
058
059    /** The Identifier of this crypt() variant. */
060    static final String MD5_PREFIX = "$1$";
061
062    /** The number of rounds of the big loop. */
063    private static final int ROUNDS = 1000;
064
065    /**
066     * See {@link #apr1Crypt(byte[], String)} for details.
067     * <p>
068     * A salt is generated for you using {@link SecureRandom}; your own {@link Random} in
069     * {@link #apr1Crypt(byte[], Random)}.
070     * </p>
071     *
072     * @param keyBytes plaintext string to hash.
073     * @return the hash value
074     * @throws IllegalArgumentException when a {@link java.security.NoSuchAlgorithmException} is caught. *
075     * @see #apr1Crypt(byte[], String)
076     */
077    public static String apr1Crypt(final byte[] keyBytes) {
078        return apr1Crypt(keyBytes, APR1_PREFIX + B64.getRandomSalt(8));
079    }
080
081    /**
082     * See {@link #apr1Crypt(byte[], String)} for details.
083     * <p>
084     * A salt is generated for you using the user provided {@link Random}.
085     * </p>
086     *
087     * @param keyBytes plaintext string to hash.
088     * @param random an arbitrary {@link Random} for the user's reason.
089     * @param random the instance of {@link Random} to use for generating the salt. Consider using {@link SecureRandom}
090     *            or {@link ThreadLocalRandom}.
091     * @throws IllegalArgumentException when a {@link java.security.NoSuchAlgorithmException} is caught. *
092     * @see #apr1Crypt(byte[], String)
093     */
094    public static String apr1Crypt(final byte[] keyBytes, final Random random) {
095        return apr1Crypt(keyBytes, APR1_PREFIX + B64.getRandomSalt(8, random));
096    }
097
098    /**
099     * See {@link #apr1Crypt(String, String)} for details.
100     * <p>
101     * A salt is generated for you using {@link SecureRandom}
102     * </p>
103     *
104     * @param keyBytes
105     *            plaintext string to hash.
106     * @param salt
107     *            An APR1 salt. The salt may be null, in which case a salt is generated for you using
108     *            {@link ThreadLocalRandom}; for more secure salts consider using {@link SecureRandom} to generate your
109     *            own salts.
110     * @return the hash value
111     * @throws IllegalArgumentException
112     *             if the salt does not match the allowed pattern
113     * @throws IllegalArgumentException
114     *             when a {@link java.security.NoSuchAlgorithmException} is caught.
115     */
116    public static String apr1Crypt(final byte[] keyBytes, String salt) {
117        // to make the md5Crypt regex happy
118        if (salt != null && !salt.startsWith(APR1_PREFIX)) {
119            salt = APR1_PREFIX + salt;
120        }
121        return Md5Crypt.md5Crypt(keyBytes, salt, APR1_PREFIX);
122    }
123
124    /**
125     * See {@link #apr1Crypt(String, String)} for details.
126     * <p>
127     * A salt is generated for you using {@link ThreadLocalRandom}; for more secure salts consider using
128     * {@link SecureRandom} to generate your own salts and calling {@link #apr1Crypt(byte[], String)}.
129     * </p>
130     *
131     * @param keyBytes
132     *            plaintext string to hash.
133     * @return the hash value
134     * @throws IllegalArgumentException
135     *             when a {@link java.security.NoSuchAlgorithmException} is caught.
136     * @see #apr1Crypt(byte[], String)
137     */
138    public static String apr1Crypt(final String keyBytes) {
139        return apr1Crypt(keyBytes.getBytes(Charsets.UTF_8));
140    }
141
142    /**
143     * Generates an Apache htpasswd compatible "$apr1$" MD5 based hash value.
144     * <p>
145     * The algorithm is identical to the crypt(3) "$1$" one but produces different outputs due to the different salt
146     * prefix.
147     *
148     * @param keyBytes
149     *            plaintext string to hash.
150     * @param salt
151     *            salt string including the prefix and optionally garbage at the end. The salt may be null, in which
152     *            case a salt is generated for you using {@link ThreadLocalRandom}; for more secure salts consider using
153     *            {@link SecureRandom} to generate your own salts.
154     * @return the hash value
155     * @throws IllegalArgumentException
156     *             if the salt does not match the allowed pattern
157     * @throws IllegalArgumentException
158     *             when a {@link java.security.NoSuchAlgorithmException} is caught.
159     */
160    public static String apr1Crypt(final String keyBytes, final String salt) {
161        return apr1Crypt(keyBytes.getBytes(Charsets.UTF_8), salt);
162    }
163
164    /**
165     * Generates a libc6 crypt() compatible "$1$" hash value.
166     * <p>
167     * See {@link #md5Crypt(byte[], String)} for details.
168     *</p>
169     * <p>
170     * A salt is generated for you using {@link ThreadLocalRandom}; for more secure salts consider using
171     * {@link SecureRandom} to generate your own salts and calling {@link #md5Crypt(byte[], String)}.
172     * </p>
173     * @param keyBytes
174     *            plaintext string to hash.
175     * @return the hash value
176     * @throws IllegalArgumentException
177     *             when a {@link java.security.NoSuchAlgorithmException} is caught.
178     * @see #md5Crypt(byte[], String)
179     */
180    public static String md5Crypt(final byte[] keyBytes) {
181        return md5Crypt(keyBytes, MD5_PREFIX + B64.getRandomSalt(8));
182    }
183
184    /**
185     * Generates a libc6 crypt() compatible "$1$" hash value.
186     * <p>
187     * See {@link #md5Crypt(byte[], String)} for details.
188     *</p>
189     * <p>
190     * A salt is generated for you using the instance of {@link Random} you supply.
191     * </p>
192     * @param keyBytes
193     *            plaintext string to hash.
194     * @param random
195     *            the instance of {@link Random} to use for generating the salt. Consider using {@link SecureRandom}
196     *            or {@link ThreadLocalRandom}.
197     * @return the hash value
198     * @throws IllegalArgumentException
199     *             when a {@link java.security.NoSuchAlgorithmException} is caught.
200     * @see #md5Crypt(byte[], String)
201     */
202    public static String md5Crypt(final byte[] keyBytes, final Random random) {
203        return md5Crypt(keyBytes, MD5_PREFIX + B64.getRandomSalt(8, random));
204    }
205
206    /**
207     * Generates a libc crypt() compatible "$1$" MD5 based hash value.
208     * <p>
209     * See {@link Crypt#crypt(String, String)} for details. We use {@link SecureRandom} for seed generation by
210     * default.
211     * </p>
212     *
213     * @param keyBytes
214     *            plaintext string to hash.
215     * @param salt
216     *            salt string including the prefix and optionally garbage at the end. The salt may be null, in which
217     *            case a salt is generated for you using {@link ThreadLocalRandom}; for more secure salts consider using
218     *            {@link SecureRandom} to generate your own salts.
219     * @return the hash value
220     * @throws IllegalArgumentException
221     *             if the salt does not match the allowed pattern
222     * @throws IllegalArgumentException
223     *             when a {@link java.security.NoSuchAlgorithmException} is caught.
224     */
225    public static String md5Crypt(final byte[] keyBytes, final String salt) {
226        return md5Crypt(keyBytes, salt, MD5_PREFIX);
227    }
228
229    /**
230     * Generates a libc6 crypt() "$1$" or Apache htpasswd "$apr1$" hash value.
231     * <p>
232     * See {@link Crypt#crypt(String, String)} or {@link #apr1Crypt(String, String)} for details. We use
233     * {@link SecureRandom by default}.
234     * </p>
235     *
236     * @param keyBytes
237     *            plaintext string to hash.
238     * @param salt
239     *            real salt value without prefix or "rounds=". The salt may be null, in which case a salt is generated for
240     *            you using {@link ThreadLocalRandom}; for more secure salts consider using {@link SecureRandom} to
241     *            generate your own salts.
242     * @param prefix
243     *            salt prefix
244     * @return the hash value
245     * @throws IllegalArgumentException
246     *             if the salt does not match the allowed pattern
247     * @throws IllegalArgumentException
248     *             when a {@link java.security.NoSuchAlgorithmException} is caught.
249     */
250    public static String md5Crypt(final byte[] keyBytes, final String salt, final String prefix) {
251        return md5Crypt(keyBytes, salt, prefix, new SecureRandom());
252    }
253
254    /**
255     * Generates a libc6 crypt() "$1$" or Apache htpasswd "$apr1$" hash value.
256     * <p>
257     * See {@link Crypt#crypt(String, String)} or {@link #apr1Crypt(String, String)} for details.
258     * </p>
259     *
260     * @param keyBytes
261     *            plaintext string to hash.
262     * @param salt
263     *            real salt value without prefix or "rounds=". The salt may be null, in which case a salt is generated for
264     *            you using {@link ThreadLocalRandom}; for more secure salts consider using {@link SecureRandom} to
265     *            generate your own salts.
266     * @param prefix
267     *            salt prefix
268     * @param random
269     *            the instance of {@link Random} to use for generating the salt. Consider using {@link SecureRandom}
270     *            or {@link ThreadLocalRandom}.
271     * @return the hash value
272     * @throws IllegalArgumentException
273     *             if the salt does not match the allowed pattern
274     * @throws IllegalArgumentException
275     *             when a {@link java.security.NoSuchAlgorithmException} is caught.
276     */
277    public static String md5Crypt(final byte[] keyBytes, final String salt, final String prefix, final Random random) {
278        final int keyLen = keyBytes.length;
279
280        // Extract the real salt from the given string which can be a complete hash string.
281        String saltString;
282        if (salt == null) {
283            saltString = B64.getRandomSalt(8, random);
284        } else {
285            final Pattern p = Pattern.compile("^" + prefix.replace("$", "\\$") + "([\\.\\/a-zA-Z0-9]{1,8}).*");
286            final Matcher m = p.matcher(salt);
287            if (!m.find()) {
288                throw new IllegalArgumentException("Invalid salt value: " + salt);
289            }
290            saltString = m.group(1);
291        }
292        final byte[] saltBytes = saltString.getBytes(Charsets.UTF_8);
293
294        final MessageDigest ctx = DigestUtils.getMd5Digest();
295
296        /*
297         * The password first, since that is what is most unknown
298         */
299        ctx.update(keyBytes);
300
301        /*
302         * Then our magic string
303         */
304        ctx.update(prefix.getBytes(Charsets.UTF_8));
305
306        /*
307         * Then the raw salt
308         */
309        ctx.update(saltBytes);
310
311        /*
312         * Then just as many characters of the MD5(pw,salt,pw)
313         */
314        MessageDigest ctx1 = DigestUtils.getMd5Digest();
315        ctx1.update(keyBytes);
316        ctx1.update(saltBytes);
317        ctx1.update(keyBytes);
318        byte[] finalb = ctx1.digest();
319        int ii = keyLen;
320        while (ii > 0) {
321            ctx.update(finalb, 0, ii > 16 ? 16 : ii);
322            ii -= 16;
323        }
324
325        /*
326         * Don't leave anything around in vm they could use.
327         */
328        Arrays.fill(finalb, (byte) 0);
329
330        /*
331         * Then something really weird...
332         */
333        ii = keyLen;
334        final int j = 0;
335        while (ii > 0) {
336            if ((ii & 1) == 1) {
337                ctx.update(finalb[j]);
338            } else {
339                ctx.update(keyBytes[j]);
340            }
341            ii >>= 1;
342        }
343
344        /*
345         * Now make the output string
346         */
347        final StringBuilder passwd = new StringBuilder(prefix + saltString + "$");
348        finalb = ctx.digest();
349
350        /*
351         * and now, just to make sure things don't run too fast On a 60 Mhz Pentium this takes 34 msec, so you would
352         * need 30 seconds to build a 1000 entry dictionary...
353         */
354        for (int i = 0; i < ROUNDS; i++) {
355            ctx1 = DigestUtils.getMd5Digest();
356            if ((i & 1) != 0) {
357                ctx1.update(keyBytes);
358            } else {
359                ctx1.update(finalb, 0, BLOCKSIZE);
360            }
361
362            if (i % 3 != 0) {
363                ctx1.update(saltBytes);
364            }
365
366            if (i % 7 != 0) {
367                ctx1.update(keyBytes);
368            }
369
370            if ((i & 1) != 0) {
371                ctx1.update(finalb, 0, BLOCKSIZE);
372            } else {
373                ctx1.update(keyBytes);
374            }
375            finalb = ctx1.digest();
376        }
377
378        // The following was nearly identical to the Sha2Crypt code.
379        // Again, the buflen is not really needed.
380        // int buflen = MD5_PREFIX.length() - 1 + salt_string.length() + 1 + BLOCKSIZE + 1;
381        B64.b64from24bit(finalb[0], finalb[6], finalb[12], 4, passwd);
382        B64.b64from24bit(finalb[1], finalb[7], finalb[13], 4, passwd);
383        B64.b64from24bit(finalb[2], finalb[8], finalb[14], 4, passwd);
384        B64.b64from24bit(finalb[3], finalb[9], finalb[15], 4, passwd);
385        B64.b64from24bit(finalb[4], finalb[10], finalb[5], 4, passwd);
386        B64.b64from24bit((byte) 0, (byte) 0, finalb[11], 2, passwd);
387
388        /*
389         * Don't leave anything around in vm they could use.
390         */
391        // Is there a better way to do this with the JVM?
392        ctx.reset();
393        ctx1.reset();
394        Arrays.fill(keyBytes, (byte) 0);
395        Arrays.fill(saltBytes, (byte) 0);
396        Arrays.fill(finalb, (byte) 0);
397
398        return passwd.toString();
399    }
400}