Search in sources :

Example 1 with CMSException

use of org.bouncycastle.cms.CMSException in project nhin-d by DirectProject.

the class ViewTrustBundlePKCS7 method viewBundle.

@SuppressWarnings({ "rawtypes" })
public boolean viewBundle(File trustDir) {
    try {
        //System.out.println("File:"+trustDir.getName());
        if (!trustDir.getName().endsWith(".p7m")) {
            byte[] trustBundleByte = loadFileData(trustDir);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            CMSSignedData dataParser = new CMSSignedData(trustBundleByte);
            ContentInfo contentInfo = dataParser.getContentInfo();
            SignedData signedData = SignedData.getInstance(contentInfo.getContent());
            Enumeration certificates = signedData.getCertificates().getObjects();
            StringBuffer output = new StringBuffer();
            int counter = 1;
            String chk = "Absent";
            while (certificates.hasMoreElements()) {
                DERObject certObj = (DERObject) certificates.nextElement();
                InputStream in = new ByteArrayInputStream(certObj.getDEREncoded());
                X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
                X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
                RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                output.append("Trust Anchor :" + counter + "\n");
                output.append("Common Name :" + IETFUtils.valueToString(cn.getFirst().getValue()) + "\n");
                output.append("DN :" + cert.getSubjectDN().getName() + "\n\n");
                counter++;
            }
            if (signedData.getEncapContentInfo().getContent() != null) {
                //chk = new String(signedData.getEncapContentInfo().getContent().getDERObject().getEncoded(),"UTF-8");
                chk = new String(signedData.getEncapContentInfo().getContent().getDERObject().getDEREncoded(), "UTF-8");
            }
            output.append("Meta Data :\n" + chk);
            error = output.toString();
        } else //end of if check of file type
        {
            StringBuffer output = new StringBuffer();
            int counter = 1;
            String chk = "Absent";
            byte[] trustBundleByte = loadFileData(trustDir);
            CMSSignedData dataParser = new CMSSignedData(trustBundleByte);
            ContentInfo contentInfo = dataParser.getContentInfo();
            SignedData signedData = SignedData.getInstance(contentInfo.getContent());
            CMSSignedData encapInfoBundle = new CMSSignedData(new CMSProcessableByteArray(signedData.getEncapContentInfo().getContent().getDERObject().getEncoded()), contentInfo);
            SignedData encapMetaData = SignedData.getInstance(encapInfoBundle.getContentInfo().getContent());
            //System.out.println("ENCAP META DATA"+new String(encapMetaData.getEncapContentInfo().getContent().getDERObject().getEncoded(),"UTF-8"));
            CMSProcessableByteArray cin = new CMSProcessableByteArray(((ASN1OctetString) encapMetaData.getEncapContentInfo().getContent()).getOctets());
            CertificateFactory ucf = CertificateFactory.getInstance("X.509");
            CMSSignedData unsignedParser = new CMSSignedData(cin.getInputStream());
            ContentInfo unsginedEncapInfo = unsignedParser.getContentInfo();
            SignedData metaData = SignedData.getInstance(unsginedEncapInfo.getContent());
            Enumeration certificates = metaData.getCertificates().getObjects();
            while (certificates.hasMoreElements()) {
                DERObject certObj = (DERObject) certificates.nextElement();
                InputStream bin = new ByteArrayInputStream(certObj.getDEREncoded());
                X509Certificate cert = (X509Certificate) ucf.generateCertificate(bin);
                X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
                RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                output.append("Trust Anchor :" + counter + "\n");
                output.append("Common Name :" + IETFUtils.valueToString(cn.getFirst().getValue()) + "\n");
                output.append("DN :" + cert.getSubjectDN().getName() + "\n\n");
                counter++;
            }
            if (metaData.getEncapContentInfo().getContent() != null) {
                //chk = new String(signedData.getEncapContentInfo().getContent().getDERObject().getEncoded(),"UTF-8");
                chk = new String(metaData.getEncapContentInfo().getContent().getDERObject().getDEREncoded(), "UTF-8");
            }
            output.append("Meta Data :\n" + chk);
            error = output.toString();
        }
    //end of .p7m check if
    }//end of try
     catch (IOException io) {
        //io.printStackTrace(System.err);
        return false;
    } catch (CMSException cm) {
        //cm.printStackTrace(System.err);
        return false;
    } catch (Exception e) {
        //e.printStackTrace(System.err);
        return false;
    }
    return true;
}
Also used : CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) Enumeration(java.util.Enumeration) SignedData(org.bouncycastle.asn1.cms.SignedData) CMSSignedData(org.bouncycastle.cms.CMSSignedData) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) X500Name(org.bouncycastle.asn1.x500.X500Name) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) CMSSignedData(org.bouncycastle.cms.CMSSignedData) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) X509Certificate(java.security.cert.X509Certificate) CMSException(org.bouncycastle.cms.CMSException) IOException(java.io.IOException) DERObject(org.bouncycastle.asn1.DERObject) EncryptedContentInfo(org.bouncycastle.asn1.cms.EncryptedContentInfo) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) RDN(org.bouncycastle.asn1.x500.RDN) CMSException(org.bouncycastle.cms.CMSException)

