mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Gaetan Boismal
25.30.2016 6ea56ecde3d05b84f42a7338d7c2c159817d00d0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Portions Copyright 2010-2015 ForgeRock AS.
 * BSD-compatible md5 password crypt
 * Ported to Java from C based on crypt-md5.c by Poul-Henning Kamp,
 * which was distributed with the following notice:
 * ----------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <phk@login.dknet.dk> wrote this file.  As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
 * ----------------------------------------------------------------------------
 */
package org.opends.server.util;
 
import org.forgerock.opendj.ldap.ByteSequence;
import org.forgerock.opendj.ldap.ByteString;
 
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
 
/**
 * BSD MD5 Crypt algorithm, ported from C.
 *
 * @author ludo
 */
public final class BSDMD5Crypt {
 
  private static final String magic = "$1$";
  private static final int saltLength = 8;
  private static final String itoa64 =
          "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
 
  private static String intTo64(int value, int length)
  {
    StringBuilder output = new StringBuilder();
 
    while (--length >= 0)
    {
      output.append(itoa64.charAt(value & 0x3f));
      value >>= 6;
    }
 
    return output.toString();
  }
 
    /**
   * Encode the supplied password in BSD MD5 crypt form, using
   * a random salt.
   *
   * @param password A password to encode.
   *
   * @return An encrypted string.
   *
   * @throws NoSuchAlgorithmException If the MD5 algorithm is not supported.
   *
   */
  public static String crypt(ByteSequence password)
          throws NoSuchAlgorithmException
  {
    SecureRandom randomGenerator = new SecureRandom();
    StringBuilder salt = new StringBuilder();
 
    /* Generate some random salt */
    while (salt.length() < saltLength)
    {
      int index = (int) (randomGenerator.nextFloat() * itoa64.length());
      salt.append(itoa64.charAt(index));
    }
 
    return BSDMD5Crypt.crypt(password, salt.toString());
  }
 
  /**
   * Encode the supplied password in BSD MD5 crypt form, using
   * provided salt.
   *
   * @param password A password to encode.
   *
   * @param salt A salt string of any size, of which only the first
   * 8 bytes will be considered.
   *
   * @return An encrypted string.
   *
   * @throws NoSuchAlgorithmException If the MD5 algorithm is not supported.
   *
   */
  public static String crypt(ByteSequence password, String salt)
          throws NoSuchAlgorithmException
  {
    MessageDigest ctx, ctx1;
    byte digest1[], digest[];
    byte[] plaintextBytes = password.toByteArray();
 
    /* First skip the magic string */
    if (salt.startsWith(magic))
    {
      salt = salt.substring(magic.length());
    }
 
    /* Salt stops at the first $, max saltLength chars */
    int saltEnd = salt.indexOf('$');
    if (saltEnd != -1)
    {
      salt = salt.substring(0, saltEnd);
    }
 
    if (salt.length() > saltLength)
    {
      salt = salt.substring(0, saltLength);
    }
 
    ctx = MessageDigest.getInstance("MD5");
 
    /* The password first, since that is what is most unknown */
    ctx.update(plaintextBytes);
 
    /* Then our magic string */
    ctx.update(magic.getBytes());
 
    /* Then the raw salt */
    ctx.update(salt.getBytes());
 
    /* Then just as many characters of the MD5(password,salt,password) */
    ctx1 = MessageDigest.getInstance("MD5");
    ctx1.update(plaintextBytes);
    ctx1.update(salt.getBytes());
    ctx1.update(plaintextBytes);
    digest1 = ctx1.digest();
 
 
    for (int pl = password.length(); pl > 0; pl -= 16)
    {
      ctx.update(digest1, 0, pl > 16 ? 16 : pl);
    }
 
    /* Don't leave anything around in vm they could use. */
    Arrays.fill(digest1, (byte) 0);
 
    /* Then something really weird... */
    for (int i = password.length(); i != 0; i >>= 1)
    {
      if ((i & 1) != 0)
      {
        ctx.update(digest1[0]);
      } else
      {
        ctx.update(plaintextBytes[0]);
      }
    }
 
    /* Now make the output string */
    StringBuilder output = new StringBuilder();
    output.append(magic);
    output.append(salt);
    output.append("$");
 
    digest = ctx.digest();
 
    /*
     * and now, just to make sure things don't run too fast
     * On a 60 MHz Pentium this takes 34 msec, so you would
     * need 30 seconds to build a 1000 entry dictionary...
     */
    for (int i = 0; i < 1000; i++)
    {
      ctx1 = MessageDigest.getInstance("MD5");
 
      if ((i & 1) != 0)
      {
        ctx1.update(plaintextBytes);
      } else
      {
        ctx1.update(digest);
      }
      if (i % 3 != 0)
      {
        ctx1.update(salt.getBytes());
      }
      if (i % 7 != 0)
      {
        ctx1.update(plaintextBytes);
      }
      if ((i & 1) != 0)
      {
        ctx1.update(digest);
      } else
      {
        ctx1.update(plaintextBytes);
      }
      digest = ctx1.digest();
    }
 
    int l;
 
    l = ((digest[0] & 0xff) << 16) | ((digest[6] & 0xff) << 8)
            | (digest[12] & 0xff);
    output.append(intTo64(l, 4));
    l = ((digest[1] & 0xff) << 16) | ((digest[7] & 0xff) << 8)
            | (digest[13] & 0xff);
    output.append(intTo64(l, 4));
    l = ((digest[2] & 0xff) << 16) | ((digest[8] & 0xff) << 8)
            | (digest[14] & 0xff);
    output.append(intTo64(l, 4));
    l = ((digest[3] & 0xff) << 16) | ((digest[9] & 0xff) << 8)
            | (digest[15] & 0xff);
    output.append(intTo64(l, 4));
    l = ((digest[4] & 0xff) << 16) | ((digest[10] & 0xff) << 8)
            | (digest[5] & 0xff);
    output.append(intTo64(l, 4));
    l = digest[11] & 0xff;
    output.append(intTo64(l, 2));
 
    /* Don't leave anything around in vm they could use. */
    Arrays.fill(digest, (byte) 0);
    Arrays.fill(plaintextBytes, (byte) 0);
    ctx = null;
    ctx1 = null;
 
    return output.toString();
 
  }
 
  /**
   * Getter to the BSD MD5 magic string.
   *
   * @return the magic string for this crypt algorithm
   */
  public static String getMagicString()
  {
    return magic;
  }
 
  /**
   * Main test method.
   *
   * @param argv The array of test arguments
   *
   */
  public static void main(String argv[])
  {
    if (argv.length < 1 || argv.length > 2)
    {
      System.err.println("Usage: BSDMD5Crypt password salt");
      System.exit(1);
    }
    try
    {
      if (argv.length == 2)
      {
        System.out.println(BSDMD5Crypt.crypt(ByteString.valueOfUtf8(argv[0]),
                argv[1]));
      } else
      {
        System.out.println(BSDMD5Crypt.crypt(ByteString.valueOfUtf8(argv[0])));
      }
    } catch (Exception e)
    {
      System.err.println(e.getMessage());
      System.exit(1);
    }
    System.exit(0);
  }
}