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

The following examples show how to use java.security.MessageDigest#getDigestLength() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MessageDigest2Test.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * java.security.MessageDigest#digest(byte[], int, int)
 */
public void test_digest$BII() throws Exception {
    for (Entry<Provider, List<String>> e : digestAlgs.entrySet()) {
        for (String algorithm : e.getValue()) {
            MessageDigest digest = MessageDigest.getInstance(algorithm, e.getKey().getName());
            assertNotNull(digest);
            int len = digest.getDigestLength();
            byte[] digestBytes = new byte[len];
            digest.digest(digestBytes, 0, digestBytes.length);
        }
        try {
            MessageDigest.getInstance("SHA").digest(new byte[] {}, Integer.MAX_VALUE, 755);
            fail();
        } catch (IllegalArgumentException expected) {
        }
    }
}
 
Example 2
Source File: TestSameLength.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: EdDSAParameterSpec.java    From mariadb-connector-j with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @param curve the curve
 * @param hashAlgo the JCA string for the hash algorithm
 * @param sc the parameter L represented as ScalarOps
 * @param B the parameter B
 * @throws IllegalArgumentException if hash algorithm is unsupported or length is wrong
 */
public EdDSAParameterSpec(Curve curve, String hashAlgo, ScalarOps sc, GroupElement B) {
  try {
    MessageDigest hash = MessageDigest.getInstance(hashAlgo);
    // EdDSA hash function must produce 2b-bit output
    if (curve.getField().getb() / 4 != hash.getDigestLength()) {
      throw new IllegalArgumentException("Hash output is not 2b-bit");
    }
  } catch (NoSuchAlgorithmException e) {
    throw new IllegalArgumentException("Unsupported hash algorithm");
  }

  this.curve = curve;
  this.hashAlgo = hashAlgo;
  this.sc = sc;
  this.B = B;
}
 
Example 4
Source File: TestSameLength.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 5
Source File: Hash.java    From chvote-protocol-poc with GNU Affero General Public License v3.0 6 votes vote down vote up
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 6
Source File: TestSameValue.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@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 7
Source File: StringUtilities.java    From WhiteRabbit with Apache License 2.0 5 votes vote down vote up
/**
 * Get hex string interpretation of the SHA-256 hash for an input string Author: Kristina
 */
public static String getSHA256Digest(String str) {
	try {
		byte[] buffer = str.getBytes();
		byte[] result = null;
		StringBuffer buf = null;
		MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
		// allocate room for the hash
		result = new byte[sha256.getDigestLength()];
		// calculate hash
		sha256.reset();
		sha256.update(buffer);
		
		result = sha256.digest();
		// System.out.println(result);
		// create hex string from the 16-byte hash
		buf = new StringBuffer(result.length * 2);
		for (int i = 0; i < result.length; i++) {
			int intVal = result[i] & 0xff;
			if (intVal < 0x10) {
				buf.append("0");
			}
			buf.append(Integer.toHexString(intVal).toUpperCase());
		}
		return buf.toString();
	} catch (NoSuchAlgorithmException e) {
		System.err.println("Exception caught: " + e);
		e.printStackTrace();
		
	}
	return null;
}
 
Example 8
Source File: TestSameValue.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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 9
Source File: TestSameValue.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@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 10
Source File: PowTests.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonceCalculation() {
    try {
        MessageDigest sha256MessageDigest = LedgerUtils.getSha256MessageDigest();
        byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15 };
        byte[] previousBlockHash = new byte[sha256MessageDigest.getDigestLength()];
        HashValidator hashValidator = new PowHashValidator(2);
        byte[] nonce = PowUtils.generateNonce(data, previousBlockHash, hashValidator, sha256MessageDigest);
        Assert.assertNotNull(nonce);
    } catch (Exception e) {
        Assert.fail();
    }
}
 
