Search in sources :

Example 36 with DigestOutputStream

use of java.security.DigestOutputStream in project i2p.i2p by i2p.

the class SU3File method write.

/**
 *  One-pass wrap and sign the content.
 *  Writes to the file specified in the constructor.
 *  Throws on all errors.
 *
 *  @param content the input file, probably in zip format
 *  @param fileType 0-255, 0 for zip
 *  @param contentType 0-255
 *  @param version 1-255 bytes when converted to UTF-8
 *  @param signer ID of the public key, 1-255 bytes when converted to UTF-8
 */
public void write(File content, int fileType, int contentType, String version, String signer, PrivateKey privkey, SigType sigType) throws IOException {
    InputStream in = null;
    DigestOutputStream out = null;
    boolean ok = false;
    try {
        in = new BufferedInputStream(new FileInputStream(content));
        MessageDigest md = sigType.getDigestInstance();
        out = new DigestOutputStream(new BufferedOutputStream(new FileOutputStream(_file)), md);
        out.write(MAGIC_BYTES);
        out.write((byte) 0);
        out.write((byte) FILE_VERSION);
        DataHelper.writeLong(out, 2, sigType.getCode());
        DataHelper.writeLong(out, 2, sigType.getSigLen());
        out.write((byte) 0);
        byte[] verBytes = DataHelper.getUTF8(version);
        if (verBytes.length == 0 || verBytes.length > 255)
            throw new IllegalArgumentException("bad version length");
        int verLen = Math.max(verBytes.length, MIN_VERSION_BYTES);
        out.write((byte) verLen);
        out.write((byte) 0);
        byte[] signerBytes = DataHelper.getUTF8(signer);
        if (signerBytes.length == 0 || signerBytes.length > 255)
            throw new IllegalArgumentException("bad signer length");
        out.write((byte) signerBytes.length);
        long contentLength = content.length();
        if (contentLength <= 0)
            throw new IllegalArgumentException("No content");
        DataHelper.writeLong(out, 8, contentLength);
        out.write((byte) 0);
        if (fileType < 0 || fileType > 255)
            throw new IllegalArgumentException("bad content type");
        out.write((byte) fileType);
        out.write((byte) 0);
        if (contentType < 0 || contentType > 255)
            throw new IllegalArgumentException("bad content type");
        out.write((byte) contentType);
        out.write(new byte[12]);
        out.write(verBytes);
        if (verBytes.length < MIN_VERSION_BYTES)
            out.write(new byte[MIN_VERSION_BYTES - verBytes.length]);
        out.write(signerBytes);
        byte[] buf = new byte[16 * 1024];
        long tot = 0;
        while (tot < contentLength) {
            int read = in.read(buf, 0, (int) Math.min(buf.length, contentLength - tot));
            if (read < 0)
                throw new EOFException();
            out.write(buf, 0, read);
            tot += read;
        }
        byte[] sha = md.digest();
        out.on(false);
        SimpleDataStructure hash = sigType.getHashInstance();
        hash.setData(sha);
        Signature signature = _context.dsa().sign(hash, privkey, sigType);
        if (signature == null)
            throw new IOException("sig fail");
        // System.out.println("hash\n" + HexDump.dump(sha));
        // System.out.println("sig\n" + HexDump.dump(signature.getData()));
        signature.writeBytes(out);
        ok = true;
    } catch (DataFormatException dfe) {
        IOException ioe = new IOException("foo");
        ioe.initCause(dfe);
        throw ioe;
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException ioe) {
            }
        if (out != null)
            try {
                out.close();
            } catch (IOException ioe) {
            }
        if (!ok)
            _file.delete();
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) DigestInputStream(java.security.DigestInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) DataFormatException(net.i2p.data.DataFormatException) BufferedInputStream(java.io.BufferedInputStream) DigestOutputStream(java.security.DigestOutputStream) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) FileOutputStream(java.io.FileOutputStream) Signature(net.i2p.data.Signature) EOFException(java.io.EOFException) MessageDigest(java.security.MessageDigest) BufferedOutputStream(java.io.BufferedOutputStream) SimpleDataStructure(net.i2p.data.SimpleDataStructure)

Example 37 with DigestOutputStream

use of java.security.DigestOutputStream in project tycho by eclipse.

the class ProbeOutputStream method md5AsHex.

public String md5AsHex() throws IOException {
    final DigestOutputStream digestStream = createMd5DigestStream();
    writeBufferedContent(digestStream);
    return formatDigestAsPaddedHex(digestStream, MD5_SUM_ZEROS);
}
Also used : DigestOutputStream(java.security.DigestOutputStream)

Example 38 with DigestOutputStream

use of java.security.DigestOutputStream in project Essentials by EssentialsX.

the class ManagedFile method copyResourceAscii.

