Java Code Examples for java.security.MessageDigest.getDigestLength()

The following are Jave code examples for showing how to use getDigestLength() of the java.security.MessageDigest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: guava-mock   File: MessageDigestHashFunctionTest.java   View Source Code Vote up 6 votes
private static void assertMessageDigestHashing(byte[] input, String algorithmName) {
  try {
    MessageDigest digest = MessageDigest.getInstance(algorithmName);
    assertEquals(
        HashCode.fromBytes(digest.digest(input)),
        ALGORITHMS.get(algorithmName).hashBytes(input));
    for (int bytes = 4; bytes <= digest.getDigestLength(); bytes++) {
      assertEquals(
          HashCode.fromBytes(Arrays.copyOf(digest.digest(input), bytes)),
          new MessageDigestHashFunction(algorithmName, bytes, algorithmName).hashBytes(input));
    }
    try {
      int maxSize = digest.getDigestLength();
      new MessageDigestHashFunction(algorithmName, maxSize + 1, algorithmName);
      fail();
    } catch (IllegalArgumentException expected) {
    }
  } catch (NoSuchAlgorithmException nsae) {
    throw new AssertionError(nsae);
  }
}
 
Example 2
Project: jdk8u-jdk   File: TestSameLength.java   View Source Code Vote up 6 votes
private boolean runTest(String algo, long dataLen,
        UpdateMethod whichUpdate) throws Exception {
    try {
        // Do initialization
        byte[] data = new byte[(int) dataLen];
        new Random().nextBytes(data);
        MessageDigest md = MessageDigest.getInstance(algo);
        int outputLen = md.getDigestLength();

        // Perform the update using all available/possible update methods
        whichUpdate.updateDigest(data, md, dataLen);
        // Get the output
        byte[] output = md.digest();

        // Compare input and output
        return outputLen == output.length;
    } catch (Exception ex) {
        System.err.println("Testing: " + algo + "/" + dataLen + "/"
                + whichUpdate.toString()
                + " failed with unexpected exception");
        ex.printStackTrace();
        throw ex;
    }
}
 
Example 3
Project: chvote-protocol-poc   File: Hash.java   View Source Code Vote up 6 votes
public Hash(String digestAlgorithm, String digestProvider, SecurityParameters securityParameters, Conversion conversion) {
    this.digestAlgorithm = digestAlgorithm;
    this.digestProvider = digestProvider;
    this.conversion = conversion;
    this.securityParameters = securityParameters;

    MessageDigest messageDigest = newMessageDigest();
    if (messageDigest.getDigestLength() < securityParameters.getUpper_l()) {
        throw new IllegalArgumentException(
                String.format(
                        "The length of the message digest should be greater or equal to the expected output " +
                                "length. Got %d expected %d (bytes)",
                        messageDigest.getDigestLength(),
                        securityParameters.getUpper_l()));
    }
}
 
Example 4
Project: googles-monorepo-demo   File: MessageDigestHashFunctionTest.java   View Source Code Vote up 6 votes
private static void assertMessageDigestHashing(byte[] input, String algorithmName) {
  try {
    MessageDigest digest = MessageDigest.getInstance(algorithmName);
    assertEquals(
        HashCode.fromBytes(digest.digest(input)),
        ALGORITHMS.get(algorithmName).hashBytes(input));
    for (int bytes = 4; bytes <= digest.getDigestLength(); bytes++) {
      assertEquals(
          HashCode.fromBytes(Arrays.copyOf(digest.digest(input), bytes)),
          new MessageDigestHashFunction(algorithmName, bytes, algorithmName).hashBytes(input));
    }
    try {
      int maxSize = digest.getDigestLength();
      new MessageDigestHashFunction(algorithmName, maxSize + 1, algorithmName);
      fail();
    } catch (IllegalArgumentException expected) {
    }
  } catch (NoSuchAlgorithmException nsae) {
    throw new AssertionError(nsae);
  }
}
 
Example 5
Project: talchain   File: TreeChunker.java   View Source Code Vote up 5 votes
public TreeChunker(int branches, MessageDigest hasher) {
    this.branches = branches;
    this.hasher = hasher;

    hashSize = hasher.getDigestLength();
    chunkSize = hashSize * branches;
}
 
Example 6
Project: lams   File: SimpleNonceManager.java   View Source Code Vote up 5 votes
public SimpleNonceManager(final String hashAlg) {
    // Verify it is a valid algorithm (at least for now)
    MessageDigest digest = getDigest(hashAlg);

    this.hashAlg = hashAlg;
    this.hashLength = digest.getDigestLength();

    // Create a new secret only valid within this NonceManager instance.
    Random rand = new SecureRandom();
    byte[] secretBytes = new byte[32];
    rand.nextBytes(secretBytes);
    secret = FlexBase64.encodeString(digest.digest(secretBytes), false);
}
 