Example 11
Source File: TestSameValue.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@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 12
Source File: SimpleNonceManager.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
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 13
Source File: TestSameValue.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@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 14
Source File: TestSameValue.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@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 15
Source File: TestSameValue.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@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 16
Source File: TestSameValue.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@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 17
Source File: TestSameValue.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@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 18
Source File: DigestHelper.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private static String getPaddedDigestString(MessageDigest digest, BigInteger pwInt) {
    String checksum;
    String pwStr = pwInt.toString(16);
    // we have half byte string representation, so
    int padding = 2*digest.getDigestLength() - pwStr.length();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < padding; i++) {
        sb.append('0'); // make sure the MD5 password is 32 digits long
    }
    sb.append(pwStr);
    checksum = sb.toString();
    return checksum;
}
 
Example 19
Source File: PreviewImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * create an ID for a optioanl given text
 * @param text the text
 * @return id part of the text
 */
private String makeTextID (String text) {
	String	rc;

	if (text.length () < 32) {
		rc = text;
	} else {
		try {
			MessageDigest	md = MessageDigest.getInstance ("MD5");
			byte[]		digest;
			StringBuffer	buf;
			String[]	hd = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};

			md.update (text.getBytes ("UTF8"));
			digest = md.digest ();
			buf = new StringBuffer (md.getDigestLength ());
			for (int n = 0; n < digest.length; ++n) {
				buf.append (hd[(digest[n] >> 4) & 0xf]);
				buf.append (hd[digest[n] & 0xf]);
			}
			rc = buf.toString ();
		} catch (Exception e) {
			rc = text;
		}
	}
	return rc;
}
 
Example 20
Source File: ZsyncMake.java    From zsync4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public Result writeToChannel(Path inputFile, WritableByteChannel out, Options options) {

    if (inputFile == null) {
      throw new IllegalArgumentException("inputFile cannot be null");
    }
    if (!Files.exists(inputFile)) {
      throw new IllegalArgumentException("input file " + inputFile + " does not exist");
    }
    if (Files.isDirectory(inputFile)) {
      throw new IllegalArgumentException("input file " + inputFile + " is a directory");
    }
    if (options == null) {
      options = new Options();
    }

    final MessageDigest fileDigest = ZsyncUtil.newSHA1();
    final MessageDigest blockDigest = ZsyncUtil.newMD4();

    // We don't want to modify the Options object that was passed in, so we create a copy. We then
    // populate any missing
    // values using the supplied input file.
    options = new Options(options).calculateMissingValues(inputFile);

    final int blockSize = options.getBlockSize();
    final long fileLength;
    try {
      fileLength = Files.size(inputFile);
    } catch (IOException e) {
      throw new IllegalArgumentException("Unable to determine size of input file: " + e.getMessage(), e);
    }
    final int sequenceMatches = fileLength > options.getBlockSize() ? 2 : 1;
    final int weakChecksumLength = weakChecksumLength(fileLength, blockSize, sequenceMatches);
    final int strongChecksumLength = strongChecksumLength(fileLength, blockSize, sequenceMatches);

    final ByteBuffer checksums = this.computeChecksums(inputFile, blockSize, fileLength, weakChecksumLength,
        strongChecksumLength, fileDigest, blockDigest);

    // first read sha1 from end of buffer
    final int pos = checksums.capacity() - fileDigest.getDigestLength();
    checksums.position(pos);
    final String sha1 = ZsyncUtil.toHexString(checksums);

    // set buffer to read from beginning to start of fileDigest
    checksums.clear().limit(pos);

    // first write headers
    this.writeHeader(out, "zsync", ZSYNC_VERSION);
    this.writeHeader(out, "Filename", options.getFilename());
    this.writeHeader(out, "MTime", getFormattedLastModifiedTime(inputFile));
    this.writeHeader(out, "Blocksize", String.valueOf(blockSize));
    this.writeHeader(out, "Length", String.valueOf(fileLength));
    this.writeHeader(out, "Hash-Lengths", sequenceMatches + "," + weakChecksumLength + "," + strongChecksumLength);
    this.writeHeader(out, "URL", options.getUrl());
    this.writeHeader(out, "SHA-1", sha1);
    this.writeHeader(out, "\n");

    try {
      do {
        out.write(checksums);
      } while (checksums.hasRemaining());
    } catch (IOException exception) {
      throw new RuntimeException("Failed to write checksums", exception);
    }

    return new Result(sha1);
  }