Search in sources :

Example 1 with SignerInformation

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

the class CryptoExtensions method findSignersByName.

/**
	 * Searches CMS signed data for a given email name.  Signed data may consist of multiple signatures either from the same subject of from multiple
	 * subjects. 
	 * @param signedData The signed data to search.
	 * @param name The name to search for in the list of signers.
	 * @param excludeNames A list of names to exclude from the list.  Because the search uses a simple "contains" search, it is possible for the name parameter
	 * to be a substring of what is requested.  The excludeNames contains a super string of the name to remove unwanted names from the returned list.  This parameter
	 * may be null;
	 * @return A colllection of pairs consisting of the singer's X509 certificated and signer information that matches the provided name.  Returns
	 * an empty collection if a signer matching the name cannot be found in the signed data.
	 */
public static Collection<SignerCertPair> findSignersByName(CMSSignedData signedData, String name, Collection<String> excludeNames) {
    if (name == null || name.length() == 0) {
        throw new IllegalArgumentException();
    }
    Collection<SignerCertPair> retVal = null;
    try {
        CertStore certs = signedData.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
        SignerInformationStore signers = signedData.getSignerInfos();
        Collection<SignerInformation> c = signers.getSigners();
        for (SignerInformation signer : c) {
            Collection<? extends Certificate> certCollection = certs.getCertificates(signer.getSID());
            if (certCollection != null && certCollection.size() > 0) {
                X509Certificate cert = (X509Certificate) certCollection.iterator().next();
                if (certSubjectContainsName(cert, name)) {
                    boolean exclude = false;
                    // check if we need to exclude anything
                    if (excludeNames != null)
                        for (String excludeStr : excludeNames) if (certSubjectContainsName(cert, excludeStr)) {
                            exclude = true;
                            break;
                        }
                    if (exclude)
                        // break out and don't include this cert
                        continue;
                    if (retVal == null)
                        retVal = new ArrayList<SignerCertPair>();
                    retVal.add(new SignerCertPair(signer, convertToProfileProvidedCertImpl(cert)));
                }
            }
        }
    } catch (Throwable e) {
    }
    if (retVal == null)
        return Collections.emptyList();
    return retVal;
}
Also used : SignerCertPair(org.nhindirect.stagent.cert.SignerCertPair) ArrayList(java.util.ArrayList) SignerInformation(org.bouncycastle.cms.SignerInformation) X509Certificate(java.security.cert.X509Certificate) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) CertStore(java.security.cert.CertStore)

Example 2 with SignerInformation

use of org.bouncycastle.cms.SignerInformation 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 SignerInformation

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

the class SplitProviderDirectSignedDataGenerator_generateTest method validateSignature.

@SuppressWarnings("unchecked")
protected void validateSignature(CMSSignedData data) throws Exception {
    assertNotNull(data);
    assertEquals(1, data.getSignerInfos().getSigners().size());
    for (SignerInformation sigInfo : (Collection<SignerInformation>) data.getSignerInfos().getSigners()) assertTrue(sigInfo.verify(signerCert, CryptoExtensions.getJCEProviderName()));
}
Also used : Collection(java.util.Collection) SignerInformation(org.bouncycastle.cms.SignerInformation)

Example 4 with SignerInformation

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

the class ShowSignature method verifyPKCS7.

/**
 * Verify a PKCS7 signature.
 *
 * @param byteArray the byte sequence that has been signed
 * @param contents the /Contents field as a COSString
 * @param sig the PDF signature (the /V dictionary)
 * @throws CertificateException
 * @throws CMSException
 * @throws StoreException
 * @throws OperatorCreationException
 */
