Search in sources :

Example 86 with DigestInputStream

use of java.security.DigestInputStream in project sagacity-sqltoy by chenrenfei.

the class FileUtil method getFileMessageDigest.

/**
 * @todo 获取文件的摘要,一般应用于检查文件是否被修改过(如在网络传输过程中,下载后取其摘要进行对比)
 * @param fileName
 * @param digestType :like MD5
 * @return
 */
public static String getFileMessageDigest(String fileName, String digestType) {
    String result = "";
    FileInputStream fin = null;
    DigestInputStream din = null;
    try {
        MessageDigest md = MessageDigest.getInstance(digestType);
        fin = new FileInputStream(fileName);
        if (fin.available() == 0) {
            return "";
        }
        // 构造输入流
        din = new DigestInputStream(fin, md);
        while ((din.read()) != -1) {
            ;
        }
        // 获得消息摘要
        byte[] re = md.digest();
        for (int i = 0; i < re.length; i++) {
            result += Integer.toHexString((0x000000ff & re[i]) | 0xffffff00).substring(6);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtil.closeQuietly(din, fin);
    }
    return result;
}
Also used : DigestInputStream(java.security.DigestInputStream) MessageDigest(java.security.MessageDigest) FileInputStream(java.io.FileInputStream) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 87 with DigestInputStream

use of java.security.DigestInputStream in project AmazeFileManager by TeamAmaze.

the class GenericCopyUtilTest method assertSha1Equals.

private void assertSha1Equals(byte[] expected, File file) throws NoSuchAlgorithmException, IOException {
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    DigestInputStream in = new DigestInputStream(new FileInputStream(file), md);
    byte[] buffer = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
    while (in.read(buffer) > -1) {
    }
    in.close();
    assertArrayEquals(expected, md.digest());
}
Also used : DigestInputStream(java.security.DigestInputStream) MessageDigest(java.security.MessageDigest) FileInputStream(java.io.FileInputStream)

Example 88 with DigestInputStream

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

the class ShowSignature method showSignature.

private void showSignature(String[] args) throws IOException, GeneralSecurityException, TSPException, CertificateVerificationException {
    if (args.length != 2) {
        usage();
    } else {
        String password = args[0];
        File infile = new File(args[1]);
        // use old-style document loading to disable leniency
        // see also https://www.pdf-insecurity.org/
        RandomAccessReadBufferedFile raFile = new RandomAccessReadBufferedFile(infile);
        // If your files are not too large, you can also download the PDF into a byte array
        // with IOUtils.toByteArray() and pass a RandomAccessBuffer() object to the
        // PDFParser constructor.
        PDFParser parser = new PDFParser(raFile, password);
        try (PDDocument document = parser.parse(false)) {
            for (PDSignature sig : document.getSignatureDictionaries()) {
                COSDictionary sigDict = sig.getCOSObject();
                byte[] contents = sig.getContents();
                // we're doing this as a stream, to be able to handle huge files
                try (FileInputStream fis = new FileInputStream(infile);
                    InputStream signedContentAsStream = new COSFilterInputStream(fis, sig.getByteRange())) {
                    System.out.println("Signature found");
                    if (sig.getName() != null) {
                        System.out.println("Name:     " + sig.getName());
                    }
                    if (sig.getSignDate() != null) {
                        System.out.println("Modified: " + sdf.format(sig.getSignDate().getTime()));
                    }
                    String subFilter = sig.getSubFilter();
                    if (subFilter != null) {
                        switch(subFilter) {
                            case "adbe.pkcs7.detached":
                            case "ETSI.CAdES.detached":
                                verifyPKCS7(signedContentAsStream, contents, sig);
                                break;
                            case "adbe.pkcs7.sha1":
                                {
                                    // example: PDFBOX-1452.pdf
                                    CertificateFactory factory = CertificateFactory.getInstance("X.509");
                                    ByteArrayInputStream certStream = new ByteArrayInputStream(contents);
                                    Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
                                    System.out.println("certs=" + certs);
                                    @SuppressWarnings({ "squid:S5542", "lgtm [java/weak-cryptographic-algorithm]" }) MessageDigest md = MessageDigest.getInstance("SHA1");
                                    try (DigestInputStream dis = new DigestInputStream(signedContentAsStream, md)) {
                                        while (dis.read() != -1) {
                                        // do nothing
                                        }
                                    }
                                    byte[] hash = md.digest();
                                    verifyPKCS7(new ByteArrayInputStream(hash), contents, sig);
                                    break;
                                }
                            case "adbe.x509.rsa_sha1":
                                {
                                    // example: PDFBOX-2693.pdf
                                    COSString certString = (COSString) sigDict.getDictionaryObject(COSName.CERT);
                                    // TODO this could also be an array.
                                    if (certString == null) {
                                        System.err.println("The /Cert certificate string is missing in the signature dictionary");
                                        return;
                                    }
                                    byte[] certData = certString.getBytes();
                                    CertificateFactory factory = CertificateFactory.getInstance("X.509");
                                    ByteArrayInputStream certStream = new ByteArrayInputStream(certData);
                                    Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
                                    System.out.println("certs=" + certs);
                                    X509Certificate cert = (X509Certificate) certs.iterator().next();
                                    try {
                                        if (sig.getSignDate() != null) {
                                            cert.checkValidity(sig.getSignDate().getTime());
                                            System.out.println("Certificate valid at signing time");
                                        } else {
                                            System.err.println("Certificate cannot be verified without signing time");
                                        }
                                    } catch (CertificateExpiredException ex) {
                                        System.err.println("Certificate expired at signing time");
                                    } catch (CertificateNotYetValidException ex) {
                                        System.err.println("Certificate not yet valid at signing time");
                                    }
                                    if (CertificateVerifier.isSelfSigned(cert)) {
                                        System.err.println("Certificate is self-signed, LOL!");
                                    } else {
                                        System.out.println("Certificate is not self-signed");
                                        if (sig.getSignDate() != null) {
                                            @SuppressWarnings("unchecked") Store<X509CertificateHolder> store = new JcaCertStore(certs);
                                            SigUtils.verifyCertificateChain(store, cert, sig.getSignDate().getTime());
                                        }
                                    }
                                    break;
                                }
                            case "ETSI.RFC3161":
                                // e.g. PDFBOX-1848, file_timestamped.pdf
                                verifyETSIdotRFC3161(signedContentAsStream, contents);
                                // verifyPKCS7(hash, contents, sig) does not work
                                break;
                            default:
                                System.err.println("Unknown certificate type: " + subFilter);
                                break;
                        }
                    } else {
                        throw new IOException("Missing subfilter for cert dictionary");
                    }
                    int[] byteRange = sig.getByteRange();
                    if (byteRange.length != 4) {
                        System.err.println("Signature byteRange must have 4 items");
                    } else {
                        long fileLen = infile.length();
                        long rangeMax = byteRange[2] + (long) byteRange[3];
                        // multiply content length with 2 (because it is in hex in the PDF) and add 2 for < and >
                        int contentLen = contents.length * 2 + 2;
                        if (fileLen != rangeMax || byteRange[0] != 0 || byteRange[1] + contentLen != byteRange[2]) {
                            // a false result doesn't necessarily mean that the PDF is a fake
                            // see this answer why:
                            // https://stackoverflow.com/a/48185913/535646
                            System.out.println("Signature does not cover whole document");
                        } else {
                            System.out.println("Signature covers whole document");
                        }
                        checkContentValueWithFile(infile, byteRange, contents);
                    }
                }
            }
            analyseDSS(document);
        } catch (CMSException | OperatorCreationException ex) {
            throw new IOException(ex);
        }
        System.out.println("Analyzed: " + args[1]);
    }
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) CollectionStore(org.bouncycastle.util.CollectionStore) KeyStore(java.security.KeyStore) Store(org.bouncycastle.util.Store) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) COSString(org.apache.pdfbox.cos.COSString) PDSignature(org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature) CertificateFactory(java.security.cert.CertificateFactory) RandomAccessReadBufferedFile(org.apache.pdfbox.io.RandomAccessReadBufferedFile) MessageDigest(java.security.MessageDigest) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) COSString(org.apache.pdfbox.cos.COSString) COSDictionary(org.apache.pdfbox.cos.COSDictionary) DigestInputStream(java.security.DigestInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) COSFilterInputStream(org.apache.pdfbox.pdmodel.interactive.digitalsignature.COSFilterInputStream) FileInputStream(java.io.FileInputStream) DigestInputStream(java.security.DigestInputStream) InputStream(java.io.InputStream) PDFParser(org.apache.pdfbox.pdfparser.PDFParser) COSFilterInputStream(org.apache.pdfbox.pdmodel.interactive.digitalsignature.COSFilterInputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) PDDocument(org.apache.pdfbox.pdmodel.PDDocument) Collection(java.util.Collection) RandomAccessReadBufferedFile(org.apache.pdfbox.io.RandomAccessReadBufferedFile) File(java.io.File) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) CMSException(org.bouncycastle.cms.CMSException)