Example 2 with CMSException

use of org.bouncycastle.cms.CMSException in project nhin-d by DirectProject.

the class MessageSigInspector method main.

public static void main(String[] args) {
    if (args.length == 0) {
        //printUsage();
        System.exit(-1);
    }
    String messgefile = null;
    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        // Options
        if (!arg.startsWith("-")) {
            System.err.println("Error: Unexpected argument [" + arg + "]\n");
            //printUsage();
            System.exit(-1);
        } else if (arg.equalsIgnoreCase("-msgFile")) {
            if (i == args.length - 1 || args[i + 1].startsWith("-")) {
                System.err.println("Error: Missing message file");
                System.exit(-1);
            }
            messgefile = args[++i];
        } else if (arg.equals("-help")) {
            //printUsage();
            System.exit(-1);
        } else {
            System.err.println("Error: Unknown argument " + arg + "\n");
            //printUsage();
            System.exit(-1);
        }
    }
    if (messgefile == null) {
        System.err.println("Error: missing message file\n");
    }
    InputStream inStream = null;
    try {
        inStream = FileUtils.openInputStream(new File(messgefile));
        MimeMessage message = new MimeMessage(null, inStream);
        MimeMultipart mm = (MimeMultipart) message.getContent();
        //byte[] messageBytes = EntitySerializer.Default.serializeToBytes(mm.getBodyPart(0).getContent());
        //MimeBodyPart signedContent = null;
        //signedContent = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
        final CMSSignedData signed = new CMSSignedData(new CMSProcessableBodyPart(mm.getBodyPart(0)), mm.getBodyPart(1).getInputStream());
        CertStore certs = signed.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
        SignerInformationStore signers = signed.getSignerInfos();
        @SuppressWarnings("unchecked") Collection<SignerInformation> c = signers.getSigners();
        System.out.println("Found " + c.size() + " signers");
        int cnt = 1;
        for (SignerInformation signer : c) {
            Collection<? extends Certificate> certCollection = certs.getCertificates(signer.getSID());
            if (certCollection != null && certCollection.size() > 0) {
                X509Certificate cert = (X509Certificate) certCollection.iterator().next();
                System.out.println("\r\nInfo for certificate " + cnt++);
                System.out.println("\tSubject " + cert.getSubjectDN());
                FileUtils.writeByteArrayToFile(new File("SigCert.der"), cert.getEncoded());
                byte[] bytes = cert.getExtensionValue("2.5.29.15");
                if (bytes != null) {
                    final DERObject obj = getObject(bytes);
                    final KeyUsage keyUsage = new KeyUsage((DERBitString) obj);
                    final byte[] data = keyUsage.getBytes();
                    final int intValue = (data.length == 1) ? data[0] & 0xff : (data[1] & 0xff) << 8 | (data[0] & 0xff);
                    System.out.println("\tKey Usage: " + intValue);
                } else
                    System.out.println("\tKey Usage: NONE");
                //verify and get the digests
                final Attribute digAttr = signer.getSignedAttributes().get(CMSAttributes.messageDigest);
                final DERObject hashObj = digAttr.getAttrValues().getObjectAt(0).getDERObject();
                final byte[] signedDigest = ((ASN1OctetString) hashObj).getOctets();
                final String signedDigestHex = org.apache.commons.codec.binary.Hex.encodeHexString(signedDigest);
                System.out.println("\r\nSigned Message Digest: " + signedDigestHex);
                try {
                    signer.verify(cert, "BC");
                    System.out.println("Signature verified.");
                } catch (CMSException e) {
                    System.out.println("Signature failed to verify.");
                }
                // should have the computed digest now
                final byte[] digest = signer.getContentDigest();
                final String digestHex = org.apache.commons.codec.binary.Hex.encodeHexString(digest);
                System.out.println("\r\nComputed Message Digest: " + digestHex);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(inStream);
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) Attribute(org.bouncycastle.asn1.cms.Attribute) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) InputStream(java.io.InputStream) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) SignerInformation(org.bouncycastle.cms.SignerInformation) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) CMSException(org.bouncycastle.cms.CMSException) PolicyProcessException(org.nhindirect.policy.PolicyProcessException) CMSProcessableBodyPart(org.bouncycastle.mail.smime.CMSProcessableBodyPart) DERObject(org.bouncycastle.asn1.DERObject) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) File(java.io.File) CertStore(java.security.cert.CertStore) CMSException(org.bouncycastle.cms.CMSException)

