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