java.security.DigestOutputStream Java Examples

The following examples show how to use java.security.DigestOutputStream. 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: NativeS3FileSystem.java    From hadoop with Apache License 2.0 6 votes vote down vote up
public NativeS3FsOutputStream(Configuration conf,
    NativeFileSystemStore store, String key, Progressable progress,
    int bufferSize) throws IOException {
  this.conf = conf;
  this.key = key;
  this.backupFile = newBackupFile();
  LOG.info("OutputStream for key '" + key + "' writing to tempfile '" + this.backupFile + "'");
  try {
    this.digest = MessageDigest.getInstance("MD5");
    this.backupStream = new BufferedOutputStream(new DigestOutputStream(
        new FileOutputStream(backupFile), this.digest));
  } catch (NoSuchAlgorithmException e) {
    LOG.warn("Cannot load MD5 digest algorithm," +
        "skipping message integrity check.", e);
    this.backupStream = new BufferedOutputStream(
        new FileOutputStream(backupFile));
  }
}
 
Example #2
Source File: BuildCheckpoints.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
private static void writeBinaryCheckpoints(TreeMap<Integer, StoredBlock> checkpoints, File file) throws Exception {
    final FileOutputStream fileOutputStream = new FileOutputStream(file, false);
    MessageDigest digest = Sha256Hash.newDigest();
    final DigestOutputStream digestOutputStream = new DigestOutputStream(fileOutputStream, digest);
    digestOutputStream.on(false);
    final DataOutputStream dataOutputStream = new DataOutputStream(digestOutputStream);
    dataOutputStream.writeBytes("CHECKPOINTS 1");
    dataOutputStream.writeInt(0);  // Number of signatures to read. Do this later.
    digestOutputStream.on(true);
    dataOutputStream.writeInt(checkpoints.size());
    ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE);
    for (StoredBlock block : checkpoints.values()) {
        block.serializeCompact(buffer);
        dataOutputStream.write(buffer.array());
        buffer.position(0);
    }
    dataOutputStream.close();
    Sha256Hash checkpointsHash = Sha256Hash.wrap(digest.digest());
    System.out.println("Hash of checkpoints data is " + checkpointsHash);
    digestOutputStream.close();
    fileOutputStream.close();
    System.out.println("Checkpoints written to '" + file.getCanonicalPath() + "'.");
}
 
Example #3
Source File: CipherStreamClose.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example #4
Source File: SwarmContentRepository.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] addContent(InputStream stream) throws IOException {
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        byte[] sha1Bytes;
        Path tmp = TempFileManager.INSTANCE.newTempFile("content", ".tmp").toPath();
        try (OutputStream fos = Files.newOutputStream(tmp); BufferedInputStream bis = new BufferedInputStream(stream)) {
            messageDigest.reset();
            try (DigestOutputStream dos = new DigestOutputStream(fos, messageDigest)) {
                byte[] bytes = new byte[8192];
                int read;
                while ((read = bis.read(bytes)) > -1) {
                    dos.write(bytes, 0, read);
                }
                fos.flush();
            }
            sha1Bytes = messageDigest.digest();
        }
        String key = toKey(sha1Bytes);
        this.index.put(key, tmp.toUri());
        return sha1Bytes;
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }
}
 
Example #5
Source File: CipherStreamClose.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example #6
Source File: DigestOutputStreamTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * java.io.DigestOutputStream#write(byte[], int, int)
 */
public void test_write$BII_7()
    throws IOException, NoSuchAlgorithmException {
    Support_OutputStream sos = new Support_OutputStream(MY_MESSAGE_LEN);
    MessageDigest md = MessageDigest.getInstance(algorithmName[0]);
    DigestOutputStream dos = new DigestOutputStream(sos, md);

    dos.write(myMessage, 0, MY_MESSAGE_LEN);

    try {
        // Support_OutputStream throws an IOException if the internal
        // buffer is full, which it should be now.
        dos.write(myMessage, 0, MY_MESSAGE_LEN);
        fail("Test 1: IOException expected.");
    } catch (IOException e) {
        // Expected.
    }
}
 
