Search in sources :

Example 81 with DigestInputStream

use of java.security.DigestInputStream in project box-java-sdk by box.

the class BoxFileIT method uploadParts.

private MessageDigest uploadParts(BoxFileUploadSession.Info session, long fileSize, File file) throws Exception {
    FileInputStream stream = new FileInputStream(file);
    MessageDigest fileDigest = MessageDigest.getInstance("SHA1");
    DigestInputStream dis = new DigestInputStream(stream, fileDigest);
    long offset = 0;
    long processed = 0;
    boolean canBreak = false;
    do {
        long min = session.getPartSize();
        long diff = fileSize - processed;
        if (diff < min) {
            min = diff;
            canBreak = true;
        }
        BoxFileUploadSessionPart part = session.getResource().uploadPart(dis, offset, (int) min, fileSize);
        assertNotNull(part.getSha1());
        assertNotNull(part.getPartId());
        assertEquals(part.getOffset(), offset);
        assertTrue(part.getSize() <= session.getPartSize());
        offset = offset + session.getPartSize();
        processed += min;
    } while (!canBreak);
    return fileDigest;
}
Also used : DigestInputStream(java.security.DigestInputStream) MessageDigest(java.security.MessageDigest) FileInputStream(java.io.FileInputStream)

Example 82 with DigestInputStream

use of java.security.DigestInputStream in project ranger by apache.

the class RangerKeyStore method engineLoad.

@Override
public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
    if (logger.isDebugEnabled()) {
        logger.debug("==> RangerKeyStore.engineLoad()");
    }
    synchronized (keyEntries) {
        List<XXRangerKeyStore> rangerKeyDetails = dbOperationLoad();
        if (rangerKeyDetails == null || rangerKeyDetails.size() < 1) {
            if (logger.isDebugEnabled()) {
                logger.debug("RangerKeyStore might be null or key is not present in the database.");
            }
            return;
        }
        keyEntries.clear();
        if (keyVaultEnabled) {
            for (XXRangerKeyStore rangerKey : rangerKeyDetails) {
                String encodedStr = rangerKey.getEncoded();
                byte[] encodedByte = DatatypeConverter.parseBase64Binary(encodedStr);
                String alias;
                SecretKeyByteEntry entry = new SecretKeyByteEntry();
                alias = rangerKey.getAlias();
                entry.date = new Date(rangerKey.getCreatedDate());
                entry.cipher_field = rangerKey.getCipher();
                entry.bit_length = rangerKey.getBitLength();
                entry.description = rangerKey.getDescription();
                entry.version = rangerKey.getVersion();
                entry.attributes = rangerKey.getAttributes();
                entry.key = encodedByte;
                keyEntries.put(alias, entry);
            }
        } else {
            DataInputStream dis;
            MessageDigest md = null;
            if (password != null) {
                md = getKeyedMessageDigest(password);
            }
            byte[] computed = {};
            if (md != null) {
                computed = md.digest();
            }
            for (XXRangerKeyStore rangerKey : rangerKeyDetails) {
                String encoded = rangerKey.getEncoded();
                byte[] data = DatatypeConverter.parseBase64Binary(encoded);
                if (data != null && data.length > 0) {
                    stream = new ByteArrayInputStream(data);
                } else {
                    logger.error("No Key found for alias " + rangerKey.getAlias());
                }
                if (computed != null) {
                    int counter = 0;
                    for (int i = computed.length - 1; i >= 0; i--) {
                        if (computed[i] != data[data.length - (1 + counter)]) {
                            Throwable t = new UnrecoverableKeyException("Password verification failed");
                            logger.error("Keystore was tampered with, or password was incorrect.", t);
                            throw (IOException) new IOException("Keystore was tampered with, or " + "password was incorrect").initCause(t);
                        } else {
                            counter++;
                        }
                    }
                }
                if (password != null) {
                    dis = new DataInputStream(new DigestInputStream(stream, md));
                } else {
                    dis = new DataInputStream(stream);
                }
                ObjectInputStream ois = null;
                try {
                    String alias;
                    SecretKeyEntry entry = new SecretKeyEntry();
                    // read the alias
                    alias = rangerKey.getAlias();
                    // read the (entry creation) date
                    entry.date = new Date(rangerKey.getCreatedDate());
                    entry.cipher_field = rangerKey.getCipher();
                    entry.bit_length = rangerKey.getBitLength();
                    entry.description = rangerKey.getDescription();
                    entry.version = rangerKey.getVersion();
                    entry.attributes = rangerKey.getAttributes();
                    // read the sealed key
                    try {
                        ois = new ObjectInputStream(dis);
                        entry.sealedKey = (SealedObject) ois.readObject();
                    } catch (ClassNotFoundException cnfe) {
                        throw new IOException(cnfe.getMessage());
                    }
                    // Add the entry to the list
                    keyEntries.put(alias, entry);
                } finally {
                    if (ois != null) {
                        ois.close();
                    } else {
                        dis.close();
                    }
                }
            }
        }
    }
}
Also used : DigestInputStream(java.security.DigestInputStream) XXRangerKeyStore(org.apache.ranger.entity.XXRangerKeyStore) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream) Date(java.util.Date) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ByteArrayInputStream(java.io.ByteArrayInputStream) MessageDigest(java.security.MessageDigest) ObjectInputStream(java.io.ObjectInputStream)

Example 83 with DigestInputStream

use of java.security.DigestInputStream in project fdroidclient by f-droid.

the class JKS method engineLoad.