Example 7
Project: xmlrss   File: CryptoUtils.java   View Source Code Vote up 5 votes
/**
 * Calculates a full domain hash (FDH) for the given byte array and the given maximum, where
 * <code>FDH < max</code>
 *
 * @param max the maximum value of the resulting FDH
 * @param m   message for which the hash is calculated
 * @return a big integer representing the full domain hash
 * @throws NoSuchAlgorithmException if no SHA-512 implementation is found
 */
public static BigInteger fullDomainHash(BigInteger max, byte[] m) throws NoSuchAlgorithmException {
    BigInteger fdh;
    BigInteger counter = BigInteger.ZERO;
    MessageDigest md = MessageDigest.getInstance("SHA-512");
    int digestLength = md.getDigestLength();
    int bitLength = max.bitLength();

    byte[] shortHash = getShortHash(md, m, counter);
    byte[] largeHash = shortHash;
    counter = counter.add(BigInteger.ONE);

    // concatenate new small hashes to the large hash until the bitlenght of the large hash is bigger than or equal
    // to the bitlength of max
    while ((largeHash.length * 8) < bitLength) {
        shortHash = getShortHash(md, m, counter);
        counter = counter.add(BigInteger.ONE);
        largeHash = new ByteArray(largeHash).concat(shortHash).getArray();
    }

    fdh = convertHashToBigInt(largeHash, bitLength);

    // while resulting fdh is too big, cut off the first part of the fdh and append a new short hash
    while (fdh.compareTo(max) > 0) {
        counter = counter.add(BigInteger.ONE);
        shortHash = getShortHash(md, m, counter);
        System.arraycopy(largeHash, digestLength, largeHash, 0, largeHash.length - digestLength);
        System.arraycopy(shortHash, 0, largeHash, largeHash.length - digestLength, digestLength);

        fdh = convertHashToBigInt(largeHash, bitLength);
    }

    return fdh;
}
 
Example 8
Project: jdk8u-jdk   File: TestSameValue.java   View Source Code Vote up 5 votes
@Override
public byte[] updateDigest(byte[] data, MessageDigest md)
        throws DigestException {
    for (byte element: data) {
        md.update(element);
    }
    byte[] output = new byte[md.getDigestLength()];
    int len = md.digest(output, 0, output.length);
    if (len != output.length) {
        throw new RuntimeException(
            "ERROR" + ": digest length differs!");
    }
    return output;
}
 
Example 9
Project: jdk8u-jdk   File: TestSameValue.java   View Source Code Vote up 5 votes
@Override
public byte[] updateDigest(byte[] data, MessageDigest md)
        throws DigestException {
    md.update(data);
    byte[] output = new byte[md.getDigestLength()];
    int len = md.digest(output, 0, output.length);
    if (len != output.length) {
        throw new RuntimeException(
            "ERROR" + ": digest length differs!");
    }
    return output;
}
 
Example 10
Project: jdk8u-jdk   File: TestSameValue.java   View Source Code Vote up 5 votes
@Override
public byte[] updateDigest(byte[] data, MessageDigest md)
        throws DigestException {

    for (int i = 0; i < data.length / 2; i++) {
        md.update(data, i * 2, 2);
    }
    byte[] output = new byte[md.getDigestLength()];
    int len = md.digest(output, 0, output.length);
    if (len != output.length) {
        throw new RuntimeException(
            "ERROR" + ": digest length differs!");
    }
    return output;
}
 
Example 11
Project: jdk8u-jdk   File: TestSameValue.java   View Source Code Vote up 5 votes
@Override
public byte[] updateDigest(byte[] data, MessageDigest md)
        throws DigestException {
    md.update(ByteBuffer.wrap(data));
    byte[] output = new byte[md.getDigestLength()];
    int len = md.digest(output, 0, output.length);
    if (len != output.length) {
        throw new RuntimeException(
              "ERROR" + ": digest length differs!");
    }
    return output;
}
 
Example 12
Project: openjdk-jdk10   File: TestSameValue.java   View Source Code Vote up 5 votes
@Override
public byte[] updateDigest(byte[] data, MessageDigest md)
        throws DigestException {
    for (byte element : data) {
        md.update(element);
    }
    byte[] output = new byte[md.getDigestLength()];
    int len = md.digest(output, 0, output.length);
    if (len != output.length) {
        throw new RuntimeException(
                "ERROR" + ": digest length differs!");
    }
    return output;
}
 
Example 13
Project: openjdk-jdk10   File: TestSameValue.java   View Source Code Vote up 5 votes
@Override
public byte[] updateDigest(byte[] data, MessageDigest md)
        throws DigestException {
    md.update(data);
    byte[] output = new byte[md.getDigestLength()];
    int len = md.digest(output, 0, output.length);
    if (len != output.length) {
        throw new RuntimeException(
                "ERROR" + ": digest length differs!");
    }
    return output;
}
 