Example #7
Source File: DigestOutputStreamTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * java.security.DigestOutputStream#setMessageDigest(MessageDigest)
 */
public void test_setMessageDigestLjava_security_MessageDigest() {

    MessageDigest digest = new MyMessageDigest1();
    OutputStream out = new MyOutputStream();

    DigestOutputStream dos = new DigestOutputStream(out, null);

    // non-null parameter
    dos.setMessageDigest(digest);
    assertSame(digest, dos.getMessageDigest());

    // null parameter
    dos.setMessageDigest(null);
    assertNull("getMessageDigest should have returned null", dos.getMessageDigest());
}
 
Example #8
Source File: CipherStreamClose.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example #9
Source File: CipherStreamClose.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example #10
Source File: BuildCheckpoints.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
private static void writeBinaryCheckpoints(TreeMap<Integer, StoredBlock> checkpoints, File file) throws Exception {
    final FileOutputStream fileOutputStream = new FileOutputStream(file, false);
    MessageDigest digest = Sha256Hash.newDigest();
    final DigestOutputStream digestOutputStream = new DigestOutputStream(fileOutputStream, digest);
    digestOutputStream.on(false);
    final DataOutputStream dataOutputStream = new DataOutputStream(digestOutputStream);
    dataOutputStream.writeBytes("CHECKPOINTS 1");
    dataOutputStream.writeInt(0);  // Number of signatures to read. Do this later.
    digestOutputStream.on(true);
    dataOutputStream.writeInt(checkpoints.size());
    ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE);
    for (StoredBlock block : checkpoints.values()) {
        block.serializeCompact(buffer);
        dataOutputStream.write(buffer.array());
        buffer.position(0);
    }
    dataOutputStream.close();
    Sha256Hash checkpointsHash = Sha256Hash.wrap(digest.digest());
    System.out.println("Hash of checkpoints data is " + checkpointsHash);
    digestOutputStream.close();
    fileOutputStream.close();
    System.out.println("Checkpoints written to '" + file.getCanonicalPath() + "'.");
}
 
Example #11
Source File: Report.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected String xmlDigest(JasperPrint print) 
		throws NoSuchAlgorithmException, FileNotFoundException, JRException, IOException
{
	File outputFile = createXmlOutputFile();
	log.debug("XML export output at " + outputFile.getAbsolutePath());
	
	MessageDigest digest = MessageDigest.getInstance("SHA-1");
	FileOutputStream output = new FileOutputStream(outputFile);
	try
	{
		DigestOutputStream out = new DigestOutputStream(output, digest);
		xmlExport(print, out);
	}
	finally
	{
		output.close();
	}
	
	return toDigestString(digest);
}
 
Example #12
Source File: CipherStreamClose.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example #13
Source File: NativeS3FileSystem.java    From RDFS with Apache License 2.0 6 votes vote down vote up
public NativeS3FsOutputStream(Configuration conf,
    NativeFileSystemStore store, String key, Progressable progress,
    int bufferSize) throws IOException {
  this.conf = conf;
  this.key = key;
  this.backupFile = newBackupFile();
  try {
    this.digest = MessageDigest.getInstance("MD5");
    this.backupStream = new BufferedOutputStream(new DigestOutputStream(
        new FileOutputStream(backupFile), this.digest));
  } catch (NoSuchAlgorithmException e) {
    LOG.warn("Cannot load MD5 digest algorithm," +
        "skipping message integrity check.", e);
    this.backupStream = new BufferedOutputStream(
        new FileOutputStream(backupFile));
  }
}
 
Example #14
Source File: NativeS3FileSystem.java    From big-c with Apache License 2.0 6 votes vote down vote up
public NativeS3FsOutputStream(Configuration conf,
    NativeFileSystemStore store, String key, Progressable progress,
    int bufferSize) throws IOException {
  this.conf = conf;
  this.key = key;
  this.backupFile = newBackupFile();
  LOG.info("OutputStream for key '" + key + "' writing to tempfile '" + this.backupFile + "'");
  try {
    this.digest = MessageDigest.getInstance("MD5");
    this.backupStream = new BufferedOutputStream(new DigestOutputStream(
        new FileOutputStream(backupFile), this.digest));
  } catch (NoSuchAlgorithmException e) {
    LOG.warn("Cannot load MD5 digest algorithm," +
        "skipping message integrity check.", e);
    this.backupStream = new BufferedOutputStream(
        new FileOutputStream(backupFile));
  }
}
 
