Example usage for java.security DigestOutputStream DigestOutputStream

List of usage examples for java.security DigestOutputStream DigestOutputStream

Introduction

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

Prototype

public DigestOutputStream(OutputStream stream, MessageDigest digest) 

Source Link

Document

Creates a digest output stream, using the specified output stream and message digest.

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;//www .j a  v a 2 s  . c o m
    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:MainClass.java

static void performOutputTest() throws Exception {
    MessageDigest md = MessageDigest.getInstance("SHA");
    FileOutputStream fout = new FileOutputStream("sha-results.txt");
    DigestOutputStream out = new DigestOutputStream(fout, md);
    byte[] b = "testCase".getBytes();
    out.write(b, 0, b.length);/*ww  w  .  j a v  a2 s  .  c o m*/
    md = out.getMessageDigest();
    String s = new String(md.digest());
    System.out.println("Calculated result: " + s);
}

From source file:com.netflix.zeno.hash.HashOrderDependent.java

public HashOrderDependent() {
    try {/*  w  w  w  .  ja v  a2s. c o m*/
        digest = MessageDigest.getInstance("MD5");
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    digestOutputStream = new DigestOutputStream(NullOutputStream.NULL_OUTPUT_STREAM, digest);
    dataOutputStream = new DataOutputStream(digestOutputStream);
}

From source file:com.thoughtworks.go.server.dashboard.GoDashboardPipelineGroup.java

public String etag() {
    try {/*from   w  w  w  .j a v  a2  s. com*/
        MessageDigest digest = DigestUtils.getSha256Digest();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                new DigestOutputStream(new NullOutputStream(), digest));
        outputStreamWriter.write(name);
        outputStreamWriter.write("/");
        outputStreamWriter.write(Integer.toString(permissions.hashCode()));
        outputStreamWriter.write("[");

        for (Map.Entry<String, GoDashboardPipeline> entry : pipelines.entrySet()) {
            long lastUpdatedTimeStamp = entry.getValue().getLastUpdatedTimeStamp();
            outputStreamWriter.write(entry.getKey());
            outputStreamWriter.write(":");
            outputStreamWriter.write(Long.toString(lastUpdatedTimeStamp));
        }

        outputStreamWriter.write("]");
        outputStreamWriter.flush();

        return Hex.encodeHexString(digest.digest());
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:MethodHashing.java

public static long methodHash(Method method) throws Exception {
    Class[] parameterTypes = method.getParameterTypes();
    String methodDesc = method.getName() + "(";
    for (int j = 0; j < parameterTypes.length; j++) {
        methodDesc += getTypeString(parameterTypes[j]);
    }//from  w  w w .  j a va 2s . co m
    methodDesc += ")" + getTypeString(method.getReturnType());

    long hash = 0;
    ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(512);
    MessageDigest messagedigest = MessageDigest.getInstance("SHA");
    DataOutputStream dataoutputstream = new DataOutputStream(
            new DigestOutputStream(bytearrayoutputstream, messagedigest));
    dataoutputstream.writeUTF(methodDesc);
    dataoutputstream.flush();
    byte abyte0[] = messagedigest.digest();
    for (int j = 0; j < Math.min(8, abyte0.length); j++)
        hash += (long) (abyte0[j] & 0xff) << j * 8;
    return hash;
}

From source file:eu.peppol.document.AsicFilterInputStreamTest.java

/**
 * Takes a file holding an SBD/SBDH with an ASiC archive in base64 as payload and extracts the ASiC archive in binary format, while
 * calculating the message digest.//  ww  w . j  a  va  2 s  . c  om
 *
 * @throws Exception
 */
@Test
public void parseSampleSbdWithAsic() throws Exception {
    InputStream resourceAsStream = AsicFilterInputStreamTest.class.getClassLoader()
            .getResourceAsStream("sample-sbd-with-asic.xml");

    AsicFilterInputStream asicFilterInputStream = new AsicFilterInputStream(resourceAsStream);

    Path asicFile = Files.createTempFile("unit-test", ".asice");
    OutputStream asicOutputStream = Files.newOutputStream(asicFile);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");

    DigestOutputStream digestOutputStream = new DigestOutputStream(asicOutputStream, messageDigest);
    Base64OutputStream base64OutputStream = new Base64OutputStream(digestOutputStream, false);

    IOUtils.copy(asicFilterInputStream, base64OutputStream);
    log.debug("Wrote ASiC to:" + asicFile);
    log.debug("Digest: " + new String(Base64.getEncoder().encode(messageDigest.digest())));

}

From source file:com.adaptris.core.services.metadata.PayloadHashingService.java

public void doService(AdaptrisMessage msg) throws ServiceException {
    InputStream in = null;// w w  w .ja  v  a2 s.c  o m
    OutputStream out = null;
    try {
        in = msg.getInputStream();
        MessageDigest digest = MessageDigest.getInstance(getHashAlgorithm());
        out = new DigestOutputStream(new DevNullOutputStream(), digest);
        IOUtils.copy(in, out);
        out.flush();
        byte[] hash = digest.digest();
        msg.addMetadata(getMetadataKey(), new Base64ByteTranslator().translate(hash));
    } catch (Exception e) {
        throw new ServiceException(e);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.thoughtworks.go.server.dashboard.AbstractDashboardGroup.java

protected String digest(String permissionsSegment) {
    try {//from  ww  w.j  a va 2  s  .  c  o m
        MessageDigest digest = DigestUtils.getSha256Digest();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                new DigestOutputStream(new NullOutputStream(), digest));
        outputStreamWriter.write(getClass().getSimpleName());
        outputStreamWriter.write("$");
        outputStreamWriter.write(name());
        outputStreamWriter.write("/");
        outputStreamWriter.write(permissionsSegment);
        outputStreamWriter.write("[");

        for (GoDashboardPipeline pipeline : allPipelines()) {
            outputStreamWriter.write(pipeline.cacheSegment());
            outputStreamWriter.write(",");
        }

        outputStreamWriter.write("]");
        outputStreamWriter.flush();

        return Hex.encodeHexString(digest.digest());
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:eu.peppol.document.PayloadParserTest.java

/**
 * Takes a file holding an SBD/SBDH with an ASiC archive in base64 as payload and extracts the ASiC archive in binary format, while
 * calculating the message digest.// w w  w  .j a v a2  s  . c  om
 *
 * @throws Exception
 */
@Test
public void parseSampleSbdWithAsic() throws Exception {

    InputStream resourceAsStream = PayloadParserTest.class.getClassLoader()
            .getResourceAsStream("sample-sbd-with-asic.xml");
    assertNotNull(resourceAsStream);

    Path xmlFile = Files.createTempFile("unit-test", ".xml");

    XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(resourceAsStream,
            "UTF-8");
    FileOutputStream outputStream = new FileOutputStream(xmlFile.toFile());
    XMLEventWriter xmlEventWriter = XMLOutputFactory.newInstance().createXMLEventWriter(outputStream, "UTF-8");

    Path asicFile = Files.createTempFile("unit-test", ".asice");
    OutputStream asicOutputStream = Files.newOutputStream(asicFile);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");

    DigestOutputStream digestOutputStream = new DigestOutputStream(asicOutputStream, messageDigest);
    Base64OutputStream base64OutputStream = new Base64OutputStream(digestOutputStream, false);

    boolean insideAsicElement = false;

    while (xmlEventReader.hasNext()) {
        XMLEvent xmlEvent = xmlEventReader.nextEvent();

        switch (xmlEvent.getEventType()) {
        case XMLEvent.START_ELEMENT:
            String localPart = xmlEvent.asStartElement().getName().getLocalPart();
            if ("asic".equals(localPart)) {
                insideAsicElement = true;
            }
            break;
        case XMLEvent.END_ELEMENT:
            localPart = xmlEvent.asEndElement().getName().getLocalPart();
            if ("asic".equals(localPart)) {
                insideAsicElement = false;
            }
            break;

        case XMLEvent.CHARACTERS:
            // Whenever we are inside the ASiC XML element, spit
            // out the base64 encoded data into the base64 decoding output stream.
            if (insideAsicElement) {
                Characters characters = xmlEvent.asCharacters();
                base64OutputStream.write(characters.getData().getBytes("UTF-8"));
            }
            break;
        }
        xmlEventWriter.add(xmlEvent);
    }

    asicOutputStream.close();
    outputStream.close();
    log.debug("Wrote xml output to: " + xmlFile);
    log.debug("Wrote ASiC to:" + asicFile);
    log.debug("Digest: " + new String(Base64.getEncoder().encode(messageDigest.digest())));
}

From source file:MethodHashing.java

public static long constructorHash(Constructor method) throws Exception {
    Class[] parameterTypes = method.getParameterTypes();
    String methodDesc = method.getName() + "(";
    for (int j = 0; j < parameterTypes.length; j++) {
        methodDesc += getTypeString(parameterTypes[j]);
    }//  w ww.j a  v a  2  s. c o m
    methodDesc += ")";

    long hash = 0;
    ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(512);
    MessageDigest messagedigest = MessageDigest.getInstance("SHA");
    DataOutputStream dataoutputstream = new DataOutputStream(
            new DigestOutputStream(bytearrayoutputstream, messagedigest));
    dataoutputstream.writeUTF(methodDesc);
    dataoutputstream.flush();
    byte abyte0[] = messagedigest.digest();
    for (int j = 0; j < Math.min(8, abyte0.length); j++)
        hash += (long) (abyte0[j] & 0xff) << j * 8;
    return hash;
}