Example usage for java.security DigestOutputStream write

List of usage examples for java.security DigestOutputStream write

Introduction

In this page you can find the example usage for java.security DigestOutputStream write.

Prototype

public void write(int b) throws IOException 

Source Link

Document

Updates the message digest (if the digest function is on) using the specified byte, and in any case writes the byte to the output stream.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    byte[] input = "www.java2s.com".getBytes();
    System.out.println("input     : " + new String(input));
    MessageDigest hash = MessageDigest.getInstance("SHA1");

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(input);
    DigestInputStream digestInputStream = new DigestInputStream(byteArrayInputStream, hash);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    int ch;//  w ww .  j  ava 2s  .com
    while ((ch = digestInputStream.read()) >= 0) {
        byteArrayOutputStream.write(ch);
    }

    byte[] newInput = byteArrayOutputStream.toByteArray();
    System.out.println("in digest : " + new String(digestInputStream.getMessageDigest().digest()));

    byteArrayOutputStream = new ByteArrayOutputStream();
    DigestOutputStream digestOutputStream = new DigestOutputStream(byteArrayOutputStream, hash);
    digestOutputStream.write(newInput);
    digestOutputStream.close();

    System.out.println("out digest: " + new String(digestOutputStream.getMessageDigest().digest()));
}

From source file:org.apache.hadoop.hdfs.qjournal.server.TestJournalNodeImageManifest.java

/**
 * Generate random contents for the image and store it together with the md5
 * for later comparison./* www  . j av  a2  s .com*/
 */
private ContentBody genContent(long txid) throws IOException {
    MessageDigest digester = MD5Hash.getDigester();

    // write through digester so we can roll the written image
    ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
    DigestOutputStream ds = new DigestOutputStream(bos, digester);

    // generate random bytes
    new Random().nextBytes(randomBytes);
    ds.write(randomBytes);
    ds.flush();

    // get written hash
    MD5Hash hash = new MD5Hash(digester.digest());

    // store contents and digest
    digests.put(txid, hash);
    content.put(txid, Arrays.copyOf(randomBytes, randomBytes.length));

    return new ByteArrayBody(bos.toByteArray(), "filename");
}