Example #15
Source File: SquallArchiveWriter.java    From imhotep with Apache License 2.0 6 votes vote down vote up
private void internalAppendFile(FSDataOutputStream os, File file, List<String> parentDirectories, SquallArchiveCompressor compressor, String archiveFilename) throws IOException {
    final String baseFilename = file.getName().replaceAll("\\s+", "_");
    final String filename = makeFilename(parentDirectories, baseFilename);
    final long size = file.length();
    final long timestamp = file.lastModified();
    final long startOffset = os.getPos();

    final InputStream is = new BufferedInputStream(new FileInputStream(file));
    final String checksum;
    try {
        final CompressionOutputStream cos = compressor.newOutputStream(os);
        final DigestOutputStream dos = new DigestOutputStream(cos, ArchiveUtils.getMD5Digest());
        ByteStreams.copy(is, dos);
        checksum = ArchiveUtils.toHex(dos.getMessageDigest().digest());
        cos.finish();
    } finally {
        is.close();
    }

    pendingMetadataWrites.add(new FileMetadata(filename, size, timestamp, checksum, startOffset, compressor, archiveFilename));
}
 
Example #16
Source File: CipherStreamClose.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example #17
Source File: PluginsZip.java    From gocd with Apache License 2.0 6 votes vote down vote up
public void create() {
    checkFilesAccessibility(bundledPlugins, externalPlugins);
    reset();

    MessageDigest md5Digest = DigestUtils.getMd5Digest();
    try (ZipOutputStream zos = new ZipOutputStream(new DigestOutputStream(new BufferedOutputStream(new FileOutputStream(destZipFile)), md5Digest))) {
        for (GoPluginBundleDescriptor agentPlugins : agentPlugins()) {
            String zipEntryPrefix = "external/";

            if (agentPlugins.isBundledPlugin()) {
                zipEntryPrefix = "bundled/";
            }

            zos.putNextEntry(new ZipEntry(zipEntryPrefix + new File(agentPlugins.bundleJARFileLocation()).getName()));
            Files.copy(new File(agentPlugins.bundleJARFileLocation()).toPath(), zos);
            zos.closeEntry();
        }
    } catch (Exception e) {
        LOG.error("Could not create zip of plugins for agent to download.", e);
    }

    md5DigestOfPlugins = Hex.encodeHexString(md5Digest.digest());
}
 
Example #18
Source File: CipherStreamClose.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example #19
Source File: CipherStreamClose.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example #20
Source File: DeviceSimulatorUpdater.java    From hawkbit-examples with Eclipse Public License 1.0 5 votes vote down vote up
private static long getOverallRead(final CloseableHttpResponse response, final MessageDigest md)
        throws IOException {

    long overallread;

    try (final OutputStream os = ByteStreams.nullOutputStream();
            final BufferedOutputStream bos = new BufferedOutputStream(new DigestOutputStream(os, md))) {

        try (BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent())) {
            overallread = ByteStreams.copy(bis, bos);
        }
    }

    return overallread;
}
 
Example #21
Source File: TestDigestIOStream.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test DigestInputStream and DigestOutputStream digest function when use
 * same message digest object.
 *
 * @param algo
 *            Message Digest algorithm
 * @param dataLength
 *            plain test data length.
 * @exception Exception
 *                throw unexpected exception
 */
