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 * 151 * @param keyBytes 152 * plaintext string to hash. 153 * @param salt 154 * salt string including the prefix and optionally garbage at the end. The salt may be null, in which 155 * case a salt is generated for you using {@link ThreadLocalRandom}; for more secure salts consider using 156 * {@link SecureRandom} to generate your own salts. 157 * @return the hash value 158 * @throws IllegalArgumentException 159 * if the salt does not match the allowed pattern 160 * @throws IllegalArgumentException 161 * when a {@link java.security.NoSuchAlgorithmException} is caught. 162 */ 163 public static String apr1Crypt(final String keyBytes, final String salt) { 164 return apr1Crypt(keyBytes.getBytes(StandardCharsets.UTF_8), salt); 165 } 166 167 /** 168 * Generates a libc6 crypt() compatible "$1$" hash value. 169 * <p> 170 * See {@link #md5Crypt(byte[], String)} for details. 171 *</p> 172 * <p> 173 * A salt is generated for you using {@link ThreadLocalRandom}; for more secure salts consider using 174 * {@link SecureRandom} to generate your own salts and calling {@link #md5Crypt(byte[], String)}. 175 * </p> 176 * @param keyBytes 177 * plaintext string to hash. 178 * @return the hash value 179 * @throws IllegalArgumentException 180 * when a {@link java.security.NoSuchAlgorithmException} is caught. 181 * @see #md5Crypt(byte[], String) 182 */ 183 public static String md5Crypt(final byte[] keyBytes) { 184 return md5Crypt(keyBytes, MD5_PREFIX + B64.getRandomSalt(8)); 185 } 186 187 /** 188 * Generates a libc6 crypt() compatible "$1$" hash value. 189 * <p> 190 * See {@link #md5Crypt(byte[], String)} for details. 191 *</p> 192 * <p> 193 * A salt is generated for you using the instance of {@link Random} you supply. 194 * </p> 195 * @param keyBytes 196 * plaintext string to hash. 197 * @param random 198 * the instance of {@link Random} to use for generating the salt. Consider using {@link SecureRandom} 199 * or {@link ThreadLocalRandom}. 200 * @return the hash value 201 * @throws IllegalArgumentException 202 * when a {@link java.security.NoSuchAlgorithmException} is caught. 203 * @see #md5Crypt(byte[], String) 204 * @since 1.12 205 */ 206 public static String md5Crypt(final byte[] keyBytes, final Random random) { 207 return md5Crypt(keyBytes, MD5_PREFIX + B64.getRandomSalt(8, random)); 208 } 209 210 /** 211 * Generates a libc crypt() compatible "$1$" MD5 based hash value. 212 * <p> 213 * See {@link Crypt#crypt(String, String)} for details. We use {@link SecureRandom} for seed generation by 214 * default. 215 * </p> 216 * 217 * @param keyBytes 218 * plaintext string to hash. 219 * @param salt 220 * salt string including the prefix and optionally garbage at the end. The salt may be null, in which 221 * case a salt is generated for you using {@link ThreadLocalRandom}; for more secure salts consider using 222 * {@link SecureRandom} to generate your own salts. 223 * @return the hash value 224 * @throws IllegalArgumentException 225 * if the salt does not match the allowed pattern 226 * @throws IllegalArgumentException 227 * when a {@link java.security.NoSuchAlgorithmException} is caught. 228 */ 229 public static String md5Crypt(final byte[] keyBytes, final String salt) { 230 return md5Crypt(keyBytes, salt, MD5_PREFIX); 231 } 232 233 /** 234 * Generates a libc6 crypt() "$1$" or Apache htpasswd "$apr1$" hash value. 235 * <p> 236 * See {@link Crypt#crypt(String, String)} or {@link #apr1Crypt(String, String)} for details. We use 237 * {@link SecureRandom by default}. 238 * </p> 239 * 240 * @param keyBytes 241 * plaintext string to hash. 242 * @param salt 243 * real salt value without prefix or "rounds=". The salt may be null, in which case a salt 244 * is generated for you using {@link ThreadLocalRandom}; for more secure salts consider 245 * using {@link SecureRandom} to generate your own salts. 246 * @param prefix 247 * salt prefix 248 * @return the hash value 249 * @throws IllegalArgumentException 250 * if the salt does not match the allowed pattern 251 * @throws IllegalArgumentException 252 * when a {@link java.security.NoSuchAlgorithmException} is caught. 253 */ 254 public static String md5Crypt(final byte[] keyBytes, final String salt, final String prefix) { 255 return md5Crypt(keyBytes, salt, prefix, new SecureRandom()); 256 } 257 258 /** 259 * Generates a libc6 crypt() "$1$" or Apache htpasswd "$apr1$" hash value. 260 * <p> 261 * See {@link Crypt#crypt(String, String)} or {@link #apr1Crypt(String, String)} for details. 262 * </p> 263 * 264 * @param keyBytes 265 * plaintext string to hash. 266 * @param salt 267 * real salt value without prefix or "rounds=". The salt may be null, in which case a salt 268 * is generated for you using {@link ThreadLocalRandom}; for more secure salts consider 269 * using {@link SecureRandom} to generate your own salts. 270 * @param prefix 271 * salt prefix 272 * @param random 273 * the instance of {@link Random} to use for generating the salt. Consider using {@link SecureRandom} 274 * or {@link ThreadLocalRandom}. 275 * @return the hash value 276 * @throws IllegalArgumentException 277 * if the salt does not match the allowed pattern 278 * @throws IllegalArgumentException 279 * when a {@link java.security.NoSuchAlgorithmException} is caught. 280 * @since 1.12 281 */ 282 public static String md5Crypt(final byte[] keyBytes, final String salt, final String prefix, final Random random) { 283 final int keyLen = keyBytes.length; 284 285 // Extract the real salt from the given string which can be a complete hash string. 286 String saltString; 287 if (salt == null) { 288 saltString = B64.getRandomSalt(8, random); 289 } else { 290 final Pattern p = Pattern.compile("^" + prefix.replace("$", "\\$") + "([\\.\\/a-zA-Z0-9]{1,8}).*"); 291 final Matcher m = p.matcher(salt); 292 if (!m.find()) { 293 throw new IllegalArgumentException("Invalid salt value: " + salt); 294 } 295 saltString = m.group(1); 296 } 297 final byte[] saltBytes = saltString.getBytes(StandardCharsets.UTF_8); 298 299 final MessageDigest ctx = DigestUtils.getMd5Digest(); 300 301 /* 302 * The password first, since that is what is most unknown 303 */ 304 ctx.update(keyBytes); 305 306 /* 307 * Then our magic string 308 */ 309 ctx.update(prefix.getBytes(StandardCharsets.UTF_8)); 310 311 /* 312 * Then the raw salt 313 */ 314 ctx.update(saltBytes); 315 316 /* 317 * Then just as many characters of the MD5(pw,salt,pw) 318 */ 319 MessageDigest ctx1 = DigestUtils.getMd5Digest(); 320 ctx1.update(keyBytes); 321 ctx1.update(saltBytes); 322 ctx1.update(keyBytes); 323 byte[] finalb = ctx1.digest(); 324 int ii = keyLen; 325 while (ii > 0) { 326 ctx.update(finalb, 0, ii > 16 ? 16 : ii); 327 ii -= 16; 328 } 329 330 /* 331 * Don't leave anything around in vm they could use. 332 */ 333 Arrays.fill(finalb, (byte) 0); 334 335 /* 336 * Then something really weird... 337 */ 338 ii = keyLen; 339 final int j = 0; 340 while (ii > 0) { 341 if ((ii & 1) == 1) { 342 ctx.update(finalb[j]); 343 } else { 344 ctx.update(keyBytes[j]); 345 } 346 ii >>= 1; 347 } 348 349 /* 350 * Now make the output string 351 */ 352 final StringBuilder passwd = new StringBuilder(prefix + saltString + "$"); 353 finalb = ctx.digest(); 354 355 /* 356 * and now, just to make sure things don't run too fast On a 60 Mhz Pentium this takes 34 msec, so you would 357 * need 30 seconds to build a 1000 entry dictionary... 358 */ 359 for (int i = 0; i < ROUNDS; i++) { 360 ctx1 = DigestUtils.getMd5Digest(); 361 if ((i & 1) != 0) { 362 ctx1.update(keyBytes); 363 } else { 364 ctx1.update(finalb, 0, BLOCKSIZE); 365 } 366 367 if (i % 3 != 0) { 368 ctx1.update(saltBytes); 369 } 370 371 if (i % 7 != 0) { 372 ctx1.update(keyBytes); 373 } 374 375 if ((i & 1) != 0) { 376 ctx1.update(finalb, 0, BLOCKSIZE); 377 } else { 378 ctx1.update(keyBytes); 379 } 380 finalb = ctx1.digest(); 381 } 382 383 // The following was nearly identical to the Sha2Crypt code. 384 // Again, the buflen is not really needed. 385 // int buflen = MD5_PREFIX.length() - 1 + salt_string.length() + 1 + BLOCKSIZE + 1; 386 B64.b64from24bit(finalb[0], finalb[6], finalb[12], 4, passwd); 387 B64.b64from24bit(finalb[1], finalb[7], finalb[13], 4, passwd); 388 B64.b64from24bit(finalb[2], finalb[8], finalb[14], 4, passwd); 389 B64.b64from24bit(finalb[3], finalb[9], finalb[15], 4, passwd); 390 B64.b64from24bit(finalb[4], finalb[10], finalb[5], 4, passwd); 391 B64.b64from24bit((byte) 0, (byte) 0, finalb[11], 2, passwd); 392 393 /* 394 * Don't leave anything around in vm they could use. 395 */ 396 // Is there a better way to do this with the JVM? 397 ctx.reset(); 398 ctx1.reset(); 399 Arrays.fill(keyBytes, (byte) 0); 400 Arrays.fill(saltBytes, (byte) 0); 401 Arrays.fill(finalb, (byte) 0); 402 403 return passwd.toString(); 404 } 405}