private void verifyPKCS7(byte[] byteArray, COSString contents, PDSignature sig) throws CMSException, CertificateException, StoreException, OperatorCreationException, NoSuchAlgorithmException, NoSuchProviderException {
    // inspiration:
    // http://stackoverflow.com/a/26702631/535646
    // http://stackoverflow.com/a/9261365/535646
    CMSProcessable signedContent = new CMSProcessableByteArray(byteArray);
    CMSSignedData signedData = new CMSSignedData(signedContent, contents.getBytes());
    Store<X509CertificateHolder> certificatesStore = signedData.getCertificates();
    Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
    SignerInformation signerInformation = signers.iterator().next();
    Collection<X509CertificateHolder> matches = certificatesStore.getMatches(signerInformation.getSID());
    X509CertificateHolder certificateHolder = matches.iterator().next();
    X509Certificate certFromSignedData = new JcaX509CertificateConverter().getCertificate(certificateHolder);
    System.out.println("certFromSignedData: " + certFromSignedData);
    certFromSignedData.checkValidity(sig.getSignDate().getTime());
    if (isSelfSigned(certFromSignedData)) {
        System.err.println("Certificate is self-signed, LOL!");
    } else {
        System.out.println("Certificate is not self-signed");
    // todo rest of chain
    }
    if (signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData))) {
        System.out.println("Signature verified");
    } else {
        System.out.println("Signature verification failed");
    }
}
Also used : CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CMSProcessable(org.bouncycastle.cms.CMSProcessable) X509Certificate(java.security.cert.X509Certificate)

Example 5 with SignerInformation

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

the class TestCreateSignature method checkSignature.

// This check fails with a file created with the code before PDFBOX-3011 was solved.
private void checkSignature(File file) throws IOException, CMSException, OperatorCreationException, GeneralSecurityException {
    try (PDDocument document = PDDocument.load(file)) {
        List<PDSignature> signatureDictionaries = document.getSignatureDictionaries();
        if (signatureDictionaries.isEmpty()) {
            Assert.fail("no signature found");
        }
        for (PDSignature sig : document.getSignatureDictionaries()) {
            COSString contents = (COSString) sig.getCOSObject().getDictionaryObject(COSName.CONTENTS);
            byte[] buf;
            try (FileInputStream fis = new FileInputStream(file)) {
                buf = sig.getSignedContent(fis);
            }
            // inspiration:
            // http://stackoverflow.com/a/26702631/535646
            // http://stackoverflow.com/a/9261365/535646
            CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(buf), contents.getBytes());
            Store certificatesStore = signedData.getCertificates();
            Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
            SignerInformation signerInformation = signers.iterator().next();
            Collection matches = certificatesStore.getMatches(signerInformation.getSID());
            X509CertificateHolder certificateHolder = (X509CertificateHolder) matches.iterator().next();
            X509Certificate certFromSignedData = new JcaX509CertificateConverter().getCertificate(certificateHolder);
            Assert.assertEquals(certificate, certFromSignedData);
            // CMSVerifierCertificateNotValidException means that the keystore wasn't valid at signing time
            if (!signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData))) {
                Assert.fail("Signature verification failed");
            }
            break;
        }
    }
}
Also used : CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) Store(org.bouncycastle.util.Store) KeyStore(java.security.KeyStore) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) PDSignature(org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature) CMSSignedData(org.bouncycastle.cms.CMSSignedData) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) PDDocument(org.apache.pdfbox.pdmodel.PDDocument) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) Collection(java.util.Collection) COSString(org.apache.pdfbox.cos.COSString)

Aggregations

SignerInformation (org.bouncycastle.cms.SignerInformation)32 SignerInformationStore (org.bouncycastle.cms.SignerInformationStore)21 CMSSignedData (org.bouncycastle.cms.CMSSignedData)19 X509Certificate (java.security.cert.X509Certificate)17 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)13 JcaSimpleSignerInfoVerifierBuilder (org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder)13 CMSException (org.bouncycastle.cms.CMSException)10 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)8 CertificateException (java.security.cert.CertificateException)7 Attribute (org.bouncycastle.asn1.cms.Attribute)7 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)7 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)7 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 Collection (java.util.Collection)6 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)6 FileInputStream (java.io.FileInputStream)4 CertStore (java.security.cert.CertStore)4 Date (java.util.Date)4