public boolean testMDShare(String algo, int dataLength) throws Exception {
    MessageDigest mdCommon = MessageDigest.getInstance(algo);
    // Generate the DigestInputStream/DigestOutputStream object
    try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
            DigestInputStream dis = new DigestInputStream(bais, mdCommon);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DigestOutputStream dos = new DigestOutputStream(baos, mdCommon);) {

        // Perform the update using all available/possible update methods
        int k = 0;
        byte[] buffer = new byte[10];

        // use both read() and read(byte[], int, int)
        while (k < data.length) {
            int len = dis.read(buffer, 0, buffer.length);
            if (len != -1) {
                k += len;
                if (k < data.length) {
                    dos.write(data[k]);
                    k++;
                    dis.skip(1);
                }
            }
        }

        // Get the output and the "correct" digest values
        byte[] output = mdCommon.digest();
        byte[] standard = md.digest(data);

        // Compare generated digest values
        return MessageDigest.isEqual(output, standard);
    } catch (Exception ex) {
        out.println("TestMDShare failed at:" + algo + "/" + dataLength
                + " with unexpected exception");
        throw ex;
    }
}
 
Example #22
Source File: Util.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Compute the "method hash" of a remote method.  The method hash
 * is a long containing the first 64 bits of the SHA digest from
 * the UTF encoded string of the method name and descriptor.
 */
public static long computeMethodHash(Method m) {
    long hash = 0;
    ByteArrayOutputStream sink = new ByteArrayOutputStream(127);
    try {
        MessageDigest md = MessageDigest.getInstance("SHA");
        DataOutputStream out = new DataOutputStream(
            new DigestOutputStream(sink, md));

        String s = getMethodNameAndDescriptor(m);
        if (serverRefLog.isLoggable(Log.VERBOSE)) {
            serverRefLog.log(Log.VERBOSE,
                "string used for method hash: \"" + s + "\"");
        }
        out.writeUTF(s);

        // use only the first 64 bits of the digest for the hash
        out.flush();
        byte hasharray[] = md.digest();
        for (int i = 0; i < Math.min(8, hasharray.length); i++) {
            hash += ((long) (hasharray[i] & 0xFF)) << (i * 8);
        }
    } catch (IOException ignore) {
        /* can't happen, but be deterministic anyway. */
        hash = -1;
    } catch (NoSuchAlgorithmException complain) {
        throw new SecurityException(complain.getMessage());
    }
    return hash;
}
 
Example #23
Source File: HashUtils.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static byte[] copyAndGetHash(final InputStream is, final OutputStream os) throws IOException {
    byte[] sha1Bytes;
    synchronized (DIGEST) {
        DIGEST.reset();
        try (BufferedInputStream bis = new BufferedInputStream(is);
             DigestOutputStream dos = new DigestOutputStream(os, DIGEST)) {
            IoUtils.copyStream(bis, dos);
        }
        sha1Bytes = DIGEST.digest();
    }
    return sha1Bytes;
}
 
Example #24
Source File: TestDigestIOStream.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test DigestInputStream and DigestOutputStream digest function when use
 * same message digest object.
 *
 * @param algo
 *            Message Digest algorithm
 * @param dataLength
 *            plain test data length.
 * @exception Exception
 *                throw unexpected exception
 */
public boolean testMDShare(String algo, int dataLength) throws Exception {
    MessageDigest mdCommon = MessageDigest.getInstance(algo);
    // Generate the DigestInputStream/DigestOutputStream object
    try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
            DigestInputStream dis = new DigestInputStream(bais, mdCommon);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DigestOutputStream dos = new DigestOutputStream(baos, mdCommon);) {

        // Perform the update using all available/possible update methods
        int k = 0;
        byte[] buffer = new byte[10];

        // use both read() and read(byte[], int, int)
        while (k < data.length) {
            int len = dis.read(buffer, 0, buffer.length);
            if (len != -1) {
                k += len;
                if (k < data.length) {
                    dos.write(data[k]);
                    k++;
                    dis.skip(1);
                }
            }
        }

        // Get the output and the "correct" digest values
        byte[] output = mdCommon.digest();
        byte[] standard = md.digest(data);

        // Compare generated digest values
        return MessageDigest.isEqual(output, standard);
    } catch (Exception ex) {
        out.println("TestMDShare failed at:" + algo + "/" + dataLength
                + " with unexpected exception");
        throw ex;
    }
}
 