Example 89 with DigestInputStream

use of java.security.DigestInputStream in project graal by oracle.

the class ServiceWatcher method calculateChecksum.

private static byte[] calculateChecksum(Path resourcePath) {
    try {
        byte[] buffer = new byte[4096];
        MessageDigest md = MessageDigest.getInstance("MD5");
        try (InputStream is = Files.newInputStream(resourcePath);
            DigestInputStream dis = new DigestInputStream(is, md)) {
            // read through the entire stream which updates the message digest underneath
            while (dis.read(buffer) != -1) {
                dis.read();
            }
        }
        return md.digest();
    } catch (Exception e) {
        // Checkstyle: stop warning message from guest code
        System.err.println("[HotSwap API]: unable to calculate checksum for watched resource " + resourcePath);
    // Checkstyle: resume warning message from guest code
    }
    return EMPTY_BYTE_ARRAY;
}
Also used : DigestInputStream(java.security.DigestInputStream) DigestInputStream(java.security.DigestInputStream) InputStream(java.io.InputStream) MessageDigest(java.security.MessageDigest) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException)

Example 90 with DigestInputStream

use of java.security.DigestInputStream in project UltimateAndroid by cymcsg.

the class MD5Utils method fileMD5.

public static String fileMD5(String inputFile) throws IOException {
    // 缓冲区大小(这个可以抽出一个参数)
    int bufferSize = 256 * 1024;
    FileInputStream fileInputStream = null;
    DigestInputStream digestInputStream = null;
    try {
        // 拿到一个MD5转换器(同样,这里可以换成SHA1)
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        // 使用DigestInputStream
        fileInputStream = new FileInputStream(inputFile);
        //  Base64InputStream base64InputStream=new Base64InputStream(fileInputStream,0);
        digestInputStream = new DigestInputStream(fileInputStream, messageDigest);
        // read的过程中进行MD5处理,直到读完文件
        byte[] buffer = new byte[bufferSize];
        while (digestInputStream.read(buffer) > 0) ;
        // 获取最终的MessageDigest
        messageDigest = digestInputStream.getMessageDigest();
        // 拿到结果,也是字节数组,包含16个元素
        byte[] resultByteArray = messageDigest.digest();
        // 同样,把字节数组转换成字符串
        return byteArrayToHex(resultByteArray);
    } catch (NoSuchAlgorithmException e) {
        return null;
    } finally {
        try {
            digestInputStream.close();
        } catch (Exception e) {
        }
        try {
            fileInputStream.close();
        } catch (Exception e) {
        }
    }
}
Also used : DigestInputStream(java.security.DigestInputStream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

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