Example 3 with CMSException

use of org.bouncycastle.cms.CMSException in project pdfbox by apache.

the class CreateEmbeddedTimeStamp method processTimeStamping.

/**
 * Processes the time-stamping of the Signature.
 *
 * @param outFile Where the new file will be written to
 * @param fileName of the existing file containing the pdf
 * @throws IOException
 */
private void processTimeStamping(File outFile, String fileName) throws IOException {
    int accessPermissions = SigUtils.getMDPPermission(document);
    if (accessPermissions == 1) {
        throw new IllegalStateException("No changes to the document are permitted due to DocMDP transform parameters dictionary");
    }
    try {
        byte[] documentBytes;
        try (FileInputStream fis = new FileInputStream(fileName)) {
            documentBytes = IOUtils.toByteArray(fis);
        }
        processRelevantSignatures(documentBytes);
        if (changedEncodedSignature != null) {
            try (FileOutputStream output = new FileOutputStream(outFile)) {
                embedNewSignatureIntoDocument(documentBytes, output);
            }
        }
    } catch (IOException | NoSuchAlgorithmException | CMSException e) {
        throw new IOException(e);
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) FileInputStream(java.io.FileInputStream) CMSException(org.bouncycastle.cms.CMSException)

Example 4 with CMSException

use of org.bouncycastle.cms.CMSException in project pdfbox by apache.

the class CreateSignatureBase method sign.

/**
 * SignatureInterface implementation.
 *
 * This method will be called from inside of the pdfbox and create the PKCS #7 signature.
 * The given InputStream contains the bytes that are given by the byte range.
 *
 * This method is for internal use only.
 *
 * Use your favorite cryptographic library to implement PKCS #7 signature creation.
 *
 * @throws IOException
 */
@Override
public byte[] sign(InputStream content) throws IOException {
    // cannot be done private (interface)
    try {
        List<Certificate> certList = new ArrayList<>();
        certList.addAll(Arrays.asList(certificateChain));
        Store certs = new JcaCertStore(certList);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate.getInstance(certificateChain[0].getEncoded());
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
        gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(sha1Signer, new X509CertificateHolder(cert)));
        gen.addCertificates(certs);
        CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
        CMSSignedData signedData = gen.generate(msg, false);
        if (tsaUrl != null && tsaUrl.length() > 0) {
            ValidationTimeStamp validation = new ValidationTimeStamp(tsaUrl);
            signedData = validation.addSignedTimeStamp(signedData);
        }
        return signedData.getEncoded();
    } catch (GeneralSecurityException | CMSException | OperatorCreationException e) {
        throw new IOException(e);
    }
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) GeneralSecurityException(java.security.GeneralSecurityException) ArrayList(java.util.ArrayList) ContentSigner(org.bouncycastle.operator.ContentSigner) Store(org.bouncycastle.util.Store) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) KeyStore(java.security.KeyStore) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) JcaSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) CMSException(org.bouncycastle.cms.CMSException)

Example 5 with CMSException

use of org.bouncycastle.cms.CMSException in project pdfbox by apache.

the class ShowSignature method showSignature.