Example 14
Project: openjdk-jdk10   File: TestSameValue.java   View Source Code Vote up 5 votes
@Override
public byte[] updateDigest(byte[] data, MessageDigest md)
        throws DigestException {

    for (int i = 0; i < data.length / 2; i++) {
        md.update(data, i * 2, 2);
    }
    byte[] output = new byte[md.getDigestLength()];
    int len = md.digest(output, 0, output.length);
    if (len != output.length) {
        throw new RuntimeException(
                "ERROR" + ": digest length differs!");
    }
    return output;
}
 
Example 15
Project: openjdk-jdk10   File: TestSameValue.java   View Source Code Vote up 5 votes
@Override
public byte[] updateDigest(byte[] data, MessageDigest md)
        throws DigestException {
    md.update(ByteBuffer.wrap(data));
    byte[] output = new byte[md.getDigestLength()];
    int len = md.digest(output, 0, output.length);
    if (len != output.length) {
        throw new RuntimeException(
                "ERROR" + ": digest length differs!");
    }
    return output;
}
 
Example 16
Project: openjdk-jdk10   File: TestSameLength.java   View Source Code Vote up 5 votes
private boolean runTest(String algo, long dataLen, UpdateMethod whichUpdate)
        throws Exception {
    try {
        // Do initialization
        byte[] data = new byte[(int) dataLen];
        RandomFactory.getRandom().nextBytes(data);
        MessageDigest md = MessageDigest.getInstance(algo);
        int outputLen = md.getDigestLength();

        // Perform the update using all available/possible update methods
        whichUpdate.updateDigest(data, md, dataLen);
        // Get the output
        byte[] output = md.digest();

        // Compare input and output
        return outputLen == output.length;
    } catch (NoSuchAlgorithmException nae) {
        if (algo.startsWith("SHA3") && !isSHA3supported()) {
            return true;
        }
        throw nae;
    } catch (Exception ex) {
        System.err.println("Testing: " + algo + "/" + dataLen + "/"
                + whichUpdate.toString()
                + " failed with unexpected exception");
        ex.printStackTrace();
        throw ex;
    }
}
 
Example 17
Project: AppCoins-ethereumj   File: TreeChunker.java   View Source Code Vote up 5 votes
public TreeChunker(int branches, MessageDigest hasher) {
    this.branches = branches;
    this.hasher = hasher;

    hashSize = hasher.getDigestLength();
    chunkSize = hashSize * branches;
}
 
Example 18
Project: RISE-V2G   File: SecurityUtils.java   View Source Code Vote up 4 votes
/**
 * Implementation of Concatenation Key Derivation Function 
 * http://csrc.nist.gov/publications/nistpubs/800-56A/SP800-56A_Revision1_Mar08-2007.pdf
 *
 * Author: NimbusDS  Lai Xin Chu and Vladimir Dzhuvinov
 * 
 * See https://code.google.com/p/openinfocard/source/browse/trunk/testsrc/org/xmldap/crypto/ConcatKeyDerivationFunction.java?r=770
 */
private static byte[] concatKDF(MessageDigest md, byte[] z, int keyDataLen, byte[] otherInfo) {
	final long MAX_HASH_INPUTLEN = Long.MAX_VALUE;
	final long UNSIGNED_INT_MAX_VALUE = 4294967295L;
	keyDataLen = keyDataLen/8;
       byte[] key = new byte[keyDataLen];
       
       int hashLen = md.getDigestLength();
       int reps = keyDataLen / hashLen;
       
       if (reps > UNSIGNED_INT_MAX_VALUE) {
       	getLogger().error("Key derivation failed");
       	return null;
       }
       
       int counter = 1;
       byte[] counterInBytes = ByteUtils.intToFourBytes(counter);
       
       if ((counterInBytes.length + z.length + otherInfo.length) * 8 > MAX_HASH_INPUTLEN) {
       	getLogger().error("Key derivation failed");
       	return null;
       }
       
       for (int i = 0; i <= reps; i++) {
           md.reset();
           md.update(ByteUtils.intToFourBytes(i+1));
           md.update(z);
           md.update(otherInfo);
           
           byte[] hash = md.digest();
           if (i < reps) {
               System.arraycopy(hash, 0, key, hashLen * i, hashLen);
           } else {
               if (keyDataLen % hashLen == 0) {
                   System.arraycopy(hash, 0, key, hashLen * i, hashLen);
               } else {
                   System.arraycopy(hash, 0, key, hashLen * i, keyDataLen % hashLen);
               }
           }
       }
       
       return key;
   }