public void engineLoad(InputStream in, char[] passwd) throws IOException, NoSuchAlgorithmException, CertificateException {
    MessageDigest md = MessageDigest.getInstance("SHA");
    if (passwd != null)
        md.update(charsToBytes(passwd));
    // HAR HAR
    md.update("Mighty Aphrodite".getBytes("UTF-8"));
    aliases.clear();
    trustedCerts.clear();
    privateKeys.clear();
    certChains.clear();
    dates.clear();
    if (in == null)
        return;
    DataInputStream din = new DataInputStream(new DigestInputStream(in, md));
    if (din.readInt() != MAGIC)
        throw new IOException("not a JavaKeyStore");
    // version no.
    din.readInt();
    final int n = din.readInt();
    aliases.ensureCapacity(n);
    if (n < 0)
        throw new LoadKeystoreException("Malformed key store");
    for (int i = 0; i < n; i++) {
        int type = din.readInt();
        String alias = din.readUTF();
        aliases.add(alias);
        dates.put(alias, new Date(din.readLong()));
        switch(type) {
            case PRIVATE_KEY:
                int len = din.readInt();
                byte[] encoded = new byte[len];
                din.read(encoded);
                privateKeys.put(alias, encoded);
                int count = din.readInt();
                Certificate[] chain = new Certificate[count];
                for (int j = 0; j < count; j++) chain[j] = readCert(din);
                certChains.put(alias, chain);
                break;
            case TRUSTED_CERT:
                trustedCerts.put(alias, readCert(din));
                break;
            default:
                throw new LoadKeystoreException("Malformed key store");
        }
    }
    if (passwd != null) {
        byte[] computedHash = md.digest();
        byte[] storedHash = new byte[20];
        din.read(storedHash);
        if (!MessageDigest.isEqual(storedHash, computedHash)) {
            throw new LoadKeystoreException("Incorrect password, or integrity check failed.");
        }
    }
}
Also used : DigestInputStream(java.security.DigestInputStream) IOException(java.io.IOException) MessageDigest(java.security.MessageDigest) DataInputStream(java.io.DataInputStream) Date(java.util.Date) Certificate(java.security.cert.Certificate)

Example 84 with DigestInputStream

use of java.security.DigestInputStream in project smarthome by eclipse.

the class FirmwareImpl method getBytes.

@Override
public synchronized byte @Nullable [] getBytes() {
    if (inputStream == null) {
        return null;
    }
    if (bytes == null) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            try (DigestInputStream dis = new DigestInputStream(inputStream, md)) {
                bytes = IOUtils.toByteArray(dis);
            } catch (IOException ioEx) {
                logger.error("Cannot read firmware {}.", this, ioEx);
                return null;
            }
            byte[] digest = md.digest();
            if (md5Hash != null && digest != null) {
                StringBuilder digestString = new StringBuilder();
                for (byte b : digest) {
                    digestString.append(String.format("%02x", b));
                }
                if (!md5Hash.equals(digestString.toString())) {
                    bytes = null;
                    throw new IllegalStateException(String.format("Invalid MD5 checksum. Expected %s, but was %s.", md5Hash, digestString));
                }
            }
        } catch (NoSuchAlgorithmException e) {
            logger.error("Cannot calculate MD5 checksum.", e);
            bytes = null;
            return null;
        }
    }
    return bytes;
}
Also used : DigestInputStream(java.security.DigestInputStream) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

Example 85 with DigestInputStream

use of java.security.DigestInputStream in project openj9 by eclipse.

the class J9DDRStructureStore method digestStructure.

private String digestStructure(String structureFileName) throws IOException {
    MessageDigest md = null;
    byte[] buffer = new byte[1024];
    try {
        md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        // This only happens if the JRE configuration is really messed up.
        throw new IllegalStateException(e.getMessage());
    }
    DigestInputStream dis = null;
    FileInputStream structure = new FileInputStream(structureFileName);
    dis = new DigestInputStream(structure, md);
    ByteArrayOutputStream structureStream = new ByteArrayOutputStream();
    try {
        while (true) {
            int bytesRead = dis.read(buffer);
            if (bytesRead == -1) {
                break;
            }
            structureStream.write(buffer, 0, bytesRead);
        }
        dis.close();
    } finally {
        structure.close();
    }
    structureBytes = structureStream.toByteArray();
    if ((structureBytes.length > 2) && (structureBytes[0] == SUPERSET_ID_EBCDIC[0]) && (structureBytes[1] == SUPERSET_ID_EBCDIC[1])) {
        convertFromEBCDIC();
    }
    byte[] digestBytes = dis.getMessageDigest().digest();
    return byteArrayHexString(digestBytes);
}
Also used : DigestInputStream(java.security.DigestInputStream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MessageDigest(java.security.MessageDigest) FileInputStream(java.io.FileInputStream)

Aggregations

DigestInputStream (java.security.DigestInputStream)179 MessageDigest (java.security.MessageDigest)138 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)84 IOException (java.io.IOException)74 InputStream (java.io.InputStream)57 FileInputStream (java.io.FileInputStream)41 ByteArrayInputStream (java.io.ByteArrayInputStream)40 File (java.io.File)21 BufferedInputStream (java.io.BufferedInputStream)13 ByteArrayOutputStream (java.io.ByteArrayOutputStream)9 FileOutputStream (java.io.FileOutputStream)8 URL (java.net.URL)8 OutputStream (java.io.OutputStream)7 FileNotFoundException (java.io.FileNotFoundException)5 BigInteger (java.math.BigInteger)5 DigestOutputStream (java.security.DigestOutputStream)5 HashMap (java.util.HashMap)5 Path (java.nio.file.Path)4 CertificateFactory (java.security.cert.CertificateFactory)4 Formatter (java.util.Formatter)4