Example #25
Source File: Util.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Compute the "method hash" of a remote method.  The method hash
 * is a long containing the first 64 bits of the SHA digest from
 * the UTF encoded string of the method name and descriptor.
 */
public static long computeMethodHash(Method m) {
    long hash = 0;
    ByteArrayOutputStream sink = new ByteArrayOutputStream(127);
    try {
        MessageDigest md = MessageDigest.getInstance("SHA");
        DataOutputStream out = new DataOutputStream(
            new DigestOutputStream(sink, md));

        String s = getMethodNameAndDescriptor(m);
        if (serverRefLog.isLoggable(Log.VERBOSE)) {
            serverRefLog.log(Log.VERBOSE,
                "string used for method hash: \"" + s + "\"");
        }
        out.writeUTF(s);

        // use only the first 64 bits of the digest for the hash
        out.flush();
        byte hasharray[] = md.digest();
        for (int i = 0; i < Math.min(8, hasharray.length); i++) {
            hash += ((long) (hasharray[i] & 0xFF)) << (i * 8);
        }
    } catch (IOException ignore) {
        /* can't happen, but be deterministic anyway. */
        hash = -1;
    } catch (NoSuchAlgorithmException complain) {
        throw new SecurityException(complain.getMessage());
    }
    return hash;
}
 
Example #26
Source File: ZipSigner.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Write the signature file to the given output stream.
 */
private void generateSignatureFile(Manifest manifest, OutputStream out)
        throws IOException, GeneralSecurityException {
    out.write(("Signature-Version: 1.0\r\n").getBytes());
    out.write(("Created-By: 1.0 (Android SignApk)\r\n").getBytes());


    // BASE64Encoder base64 = new BASE64Encoder();
    MessageDigest md = MessageDigest.getInstance("SHA1");
    PrintStream print = new PrintStream(
            new DigestOutputStream(new ByteArrayOutputStream(), md),
            true, "UTF-8");

    // Digest of the entire manifest
    manifest.write(print);
    print.flush();

    out.write(("SHA1-Digest-Manifest: " + Base64.encode(md.digest()) + "\r\n\r\n").getBytes());

    Map<String, Attributes> entries = manifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
        if (canceled) break;
        progressHelper.progress(ProgressEvent.PRORITY_NORMAL, resourceAdapter.getString(ResourceAdapter.Item.GENERATING_SIGNATURE_FILE));
        // Digest of the manifest stanza for this entry.
        String nameEntry = "Name: " + entry.getKey() + "\r\n";
        print.print(nameEntry);
        for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
            print.print(att.getKey() + ": " + att.getValue() + "\r\n");
        }
        print.print("\r\n");
        print.flush();

        out.write(nameEntry.getBytes());
        out.write(("SHA1-Digest: " + Base64.encode(md.digest()) + "\r\n\r\n").getBytes());
    }

}
 
Example #27
Source File: TestDigestIOStream.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test DigestInputStream and DigestOutputStream digest function when use
 * same message digest object.
 *
 * @param algo
 *            Message Digest algorithm
 * @param dataLength
 *            plain test data length.
 * @exception Exception
 *                throw unexpected exception
 */
public boolean testMDShare(String algo, int dataLength) throws Exception {
    MessageDigest mdCommon = MessageDigest.getInstance(algo);
    // Generate the DigestInputStream/DigestOutputStream object
    try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
            DigestInputStream dis = new DigestInputStream(bais, mdCommon);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DigestOutputStream dos = new DigestOutputStream(baos, mdCommon);) {

        // Perform the update using all available/possible update methods
        int k = 0;
        byte[] buffer = new byte[10];

        // use both read() and read(byte[], int, int)
        while (k < data.length) {
            int len = dis.read(buffer, 0, buffer.length);
            if (len != -1) {
                k += len;
                if (k < data.length) {
                    dos.write(data[k]);
                    k++;
                    dis.skip(1);
                }
            }
        }

        // Get the output and the "correct" digest values
        byte[] output = mdCommon.digest();
        byte[] standard = md.digest(data);

        // Compare generated digest values
        return MessageDigest.isEqual(output, standard);
    } catch (Exception ex) {
        out.println("TestMDShare failed at:" + algo + "/" + dataLength
                + " with unexpected exception");
        throw ex;
    }
}
 
