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.util.Arrays; 021import java.util.regex.Matcher; 022import java.util.regex.Pattern; 023 024import org.apache.commons.codec.Charsets; 025 026/** 027 * The libc crypt() "$1$" and Apache "$apr1$" MD5-based hash algorithm. 028 * <p> 029 * Based on the public domain ("beer-ware") C implementation from Poul-Henning Kamp which was found at: <a 030 * href="http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libcrypt/crypt-md5.c?rev=1.1;content-type=text%2Fplain"> 031 * crypt-md5.c @ freebsd.org</a><br> 032 * <p> 033 * Source: 034 * 035 * <pre> 036 * $FreeBSD: src/lib/libcrypt/crypt-md5.c,v 1.1 1999/01/21 13:50:09 brandon Exp $ 037 * </pre> 038 * <p> 039 * Conversion to Kotlin and from there to Java in 2012. 040 * <p> 041 * The C style comments are from the original C code, the ones with "//" from the port. 042 * <p> 043 * This class is immutable and thread-safe. 044 * 045 * @version $Id: Md5Crypt.java 1744746 2016-05-20 14:19:43Z sebb $ 046 * @since 1.7 047 */ 048public class Md5Crypt { 049 050 /** The Identifier of the Apache variant. */ 051 static final String APR1_PREFIX = "$apr1$"; 052 053 /** The number of bytes of the final hash. */ 054 private static final int BLOCKSIZE = 16; 055 056 /** The Identifier of this crypt() variant. */ 057 static final String MD5_PREFIX = "$1$"; 058 059 /** The number of rounds of the big loop. */ 060 private static final int ROUNDS = 1000; 061 062 /** 063 * See {@link #apr1Crypt(String, String)} for details. 064 * 065 * @param keyBytes 066 * plaintext string to hash. 067 * @return the hash value 068 * @throws RuntimeException 069 * when a {@link java.security.NoSuchAlgorithmException} is caught. * 070 */ 071 public static String apr1Crypt(final byte[] keyBytes) { 072 return apr1Crypt(keyBytes, APR1_PREFIX + B64.getRandomSalt(8)); 073 } 074 075 /** 076 * See {@link #apr1Crypt(String, String)} for details. 077 * 078 * @param keyBytes 079 * plaintext string to hash. 080 * @param salt An APR1 salt. 081 * @return the hash value 082 * @throws IllegalArgumentException 083 * if the salt does not match the allowed pattern 084 * @throws RuntimeException 085 * when a {@link java.security.NoSuchAlgorithmException} is caught. 086 */ 087 public static String apr1Crypt(final byte[] keyBytes, String salt) { 088 // to make the md5Crypt regex happy 089 if (salt != null && !salt.startsWith(APR1_PREFIX)) { 090 salt = APR1_PREFIX + salt; 091 } 092 return Md5Crypt.md5Crypt(keyBytes, salt, APR1_PREFIX); 093 } 094 095 /** 096 * See {@link #apr1Crypt(String, String)} for details. 097 * 098 * @param keyBytes 099 * 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.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}