View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.codec.digest;
18  
19  import java.nio.charset.StandardCharsets;
20  import java.security.MessageDigest;
21  import java.security.NoSuchAlgorithmException;
22  import java.security.SecureRandom;
23  import java.util.Arrays;
24  import java.util.Random;
25  import java.util.regex.Matcher;
26  import java.util.regex.Pattern;
27  
28  /**
29   * SHA2-based Unix crypt implementation.
30   * <p>
31   * Based on the C implementation released into the Public Domain by Ulrich Drepper &lt;drepper@redhat.com&gt;
32   * http://www.akkadia.org/drepper/SHA-crypt.txt
33   * </p>
34   * <p>
35   * Conversion to Kotlin and from there to Java in 2012 by Christian Hammers &lt;ch@lathspell.de&gt; and likewise put
36   * into the Public Domain.
37   * </p>
38   * <p>
39   * This class is immutable and thread-safe.
40   * </p>
41   * <p>
42   * SHA-crypt hashing has a quadratic input-length step. To bound CPU and memory consumption when plaintext is supplied by an
43   * untrusted caller, plaintext is limited to 4096 bytes by default. The limit can be changed with the
44   * {@code org.apache.commons.codec.digest.Sha2Crypt.keyMax} system property; this property is intended for trusted JVM
45   * configuration only.
46   * </p>
47   *
48   * @since 1.7
49   */
50  public class Sha2Crypt {
51  
52      /** Default maximum plaintext (key) length in bytes. */
53      private static final int KEY_MAX_DEFAULT = 4096;
54  
55      /** System property used to override the default maximum plaintext (key) length. */
56      static final String KEY_MAX_PROPERTY = "org.apache.commons.codec.digest.Sha2Crypt.keyMax";
57  
58      /** Default number of rounds if not explicitly specified. */
59      private static final int ROUNDS_DEFAULT = 5000;
60  
61      /** Maximum number of rounds. */
62      private static final int ROUNDS_MAX = 999_999_999;
63  
64      /** Default maximum number of rounds accepted from a caller-supplied salt string. */
65      private static final int ROUNDS_MAX_DEFAULT = 1_000_000;
66  
67      /** Minimum number of rounds. */
68      private static final int ROUNDS_MIN = 1000;
69  
70      /** Prefix for optional rounds specification. */
71      private static final String ROUNDS_PREFIX = "rounds=";
72  
73      /** System property used to override the default maximum number of rounds. */
74      static final String ROUNDS_MAX_PROPERTY = "org.apache.commons.codec.digest.Sha2Crypt.roundsMax";
75  
76      /** The number of bytes the final hash value will have (SHA-256 variant). */
77      private static final int SHA256_BLOCKSIZE = 32;
78  
79      /** The prefixes that can be used to identify this crypt() variant (SHA-256). */
80      static final String SHA256_PREFIX = "$5$";
81  
82      /** The number of bytes the final hash value will have (SHA-512 variant). */
83      private static final int SHA512_BLOCKSIZE = 64;
84  
85      /** The prefixes that can be used to identify this crypt() variant (SHA-512). */
86      static final String SHA512_PREFIX = "$6$";
87  
88      /** The pattern to match valid salt values. */
89      private static final Pattern SALT_PATTERN = Pattern
90              .compile("^\\$([56])\\$(rounds=(\\d+)\\$)?([\\.\\/a-zA-Z0-9]{1,16})[\\.\\/a-zA-Z0-9]*(?:\\$.*)?\\z");
91  
92      /**
93       * Finds the first non-zero digit, retaining one zero for an all-zero value.
94       *
95       * @param value a non-empty decimal string
96       * @return the index of the first significant digit
97       */
98      private static int firstNonZeroIndex(final String value) {
99          int index = 0;
100         while (index < value.length() - 1 && value.charAt(index) == '0') {
101             index++;
102         }
103         return index;
104     }
105 
106     /**
107      * Gets the maximum plaintext (key) length in bytes, as configured by the {@code org.apache.commons.codec.digest.Sha2Crypt.keyMax} system property.
108      *
109      * @return the maximum plaintext (key) length in bytes.
110      */
111     private static int getMaxKeyLen() {
112         return Math.max(0, Integer.getInteger(KEY_MAX_PROPERTY, KEY_MAX_DEFAULT));
113     }
114 
115     /**
116      * Gets the maximum number of rounds accepted from a caller-supplied salt string, as configured by the
117      * {@code org.apache.commons.codec.digest.Sha2Crypt.roundsMax} system property.
118      *
119      * @return the maximum number of rounds accepted from a caller-supplied salt string.
120      */
121     private static int getMaxRounds() {
122         return Math.max(ROUNDS_MIN, Math.min(ROUNDS_MAX, Integer.getInteger(ROUNDS_MAX_PROPERTY, ROUNDS_MAX_DEFAULT)));
123     }
124 
125     /**
126      * Generates a libc crypt() compatible "$5$" hash value with random salt.
127      *
128      * <p>
129      * See {@link Crypt#crypt(String, String)} for details.
130      * </p>
131      * <p>
132      * A salt is generated for you using {@link SecureRandom}.
133      * </p>
134      *
135      * @param keyBytes Plaintext to hash. Each array element is set to {@code 0} before returning.
136      * @return The Complete hash value.
137      * @throws IllegalArgumentException Thrown if {@code keyBytes} exceeds the configured maximum length
138      * @throws IllegalArgumentException Thrown if a {@link NoSuchAlgorithmException} is caught.
139      */
140     public static String sha256Crypt(final byte[] keyBytes) {
141         return sha256Crypt(keyBytes, null);
142     }
143 
144     /**
145      * Generates a libc6 crypt() compatible "$5$" hash value.
146      * <p>
147      * See {@link Crypt#crypt(String, String)} for details.
148      * </p>
149      *
150      * @param keyBytes Plaintext to hash. Each array element is set to {@code 0} before returning.
151      * @param salt     real salt value without prefix or "rounds=". The salt may be null, in which case a salt is generated for you using {@link SecureRandom}.
152      *                 If one does not want to use {@link SecureRandom}, you can pass your own {@link Random} in {@link #sha256Crypt(byte[], String, Random)}.
153      * @return The Complete hash value including salt.
154      * @throws IllegalArgumentException Thrown if {@code keyBytes} exceeds the configured maximum length
155      * @throws IllegalArgumentException Thrown if the salt does not match the allowed pattern.
156      * @throws IllegalArgumentException Thrown if a {@link NoSuchAlgorithmException} is caught.
157      */
158     public static String sha256Crypt(final byte[] keyBytes, String salt) {
159         if (salt == null) {
160             salt = SHA256_PREFIX + B64.getRandomSalt(8);
161         }
162         return sha2Crypt(keyBytes, salt, SHA256_PREFIX, SHA256_BLOCKSIZE, MessageDigestAlgorithms.SHA_256, getMaxKeyLen(), getMaxRounds());
163     }
164 
165     /**
166      * Generates a libc6 crypt() compatible "$5$" hash value.
167      * <p>
168      * See {@link Crypt#crypt(String, String)} for details.
169      * </p>
170      *
171      * @param keyBytes plaintext to hash. Each array element is set to {@code 0} before returning.
172      * @param salt     real salt value without prefix or "rounds=".
173      * @param random   The instance of {@link Random} to use for generating the salt. Consider using {@link SecureRandom} for more secure salts.
174      * @return The Complete hash value including salt.
175      * @throws IllegalArgumentException Thrown if {@code keyBytes} exceeds the configured maximum length
176      * @throws IllegalArgumentException Thrown if the salt does not match the allowed pattern.
177      * @throws IllegalArgumentException Thrown if a {@link NoSuchAlgorithmException} is caught.
178      * @since 1.12
179      */
180     public static String sha256Crypt(final byte[] keyBytes, String salt, final Random random) {
181         if (salt == null) {
182             salt = SHA256_PREFIX + B64.getRandomSalt(8, random);
183         }
184         return sha2Crypt(keyBytes, salt, SHA256_PREFIX, SHA256_BLOCKSIZE, MessageDigestAlgorithms.SHA_256, getMaxKeyLen(), getMaxRounds());
185     }
186 
187     /**
188      * Generates a libc6 crypt() compatible "$5$" or "$6$" SHA2 based hash value.
189      * <p>
190      * This is a nearly line by line conversion of the original C function. The numbered comments are from the algorithm description, the short C-style ones
191      * from the original C code and the ones with "Remark" from me.
192      * </p>
193      * <p>
194      * See {@link Crypt#crypt(String, String)} for details.
195      * </p>
196      *
197      * @param keyBytes   plaintext to hash. Each array element is set to {@code 0} before returning.
198      * @param salt       real salt value without prefix or {@code "rounds="}; may not be null.
199      * @param saltPrefix either {@code $5$} or {@code $6$}.
200      * @param blocksize  A value that differs between {@code $5$}  and {@code $6$}.
201      * @param algorithm  {@link MessageDigest} algorithm identifier string.
202      * @param maxKeyLen The maximum plaintext (key) length in bytes.
203      * @param maxRounds The maximum number of rounds accepted from a caller-supplied salt string.
204      * @return The Complete hash value including prefix and salt.
205      * @throws IllegalArgumentException Thrown if the given salt is {@code null} or does not match the allowed pattern.
206      * @throws IllegalArgumentException Thrown if a {@link NoSuchAlgorithmException} is caught.
207      * @see MessageDigestAlgorithms
208      */
209     private static String sha2Crypt(final byte[] keyBytes, final String salt, final String saltPrefix, final int blocksize, final String algorithm,
210             final int maxKeyLen, final int maxRounds) {
211         final int keyLen = keyBytes.length;
212         if (keyLen > maxKeyLen) {
213             throw new IllegalArgumentException("Key length " + keyLen + " exceeds the maximum of " + maxKeyLen + " bytes; " +
214                     "raise it with the " + KEY_MAX_PROPERTY + " system property if intended");
215         }
216         // Extracts effective salt and the number of rounds from the given salt.
217         int rounds = ROUNDS_DEFAULT;
218         boolean roundsCustom = false;
219         if (salt == null) {
220             throw new IllegalArgumentException("Salt must not be null");
221         }
222         final Matcher m = SALT_PATTERN.matcher(salt);
223         if (!m.find()) {
224             throw new IllegalArgumentException("Invalid salt value: " + salt);
225         }
226         if (m.group(3) != null) {
227             final String roundsString = m.group(3);
228             final int firstNonZero = firstNonZeroIndex(roundsString);
229             final String normalizedRounds = roundsString.substring(firstNonZero);
230             final String roundsMaxString = Integer.toString(maxRounds);
231             if (normalizedRounds.length() > roundsMaxString.length() ||
232                     normalizedRounds.length() == roundsMaxString.length() && normalizedRounds.compareTo(roundsMaxString) > 0) {
233                 throw new IllegalArgumentException("Rounds value in salt exceeds the maximum of " + maxRounds + ": " + salt);
234             }
235             rounds = Math.max(ROUNDS_MIN, Integer.parseInt(normalizedRounds));
236             roundsCustom = true;
237         }
238         final String saltString = m.group(4);
239         final byte[] saltBytes = saltString.getBytes(StandardCharsets.UTF_8);
240         final int saltLen = saltBytes.length;
241 
242         // 1. start digest A
243         // Prepare for the real work.
244         final MessageDigest messageDigest = DigestUtils.getDigest(algorithm);
245 
246         // 2. the password string is added to digest A
247         /*
248          * Add the key string.
249          */
250         messageDigest.update(keyBytes);
251 
252         // 3. the salt string is added to digest A. This is just the salt string
253         // itself without the enclosing '$', without the magic salt_prefix $5$ and
254         // $6$ respectively and without the rounds=<N> specification.
255         //
256         // NB: the MD5 algorithm did add the $1$ salt_prefix. This is not deemed
257         // necessary since it is a constant string and does not add security
258         // and /possibly/ allows a plain text attack. Since the rounds=<N>
259         // specification should never be added this would also create an
260         // inconsistency.
261         /*
262          * The last part is the salt string. This must be at most 16 characters and it ends at the first `$' character
263          * (for compatibility with existing implementations).
264          */
265         messageDigest.update(saltBytes);
266 
267         // 4. start digest B
268         /*
269          * Compute alternate SHA sum with input KEY, SALT, and KEY. The final result will be added to the first
270          * context.
271          */
272         final MessageDigest altDigest = DigestUtils.getDigest(algorithm);
273 
274         // 5. add the password to digest B
275         /*
276          * Add key.
277          */
278         altDigest.update(keyBytes);
279 
280         // 6. add the salt string to digest B
281         /*
282          * Add salt.
283          */
284         altDigest.update(saltBytes);
285 
286         // 7. add the password again to digest B
287         /*
288          * Add key again.
289          */
290         altDigest.update(keyBytes);
291 
292         // 8. finish digest B
293         /*
294          * Now get result of this (32 bytes) and add it to the other context.
295          */
296         byte[] altResult = altDigest.digest();
297 
298         // 9. For each block of 32 or 64 bytes in the password string (excluding
299         // the terminating NUL in the C representation), add digest B to digest A
300         /*
301          * Add for any character in the key one byte of the alternate sum.
302          */
303         /*
304          * (Remark: the C code comment seems wrong for key length > 32!)
305          */
306         int cnt = keyLen;
307         while (cnt > blocksize) {
308             messageDigest.update(altResult, 0, blocksize);
309             cnt -= blocksize;
310         }
311 
312         // 10. For the remaining N bytes of the password string add the first
313         // N bytes of digest B to digest A
314         messageDigest.update(altResult, 0, cnt);
315 
316         // 11. For each bit of the binary representation of the length of the
317         // password string up to and including the highest 1-digit, starting
318         // from to the lowest bit position (numeric value 1):
319         //
320         // a) for a 1-digit add digest B to digest A
321         //
322         // b) for a 0-digit add the password string
323         //
324         // NB: this step differs significantly from the MD5 algorithm. It
325         // adds more randomness.
326         /*
327          * Take the binary representation of the length of the key and for every 1 add the alternate sum, for every 0
328          * the key.
329          */
330         cnt = keyLen;
331         while (cnt > 0) {
332             if ((cnt & 1) != 0) {
333                 messageDigest.update(altResult, 0, blocksize);
334             } else {
335                 messageDigest.update(keyBytes);
336             }
337             cnt >>= 1;
338         }
339 
340         // 12. finish digest A
341         /*
342          * Create intermediate result.
343          */
344         altResult = messageDigest.digest();
345 
346         // 13. start digest DP
347         /*
348          * Start computation of P byte sequence.
349          */
350         altDigest.reset();
351 
352         // 14. for every byte in the password (excluding the terminating NUL byte
353         // in the C representation of the string)
354         //
355         // add the password to digest DP
356         /*
357          * For every character in the password add the entire password.
358          */
359         for (int i = 1; i <= keyLen; i++) {
360             altDigest.update(keyBytes);
361         }
362 
363         // 15. finish digest DP
364         /*
365          * Finish the digest.
366          */
367         byte[] tempResult = altDigest.digest();
368 
369         // 16. produce byte sequence P of the same length as the password where
370         //
371         // a) for each block of 32 or 64 bytes of length of the password string
372         // the entire digest DP is used
373         //
374         // b) for the remaining N (up to 31 or 63) bytes use the first N
375         // bytes of digest DP
376         /*
377          * Create byte sequence P.
378          */
379         final byte[] bytes = new byte[keyLen];
380         int cp = 0;
381         while (cp < keyLen - blocksize) {
382             System.arraycopy(tempResult, 0, bytes, cp, blocksize);
383             cp += blocksize;
384         }
385         System.arraycopy(tempResult, 0, bytes, cp, keyLen - cp);
386 
387         // 17. start digest DS
388         /*
389          * Start computation of S byte sequence.
390          */
391         altDigest.reset();
392 
393         // 18. repeat the following 16+A[0] times, where A[0] represents the first
394         // byte in digest A interpreted as an 8-bit unsigned value
395         //
396         // add the salt to digest DS
397         /*
398          * For every character in the password add the entire password.
399          */
400         for (int i = 1; i <= 16 + (altResult[0] & 0xff); i++) {
401             altDigest.update(saltBytes);
402         }
403 
404         // 19. finish digest DS
405         /*
406          * Finish the digest.
407          */
408         tempResult = altDigest.digest();
409 
410         // 20. produce byte sequence S of the same length as the salt string where
411         //
412         // a) for each block of 32 or 64 bytes of length of the salt string
413         // the entire digest DS is used
414         //
415         // b) for the remaining N (up to 31 or 63) bytes use the first N
416         // bytes of digest DS
417         /*
418          * Create byte sequence S.
419          */
420         // Remark: The salt is limited to 16 chars, how does this make sense?
421         final byte[] sBytes = new byte[saltLen];
422         cp = 0;
423         while (cp < saltLen - blocksize) {
424             System.arraycopy(tempResult, 0, sBytes, cp, blocksize);
425             cp += blocksize;
426         }
427         System.arraycopy(tempResult, 0, sBytes, cp, saltLen - cp);
428 
429         // 21. repeat a loop according to the number specified in the rounds=<N>
430         // specification in the salt (or the default value if none is
431         // present). Each round is numbered, starting with 0 and up to N-1.
432         //
433         // The loop uses a digest as input. In the first round it is the
434         // digest produced in step 12. In the latter steps it is the digest
435         // produced in step 21.h. The following text uses the notation
436         // "digest A/C" to describe this behavior.
437         //
438         // Repeatedly run the collected hash value through SHA to burn CPU cycles.
439         for (int i = 0; i < rounds; i++) {
440             // a) start digest C
441             /*
442              * Reset and reuse the existing digest context.
443              */
444             messageDigest.reset();
445 
446             // b) for odd round numbers add the byte sequence P to digest C
447             // c) for even round numbers add digest A/C
448             /*
449              * Add key or last result.
450              */
451             if ((i & 1) != 0) {
452                 messageDigest.update(bytes, 0, keyLen);
453             } else {
454                 messageDigest.update(altResult, 0, blocksize);
455             }
456 
457             // d) for all round numbers not divisible by 3 add the byte sequence S
458             /*
459              * Add salt for numbers not divisible by 3.
460              */
461             if (i % 3 != 0) {
462                 messageDigest.update(sBytes, 0, saltLen);
463             }
464 
465             // e) for all round numbers not divisible by 7 add the byte sequence P
466             /*
467              * Add key for numbers not divisible by 7.
468              */
469             if (i % 7 != 0) {
470                 messageDigest.update(bytes, 0, keyLen);
471             }
472 
473             // f) for odd round numbers add digest A/C
474             // g) for even round numbers add the byte sequence P
475             /*
476              * Add key or last result.
477              */
478             if ((i & 1) != 0) {
479                 messageDigest.update(altResult, 0, blocksize);
480             } else {
481                 messageDigest.update(bytes, 0, keyLen);
482             }
483 
484             // h) finish digest C.
485             /*
486              * Create intermediate result.
487              */
488             altResult = messageDigest.digest();
489         }
490 
491         // 22. Produce the output string. This is an ASCII string of the maximum
492         // size specified above, consisting of multiple pieces:
493         //
494         // a) the salt salt_prefix, $5$ or $6$ respectively
495         //
496         // b) the rounds=<N> specification, if one was present in the input
497         // salt string. A trailing '$' is added in this case to separate
498         // the rounds specification from the following text.
499         //
500         // c) the salt string truncated to 16 characters
501         //
502         // d) a '$' character
503         /*
504          * Now we can construct the result string. It consists of three parts.
505          */
506         final StringBuilder buffer = new StringBuilder(saltPrefix);
507         if (roundsCustom) {
508             buffer.append(ROUNDS_PREFIX);
509             buffer.append(rounds);
510             buffer.append("$");
511         }
512         buffer.append(saltString);
513         buffer.append("$");
514 
515         // e) the base-64 encoded final C digest. The encoding used is as
516         // follows:
517         // [...]
518         //
519         // Each group of three bytes from the digest produces four
520         // characters as output:
521         //
522         // 1. character: the six low bits of the first byte
523         // 2. character: the two high bits of the first byte and the
524         // four low bytes from the second byte
525         // 3. character: the four high bytes from the second byte and
526         // the two low bits from the third byte
527         // 4. character: the six high bits from the third byte
528         //
529         // The groups of three bytes are as follows (in this sequence).
530         // These are the indices into the byte array containing the
531         // digest, starting with index 0. For the last group there are
532         // not enough bytes left in the digest and the value zero is used
533         // in its place. This group also produces only three or two
534         // characters as output for SHA-512 and SHA-512 respectively.
535 
536         // This was just a safeguard in the C implementation:
537         // int buflen = salt_prefix.length() - 1 + ROUNDS_PREFIX.length() + 9 + 1 + salt_string.length() + 1 + 86 + 1;
538 
539         if (blocksize == 32) {
540             B64.b64from24bit(altResult[0], altResult[10], altResult[20], 4, buffer);
541             B64.b64from24bit(altResult[21], altResult[1], altResult[11], 4, buffer);
542             B64.b64from24bit(altResult[12], altResult[22], altResult[2], 4, buffer);
543             B64.b64from24bit(altResult[3], altResult[13], altResult[23], 4, buffer);
544             B64.b64from24bit(altResult[24], altResult[4], altResult[14], 4, buffer);
545             B64.b64from24bit(altResult[15], altResult[25], altResult[5], 4, buffer);
546             B64.b64from24bit(altResult[6], altResult[16], altResult[26], 4, buffer);
547             B64.b64from24bit(altResult[27], altResult[7], altResult[17], 4, buffer);
548             B64.b64from24bit(altResult[18], altResult[28], altResult[8], 4, buffer);
549             B64.b64from24bit(altResult[9], altResult[19], altResult[29], 4, buffer);
550             B64.b64from24bit((byte) 0, altResult[31], altResult[30], 3, buffer);
551         } else {
552             B64.b64from24bit(altResult[0], altResult[21], altResult[42], 4, buffer);
553             B64.b64from24bit(altResult[22], altResult[43], altResult[1], 4, buffer);
554             B64.b64from24bit(altResult[44], altResult[2], altResult[23], 4, buffer);
555             B64.b64from24bit(altResult[3], altResult[24], altResult[45], 4, buffer);
556             B64.b64from24bit(altResult[25], altResult[46], altResult[4], 4, buffer);
557             B64.b64from24bit(altResult[47], altResult[5], altResult[26], 4, buffer);
558             B64.b64from24bit(altResult[6], altResult[27], altResult[48], 4, buffer);
559             B64.b64from24bit(altResult[28], altResult[49], altResult[7], 4, buffer);
560             B64.b64from24bit(altResult[50], altResult[8], altResult[29], 4, buffer);
561             B64.b64from24bit(altResult[9], altResult[30], altResult[51], 4, buffer);
562             B64.b64from24bit(altResult[31], altResult[52], altResult[10], 4, buffer);
563             B64.b64from24bit(altResult[53], altResult[11], altResult[32], 4, buffer);
564             B64.b64from24bit(altResult[12], altResult[33], altResult[54], 4, buffer);
565             B64.b64from24bit(altResult[34], altResult[55], altResult[13], 4, buffer);
566             B64.b64from24bit(altResult[56], altResult[14], altResult[35], 4, buffer);
567             B64.b64from24bit(altResult[15], altResult[36], altResult[57], 4, buffer);
568             B64.b64from24bit(altResult[37], altResult[58], altResult[16], 4, buffer);
569             B64.b64from24bit(altResult[59], altResult[17], altResult[38], 4, buffer);
570             B64.b64from24bit(altResult[18], altResult[39], altResult[60], 4, buffer);
571             B64.b64from24bit(altResult[40], altResult[61], altResult[19], 4, buffer);
572             B64.b64from24bit(altResult[62], altResult[20], altResult[41], 4, buffer);
573             B64.b64from24bit((byte) 0, (byte) 0, altResult[63], 2, buffer);
574         }
575 
576         /*
577          * Clear the buffer for the intermediate result so that people attaching to processes or reading core dumps
578          * cannot get any information.
579          */
580         // Is there a better way to do this with the JVM?
581         Arrays.fill(altResult, (byte) 0);
582         Arrays.fill(tempResult, (byte) 0);
583         Arrays.fill(bytes, (byte) 0);
584         Arrays.fill(sBytes, (byte) 0);
585         messageDigest.reset();
586         altDigest.reset();
587         Arrays.fill(keyBytes, (byte) 0);
588         Arrays.fill(saltBytes, (byte) 0);
589 
590         return buffer.toString();
591     }
592 
593     /**
594      * Generates a libc crypt() compatible "$6$" hash value with random salt.
595      *
596      * <p>
597      * See {@link Crypt#crypt(String, String)} for details.
598      * </p>
599      * <p>
600      * A salt is generated for you using {@link SecureRandom}.
601      * </p>
602      *
603      * @param keyBytes Plaintext to hash. Each array element is set to {@code 0} before returning.
604      * @return Complete hash value.
605      * @throws IllegalArgumentException Thrown if {@code keyBytes} exceeds the configured maximum length
606      * @throws IllegalArgumentException Thrown if a {@link NoSuchAlgorithmException} is caught.
607      */
608     public static String sha512Crypt(final byte[] keyBytes) {
609         return sha512Crypt(keyBytes, null);
610     }
611 
612     /**
613      * Generates a libc6 crypt() compatible "$6$" hash value.
614      *
615      * <p>
616      * See {@link Crypt#crypt(String, String)} for details.
617      * </p>
618      *
619      * @param keyBytes Plaintext to hash. Each array element is set to {@code 0} before returning.
620      * @param salt     Real salt value without prefix or "rounds=". The salt may be null, in which case a salt is generated for you using {@link SecureRandom};
621      *                 if you want to use a {@link Random} object other than {@link SecureRandom} then we suggest you provide it using
622      *                 {@link #sha512Crypt(byte[], String, Random)}.
623      * @return Complete hash value including salt.
624      * @throws IllegalArgumentException Thrown if {@code keyBytes} exceeds the configured maximum length
625      * @throws IllegalArgumentException Thrown if the salt does not match the allowed pattern.
626      * @throws IllegalArgumentException Thrown if a {@link NoSuchAlgorithmException} is caught.
627      */
628     public static String sha512Crypt(final byte[] keyBytes, String salt) {
629         if (salt == null) {
630             salt = SHA512_PREFIX + B64.getRandomSalt(8);
631         }
632         return sha2Crypt(keyBytes, salt, SHA512_PREFIX, SHA512_BLOCKSIZE, MessageDigestAlgorithms.SHA_512, getMaxKeyLen(), getMaxRounds());
633     }
634 
635     /**
636      * Generates a libc6 crypt() compatible "$6$" hash value.
637      *
638      * <p>
639      * See {@link Crypt#crypt(String, String)} for details.
640      * </p>
641      *
642      * @param keyBytes Plaintext to hash. Each array element is set to {@code 0} before returning.
643      * @param salt     Real salt value without prefix or "rounds=". The salt may be null, in which case a salt is generated for you using {@link SecureRandom}.
644      * @param random   The instance of {@link Random} to use for generating the salt. Consider using {@link SecureRandom} for more secure salts.
645      * @return Complete hash value including salt.
646      * @throws IllegalArgumentException Thrown if the salt does not match the allowed pattern.
647      * @throws IllegalArgumentException Thrown if a {@link NoSuchAlgorithmException} is caught.
648      * @since 1.12
649      */
650     public static String sha512Crypt(final byte[] keyBytes, String salt, final Random random) {
651         if (salt == null) {
652             salt = SHA512_PREFIX + B64.getRandomSalt(8, random);
653         }
654         return sha2Crypt(keyBytes, salt, SHA512_PREFIX, SHA512_BLOCKSIZE, MessageDigestAlgorithms.SHA_512, getMaxKeyLen(), getMaxRounds());
655     }
656 
657     /**
658      * Consider private.
659      *
660      * @deprecated Will be private in the next major version.
661      */
662     @Deprecated
663     public Sha2Crypt() {
664         // empty
665     }
666 }