Example #28
Source File: Util.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Compute the "method hash" of a remote method.  The method hash
 * is a long containing the first 64 bits of the SHA digest from
 * the UTF encoded string of the method name and descriptor.
 */
public static long computeMethodHash(Method m) {
    long hash = 0;
    ByteArrayOutputStream sink = new ByteArrayOutputStream(127);
    try {
        MessageDigest md = MessageDigest.getInstance("SHA");
        DataOutputStream out = new DataOutputStream(
            new DigestOutputStream(sink, md));

        String s = getMethodNameAndDescriptor(m);
        if (serverRefLog.isLoggable(Log.VERBOSE)) {
            serverRefLog.log(Log.VERBOSE,
                "string used for method hash: \"" + s + "\"");
        }
        out.writeUTF(s);

        // use only the first 64 bits of the digest for the hash
        out.flush();
        byte hasharray[] = md.digest();
        for (int i = 0; i < Math.min(8, hasharray.length); i++) {
            hash += ((long) (hasharray[i] & 0xFF)) << (i * 8);
        }
    } catch (IOException ignore) {
        /* can't happen, but be deterministic anyway. */
        hash = -1;
    } catch (NoSuchAlgorithmException complain) {
        throw new SecurityException(complain.getMessage());
    }
    return hash;
}
 
Example #29
Source File: DigestOutputStreamTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test #3 for <code>write(byte[],int,int)</code> method<br>
 *
 * Assertion: put bytes into output stream<br>
 *
 * Assertion: updates associated digest<br>
 */
public final void test_write$BII_3()
    throws NoSuchAlgorithmException,
           IOException {
    // check precondition
    assertTrue(MY_MESSAGE_LEN % (CHUNK_SIZE+1) != 0);

    for (int k=0; k<algorithmName.length; k++) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(MY_MESSAGE_LEN);
            MessageDigest md = MessageDigest.getInstance(algorithmName[k]);
            DigestOutputStream dos = new DigestOutputStream(bos, md);

            // write message by chunks
            for (int i=0; i<MY_MESSAGE_LEN/(CHUNK_SIZE+1); i++) {
                dos.write(myMessage, i*(CHUNK_SIZE+1), CHUNK_SIZE+1);
            }
            // write remaining bytes
            dos.write(myMessage,
                    MY_MESSAGE_LEN/(CHUNK_SIZE+1)*(CHUNK_SIZE+1),
                    MY_MESSAGE_LEN % (CHUNK_SIZE+1));
            // check write
            assertTrue("write", Arrays.equals(myMessage, bos.toByteArray()));
            // check that associated digest has been updated properly
            assertTrue("update", Arrays.equals(dos.getMessageDigest().digest(),
                    MDGoldenData.getDigest(algorithmName[k])));
            return;
        } catch (NoSuchAlgorithmException e) {
            // allowed failure
        }
    }
    fail(getName() + ": no MessageDigest algorithms available - test not performed");
}
 
Example #30
Source File: ContentMD5Writer.java    From resteasy-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException
{
   MessageDigest digest = null;
   try
   {
      digest = MessageDigest.getInstance("MD5");
   }
   catch (NoSuchAlgorithmException e)
   {
      throw new IllegalArgumentException(e);
   }
   ByteArrayOutputStream buffer = new ByteArrayOutputStream();
   DigestOutputStream digestStream = new DigestOutputStream(buffer, digest);
   OutputStream old = context.getOutputStream();
   context.setOutputStream(digestStream);

   try
   {
      context.proceed();

      byte[] hash = digest.digest();
      String encodedHash = Base64.getEncoder().encodeToString(hash);
      context.getHeaders().putSingle("Content-MD5", encodedHash);

      byte[] content = buffer.toByteArray();
      old.write(content);
   }
   finally
   {
      context.setOutputStream(old);
   }
}