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.nio.charset.StandardCharsets;
020import java.security.MessageDigest;
021import java.security.SecureRandom;
022import java.util.Arrays;
023import java.util.Random;
024import java.util.concurrent.ThreadLocalRandom;
025import java.util.regex.Matcher;
026import java.util.regex.Pattern;
027
028/**
029 * The libc crypt() "$1$" and Apache "$apr1$" MD5-based hash algorithm.
030 * <p>
031 * Based on the public domain ("beer-ware") C implementation from Poul-Henning Kamp which was found at: <a
032 * href="http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libcrypt/crypt-md5.c?rev=1.1;content-type=text%2Fplain">
033 * crypt-md5.c @ freebsd.org</a>
034 * </p>
035 * <p>
036 * Source:
037 * </p>
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 * <p>
045 * The C style comments are from the original C code, the ones with "//" from the port.
046 * </p>
047 * <p>
048 * This class is immutable and thread-safe.
049 * </p>
050 *
051 * @since 1.7
052 */
053public class Md5Crypt {
054
055    /** The Identifier of the Apache variant. */
056    static final String APR1_PREFIX = "$apr1$";
057
058    /** The number of bytes of the final hash. */
059    private static final int BLOCKSIZE = 16;
060
061    /** The Identifier of this crypt() variant. */
062    static final String MD5_PREFIX = "$1$";
063
064    /** The number of rounds of the big loop. */
065    private static final int ROUNDS = 1000;
066
067    /**
068     * See {@link #apr1Crypt(byte[], String)} for details.
069     * <p>
070     * A salt is generated for you using {@link SecureRandom}; your own {@link Random} in
071     * {@link #apr1Crypt(byte[], Random)}.
072     * </p>
073     *
074     * @param keyBytes plaintext string to hash.
075     * @return the hash value
076     * @throws IllegalArgumentException when a {@link java.security.NoSuchAlgorithmException} is caught. *
077     * @see #apr1Crypt(byte[], String)
078     */
079    public static String apr1Crypt(final byte[] keyBytes) {
080        return apr1Crypt(keyBytes, APR1_PREFIX + B64.getRandomSalt(8));
081    }
082
083    /**
084     * See {@link #apr1Crypt(byte[], String)} for details.
085     * <p>
086     * A salt is generated for you using the user provided {@link Random}.
087     * </p>
088     *
089     * @param keyBytes plaintext string to hash.
090     * @param random the instance of {@link Random} to use for generating the salt. Consider using {@link SecureRandom}
091     *            or {@link ThreadLocalRandom}.
092     * @return the hash value
093     * @throws IllegalArgumentException when a {@link java.security.NoSuchAlgorithmException} is caught. *
094     * @see #apr1Crypt(byte[], String)
095     * @since 1.12
096     */
097    public static String apr1Crypt(final byte[] keyBytes, final Random random) {
098        return apr1Crypt(keyBytes, APR1_PREFIX + B64.getRandomSalt(8, random));
099    }
100
101    /**
102     * See {@link #apr1Crypt(String, String)} for details.
103     * <p>
104     * A salt is generated for you using {@link SecureRandom}
105     * </p>
106     *
107     * @param keyBytes
108     *            plaintext string to hash.
109     * @param salt
110     *            An APR1 salt. The salt may be null, in which case a salt is generated for you using
111     *            {@link ThreadLocalRandom}; for more secure salts consider using {@link SecureRandom} to generate your
112     *            own salts.
113     * @return the hash value
114     * @throws IllegalArgumentException
115     *             if the salt does not match the allowed pattern
116     * @throws IllegalArgumentException
117     *             when a {@link java.security.NoSuchAlgorithmException} is caught.
118     */
119    public static String apr1Crypt(final byte[] keyBytes, String salt) {
120        // to make the md5Crypt regex happy
121        if (salt != null && !salt.startsWith(APR1_PREFIX)) {
122            salt = APR1_PREFIX + salt;
123        }
124        return Md5Crypt.md5Crypt(keyBytes, salt, APR1_PREFIX);
125    }
126
127    /**
128     * See {@link #apr1Crypt(String, String)} for details.
129     * <p>
130     * A salt is generated for you using {@link ThreadLocalRandom}; for more secure salts consider using
131     * {@link SecureRandom} to generate your own salts and calling {@link #apr1Crypt(byte[], String)}.
132     * </p>
133     *
134     * @param keyBytes
135     *            plaintext string to hash.
136     * @return the hash value
137     * @throws IllegalArgumentException
138     *             when a {@link java.security.NoSuchAlgorithmException} is caught.
139     * @see #apr1Crypt(byte[], String)
140     */
141    public static String apr1Crypt(final String keyBytes) {
142        return apr1Crypt(keyBytes.getBytes(StandardCharsets.UTF_8));
143    }
144
145    /**
146     * Generates an Apache htpasswd compatible "$apr1$" MD5 based hash value.
147     * <p>
148     * The algorithm is identical to the crypt(3) "$1$" one but produces different outputs due to the different salt
149     * prefix.
150     * </p>
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(StandardCharsets.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        final 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(StandardCharsets.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(StandardCharsets.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, Math.min(ii, 16));
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 milliseconds, so you
358         * would 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}