private void showSignature(String[] args) throws IOException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, TSPException {
    if (args.length != 2) {
        usage();
    } else {
        String password = args[0];
        File infile = new File(args[1]);
        try (PDDocument document = PDDocument.load(infile, password)) {
            for (PDSignature sig : document.getSignatureDictionaries()) {
                COSDictionary sigDict = sig.getCOSObject();
                COSString contents = (COSString) sigDict.getDictionaryObject(COSName.CONTENTS);
                // download the signed content
                byte[] buf;
                try (FileInputStream fis = new FileInputStream(infile)) {
                    buf = sig.getSignedContent(fis);
                }
                System.out.println("Signature found");
                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.getString().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");
                    }
                }
                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(buf, contents, sig);
                            // TODO check certificate chain, revocation lists, timestamp...
                            break;
                        case "adbe.pkcs7.sha1":
                            {
                                // example: PDFBOX-1452.pdf
                                byte[] certData = contents.getBytes();
                                CertificateFactory factory = CertificateFactory.getInstance("X.509");
                                ByteArrayInputStream certStream = new ByteArrayInputStream(certData);
                                Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
                                System.out.println("certs=" + certs);
                                byte[] hash = MessageDigest.getInstance("SHA1").digest(buf);
                                verifyPKCS7(hash, contents, sig);
                                // TODO check certificate chain, revocation lists, timestamp...
                                break;
                            }
                        case "adbe.x509.rsa_sha1":
                            {
                                // example: PDFBOX-2693.pdf
                                COSString certString = (COSString) sigDict.getDictionaryObject(COSName.CERT);
                                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);
                                // TODO verify signature
                                break;
                            }
                        case "ETSI.RFC3161":
                            TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(contents.getBytes()));
                            System.out.println("Time stamp gen time: " + timeStampToken.getTimeStampInfo().getGenTime());
                            System.out.println("Time stamp tsa name: " + timeStampToken.getTimeStampInfo().getTsa().getName());
                            CertificateFactory factory = CertificateFactory.getInstance("X.509");
                            ByteArrayInputStream certStream = new ByteArrayInputStream(contents.getBytes());
                            Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
                            System.out.println("certs=" + certs);
                            // TODO verify signature
                            break;
                        default:
                            System.err.println("Unknown certificate type: " + subFilter);
                            break;
                    }
                } else {
                    throw new IOException("Missing subfilter for cert dictionary");
                }
            }
            analyseDSS(document);
        } catch (CMSException | OperatorCreationException ex) {
            throw new IOException(ex);
        }
        System.out.println("Analyzed: " + args[1]);
    }
}
Also used : COSDictionary(org.apache.pdfbox.cos.COSDictionary) COSString(org.apache.pdfbox.cos.COSString) IOException(java.io.IOException) PDSignature(org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature) CertificateFactory(java.security.cert.CertificateFactory) CMSSignedData(org.bouncycastle.cms.CMSSignedData) FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) PDDocument(org.apache.pdfbox.pdmodel.PDDocument) Collection(java.util.Collection) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) File(java.io.File) COSString(org.apache.pdfbox.cos.COSString) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) CMSException(org.bouncycastle.cms.CMSException)

Aggregations

CMSException (org.bouncycastle.cms.CMSException)41 CMSSignedData (org.bouncycastle.cms.CMSSignedData)30 IOException (java.io.IOException)28 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)19 X509Certificate (java.security.cert.X509Certificate)18 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)14 CMSSignedDataGenerator (org.bouncycastle.cms.CMSSignedDataGenerator)14 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)13 CertificateEncodingException (java.security.cert.CertificateEncodingException)11 CertificateException (java.security.cert.CertificateException)10 SignerInformation (org.bouncycastle.cms.SignerInformation)9 CMSAbsentContent (org.bouncycastle.cms.CMSAbsentContent)8 SignerInformationStore (org.bouncycastle.cms.SignerInformationStore)8 InputStream (java.io.InputStream)7 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)7 TSPException (org.bouncycastle.tsp.TSPException)7 CertificateCoreException (org.demoiselle.signer.core.exception.CertificateCoreException)7 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)6 Attribute (org.bouncycastle.asn1.cms.Attribute)6 CMSTypedData (org.bouncycastle.cms.CMSTypedData)6