Path: blob/master/src/java.base/share/classes/sun/security/provider/HashDrbg.java
41159 views
/*1* Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.provider;2627import java.math.BigInteger;28import java.security.DigestException;29import java.security.MessageDigest;30import java.security.NoSuchAlgorithmException;31import java.security.NoSuchProviderException;32import java.security.SecureRandomParameters;33import java.util.ArrayList;34import java.util.Arrays;35import java.util.HexFormat;36import java.util.List;3738public class HashDrbg extends AbstractHashDrbg {3940private static final byte[] ZERO = new byte[1];41private static final byte[] ONE = new byte[]{1};4243private MessageDigest digest;4445private byte[] v;46private byte[] c;4748public HashDrbg(SecureRandomParameters params) {49mechName = "Hash_DRBG";50configure(params);51}5253/**54* This call, used by the constructors, instantiates the digest.55*/56@Override57protected void initEngine() {58try {59/*60* Use the local SUN implementation to avoid native61* performance overhead.62*/63digest = MessageDigest.getInstance(algorithm, "SUN");64} catch (NoSuchProviderException | NoSuchAlgorithmException e) {65// Fallback to any available.66try {67digest = MessageDigest.getInstance(algorithm);68} catch (NoSuchAlgorithmException exc) {69throw new InternalError(70"internal error: " + algorithm + " not available.", exc);71}72}73}7475private byte[] hashDf(int requested, List<byte[]> inputs) {76return hashDf(digest, outLen, requested, inputs);77}7879/**80* A hash-based derivation function defined in NIST SP 800-90Ar1 10.3.1.81* The function is used inside Hash_DRBG, and can also be used as an82* approved conditioning function as described in 800-90B 6.4.2.2.83*84* Note: In each current call, requested is seedLen, therefore small,85* no need to worry about overflow.86*87* @param digest a {@code MessageDigest} object in reset state88* @param outLen {@link MessageDigest#getDigestLength} of {@code digest}89* @param requested requested output length, in bytes90* @param inputs input data91* @return the condensed/expanded output92*/93public static byte[] hashDf(MessageDigest digest, int outLen,94int requested, List<byte[]> inputs) {95// 1. temp = the Null string.96// 2. len = upper_int(no_of_bits_to_return / outLen)97int len = (requested + outLen - 1) / outLen;98byte[] temp = new byte[len * outLen];99// 3. counter = 0x01100int counter = 1;101102// 4. For i = 1 to len do103for (int i=0; i<len; i++) {104// 4.1 temp = temp105// || Hash (counter || no_of_bits_to_return || input_string).106digest.update((byte) counter);107digest.update((byte)(requested >> 21)); // requested*8 as int32108digest.update((byte)(requested >> 13));109digest.update((byte)(requested >> 5));110digest.update((byte)(requested << 3));111for (byte[] input : inputs) {112digest.update(input);113}114try {115digest.digest(temp, i * outLen, outLen);116} catch (DigestException e) {117throw new AssertionError("will not happen", e);118}119// 4.2 counter = counter + 1120counter++;121}122// 5. requested_bits = leftmost (temp, no_of_bits_to_return).123return temp.length == requested? temp: Arrays.copyOf(temp, requested);124// 6. Return125}126127// This method is used by both instantiation and reseeding.128@Override129protected final synchronized void hashReseedInternal(List<byte[]> inputs) {130131// 800-90Ar1 10.1.1.2: Instantiate Process.132// 800-90Ar1 10.1.1.3: Reseed Process.133byte[] seed;134135// Step 2: seed = Hash_df (seed_material, seedlen).136if (v != null) {137// Step 1 of 10.1.1.3: Prepend 0x01 || V138inputs.add(0, ONE);139inputs.add(1, v);140seed = hashDf(seedLen, inputs);141} else {142seed = hashDf(seedLen, inputs);143}144145// Step 3. V = seed.146v = seed;147148// Step 4. C = Hash_df ((0x00 || V), seedlen).149inputs = new ArrayList<>(2);150inputs.add(ZERO);151inputs.add(v);152c = hashDf(seedLen, inputs);153154// Step 5. reseed_counter = 1.155reseedCounter = 1;156157//status();158159// Step 6: Return160}161162private void status() {163if (debug != null) {164debug.println(this, "V = " + HexFormat.of().formatHex(v));165debug.println(this, "C = " + HexFormat.of().formatHex(c));166debug.println(this, "reseed counter = " + reseedCounter);167}168}169170/**171* Adds byte arrays into an existing one.172*173* @param out existing array174* @param data more arrays, can be of different length175*/176private static void addBytes(byte[] out, int len, byte[]... data) {177for (byte[] d: data) {178int dlen = d.length;179int carry = 0;180for (int i = 0; i < len; i++) {181int sum = (out[len - i - 1] & 0xff) + carry;182if (i < dlen) {183sum += (d[dlen - i - 1] & 0xff);184}185out[len - i - 1] = (byte) sum;186carry = sum >> 8;187if (i >= dlen - 1 && carry == 0) break;188}189}190}191192/**193* Generates a user-specified number of random bytes.194*195* @param result the array to be filled in with random bytes.196*/197@Override198public final synchronized void generateAlgorithm(199byte[] result, byte[] additionalInput) {200201if (debug != null) {202debug.println(this, "generateAlgorithm");203}204205// 800-90Ar1 10.1.1.4: Hash_DRBG_Generate Process206207// Step 1: Check reseed_counter. Will not fail. Already checked in208// AbstractDrbg#engineNextBytes.209210// Step 2: additional_input211if (additionalInput != null) {212digest.update((byte)2);213digest.update(v);214digest.update(additionalInput);215addBytes(v, seedLen, digest.digest());216}217218// Step 3. Hashgen (requested_number_of_bits, V).219hashGen(result, v);220221// Step 4. H = Hash (0x03 || V).222digest.update((byte)3);223digest.update(v);224byte[] h = digest.digest();225226// Step 5. V = (V + H + C + reseed_counter) mod 2seedlen.227byte[] rcBytes;228if (reseedCounter < 256) {229rcBytes = new byte[]{(byte)reseedCounter};230} else {231rcBytes = BigInteger.valueOf(reseedCounter).toByteArray();232}233addBytes(v, seedLen, h, c, rcBytes);234235// Step 6. reseed_counter = reseed_counter + 1.236reseedCounter++;237238//status();239240// Step 7: Return.241}242243// 800-90Ar1 10.1.1.4: Hashgen244private void hashGen(byte[] output, byte[] v) {245246// Step 2. data = V247byte[] data = v;248249// Step 3: W is output not filled250251// Step 4: For i = 1 to m252int pos = 0;253int len = output.length;254255while (len > 0) {256// Step 4.1 w = Hash (data).257digest.update(data);258if (len < outLen) {259// Step 4.2 W = W || w.260byte[] out = digest.digest();261System.arraycopy(out, 0, output, pos, len);262Arrays.fill(out, (byte)0);263} else {264try {265// Step 4.2 digest into right position, no need to cat266digest.digest(output, pos, outLen);267} catch (DigestException e) {268throw new AssertionError("will not happen", e);269}270}271len -= outLen;272if (len <= 0) {273// shortcut, so that data and pos needn't be updated274break;275}276// Step 4.3 data = (data + 1) mod 2^seedlen.277if (data == v) {278data = Arrays.copyOf(v, v.length);279}280addBytes(data, seedLen, ONE);281pos += outLen;282}283284// Step 5: No need to truncate285// Step 6: Return286}287}288289290