public static void copyResourceAscii(final String resourceName, final File file) throws IOException {
    final InputStreamReader reader = new InputStreamReader(ManagedFile.class.getResourceAsStream(resourceName));
    try {
        final MessageDigest digest = getDigest();
        final DigestOutputStream digestStream = new DigestOutputStream(new FileOutputStream(file), digest);
        try {
            final OutputStreamWriter writer = new OutputStreamWriter(digestStream);
            try {
                final char[] buffer = new char[BUFFERSIZE];
                do {
                    final int length = reader.read(buffer);
                    if (length >= 0) {
                        writer.write(buffer, 0, length);
                    } else {
                        break;
                    }
                } while (true);
                writer.write("\n");
                writer.flush();
                final BigInteger hashInt = new BigInteger(1, digest.digest());
                digestStream.on(false);
                digestStream.write('#');
                digestStream.write(hashInt.toString(16).getBytes());
            } finally {
                writer.close();
            }
        } finally {
            digestStream.close();
        }
    } finally {
        reader.close();
    }
}
Also used : DigestOutputStream(java.security.DigestOutputStream) BigInteger(java.math.BigInteger) MessageDigest(java.security.MessageDigest)

Example 39 with DigestOutputStream

use of java.security.DigestOutputStream in project wildfly-swarm by wildfly-swarm.

the class SwarmContentRepository method addContent.

@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);
    }
}
Also used : Path(java.nio.file.Path) BufferedInputStream(java.io.BufferedInputStream) DigestOutputStream(java.security.DigestOutputStream) OutputStream(java.io.OutputStream) DigestOutputStream(java.security.DigestOutputStream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) MessageDigest(java.security.MessageDigest)

Example 40 with DigestOutputStream

use of java.security.DigestOutputStream in project ovirt-engine by oVirt.

the class SSHClient method receiveFile.

/**
 * Receive file using compression and localDigest check.
 *
 * We read the stream and pipe into gunzip, and write into the file. Calculating the remoteDigest on the fly.
 *
 * The localDigest is printed into stderr for us to collect.
 *
 * @param file1
 *            source.
 * @param file2
 *            destination.
 */
public void receiveFile(String file1, String file2) throws Exception {
    log.debug("Receiving: '{}' '{}'", file1, file2);
    remoteFileName(file1);
    MessageDigest localDigest = MessageDigest.getInstance("MD5");
    // stdout->pout->pin->in->out->digest->{}->file2
    Thread t = null;
    try (final PipedOutputStream pout = new PipedOutputStream();
        final InputStream pin = new PipedInputStream(pout, STREAM_BUFFER_SIZE);
        final OutputStream out = new DigestOutputStream(new FileOutputStream(file2), localDigest);
        final InputStream empty = new ByteArrayInputStream(new byte[0]);
        final ByteArrayOutputStream remoteDigest = new ConstraintByteArrayOutputStream(CONSTRAINT_BUFFER_SIZE)) {
        t = new Thread(() -> {
            try (final InputStream in = new GZIPInputStream(pin)) {
                byte[] b = new byte[STREAM_BUFFER_SIZE];
                int n;
                while ((n = in.read(b)) != -1) {
                    out.write(b, 0, n);
                }
            } catch (IOException e) {
                log.debug("Exceution during stream processing", e);
            }
        }, "SSHClient.decompress " + file2);
        t.start();
        executeCommand(String.format(COMMAND_FILE_RECEIVE, "gzip -q", file1), empty, pout, remoteDigest);
        t.join(THREAD_JOIN_WAIT_TIME);
        if (t.getState() != Thread.State.TERMINATED) {
            throw new IllegalStateException("Cannot stop SSH stream thread");
        }
        validateDigest(localDigest, new String(remoteDigest.toByteArray(), StandardCharsets.UTF_8).trim());
    } catch (Exception e) {
        log.debug("Receive failed", e);
        throw e;
    } finally {
        if (t != null) {
            t.interrupt();
        }
    }
    log.debug("Received: '{}' '{}'", file1, file2);
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) PipedInputStream(java.io.PipedInputStream) FileInputStream(java.io.FileInputStream) DigestInputStream(java.security.DigestInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) PipedOutputStream(java.io.PipedOutputStream) DigestOutputStream(java.security.DigestOutputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream) PipedOutputStream(java.io.PipedOutputStream) PipedInputStream(java.io.PipedInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) AuthenticationException(javax.naming.AuthenticationException) DecoderException(org.apache.commons.codec.DecoderException) IOException(java.io.IOException) TimeLimitExceededException(javax.naming.TimeLimitExceededException) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) DigestOutputStream(java.security.DigestOutputStream) FileOutputStream(java.io.FileOutputStream) MessageDigest(java.security.MessageDigest)

Aggregations

DigestOutputStream (java.security.DigestOutputStream)106 MessageDigest (java.security.MessageDigest)86 ByteArrayOutputStream (java.io.ByteArrayOutputStream)53 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)44 IOException (java.io.IOException)41 OutputStream (java.io.OutputStream)26 FileOutputStream (java.io.FileOutputStream)14 File (java.io.File)13 Support_OutputStream (tests.support.Support_OutputStream)9 NullOutputStream (com.keepassdroid.stream.NullOutputStream)8 BufferedOutputStream (java.io.BufferedOutputStream)8 InputStream (java.io.InputStream)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 Map (java.util.Map)7 NullOutputStream (org.apache.commons.io.output.NullOutputStream)7 Base64OutputStream (android.util.Base64OutputStream)6 DigestInputStream (java.security.DigestInputStream)6 DataOutputStream (java.io.DataOutputStream)5 FileInputStream (java.io.FileInputStream)5 Attributes (java.util.jar.Attributes)5