Search in sources :

Example 6 with SignerInformationStore

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

the class SigTest method testCreateVerifySig.

public void testCreateVerifySig() throws Exception {
    X509CertificateEx internalCert = TestUtils.getInternalCert("user1");
    X509Certificate caCert = TestUtils.getExternalCert("cacert");
    String testMessage = TestUtils.readResource("MultipartMimeMessage.txt");
    MimeMessage entity = EntitySerializer.Default.deserialize(testMessage);
    Message message = new Message(entity);
    MimeEntity entityToSig = message.extractEntityForSignature(true);
    // Serialize message out as ASCII encoded...
    byte[] messageBytes = EntitySerializer.Default.serializeToBytes(entityToSig);
    MimeBodyPart partToSign = null;
    try {
        partToSign = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
    } catch (Exception e) {
    }
    SMIMESignedGenerator gen = new SMIMESignedGenerator();
    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
    SMIMECapabilityVector caps = new SMIMECapabilityVector();
    caps.addCapability(SMIMECapability.dES_EDE3_CBC);
    caps.addCapability(SMIMECapability.rC2_CBC, 128);
    caps.addCapability(SMIMECapability.dES_CBC);
    caps.addCapability(new DERObjectIdentifier("1.2.840.113549.1.7.1"));
    caps.addCapability(PKCSObjectIdentifiers.x509Certificate);
    signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
    List certList = new ArrayList();
    gen.addSigner(internalCert.getPrivateKey(), internalCert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null);
    //SMIMESignedGenerator.DIGEST_SHA1, null, null);
    certList.add(internalCert);
    MimeMultipart retVal = null;
    CertStore certsAndcrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), CryptoExtensions.getJCEProviderName());
    gen.addCertificatesAndCRLs(certsAndcrls);
    _certStores.add(certsAndcrls);
    _signers.add(new Signer(internalCert.getPrivateKey(), internalCert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null));
    retVal = generate(partToSign, CryptoExtensions.getJCEProviderName());
    for (int i = 0; i < 10; ++i) {
        ByteArrayOutputStream oStream = new ByteArrayOutputStream();
        retVal.writeTo(oStream);
        oStream.flush();
        byte[] serialzedBytes = oStream.toByteArray();
        //System.out.println(new String(serialzedBytes, "ASCII") + "\r\n\r\n\r\n\r\n\r\n");
        ByteArrayDataSource dataSource = new ByteArrayDataSource(serialzedBytes, retVal.getContentType());
        MimeMultipart verifyMM = new MimeMultipart(dataSource);
        CMSSignedData signed = null;
        //CMSSignedData signeddata = new CMSSignedData(new CMSProcessableBodyPartInbound(verifyMM.getBodyPart(0)), verifyMM.getBodyPart(1).getInputStream());			
        CMSSignedData signeddata = new CMSSignedData(new CMSProcessableBodyPartInbound(partToSign), verifyMM.getBodyPart(1).getInputStream());
        int verified = 0;
        CertStore certs = signeddata.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
        SignerInformationStore signers = signeddata.getSignerInfos();
        Collection c = signers.getSigners();
        Iterator it = c.iterator();
        while (it.hasNext()) {
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = certs.getCertificates(signer.getSID());
            Attribute dig = signer.getSignedAttributes().get(CMSAttributes.messageDigest);
            DERObject hashObj = dig.getAttrValues().getObjectAt(0).getDERObject();
            byte[] signedHash = ((ASN1OctetString) hashObj).getOctets();
            System.out.print("value of signedHash: \r\n\tvalue: ");
            for (byte bt : signedHash) {
                System.out.print(bt + " ");
            }
            System.out.println();
            Iterator certIt = certCollection.iterator();
            try {
                assertTrue(signer.verify(internalCert, CryptoExtensions.getJCEProviderName()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            byte[] bytes = signer.getContentDigest();
            /*
	    		  X509Certificate cert = (X509Certificate)certIt.next();
	    		  
    		      if (signer.verify(cert.getPublicKey()))
    		      {
    		          verified++;
    		      }
	    		  */
            verified++;
        }
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) CMSProcessableBodyPartInbound(org.bouncycastle.mail.smime.CMSProcessableBodyPartInbound) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Attribute(org.bouncycastle.asn1.cms.Attribute) SMIMECapabilitiesAttribute(org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute) ArrayList(java.util.ArrayList) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) SMIMESignedGenerator(org.bouncycastle.mail.smime.SMIMESignedGenerator) SignerInformation(org.bouncycastle.cms.SignerInformation) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) DERObject(org.bouncycastle.asn1.DERObject) MimeMessage(javax.mail.internet.MimeMessage) SMIMECapabilityVector(org.bouncycastle.asn1.smime.SMIMECapabilityVector) MimeMultipart(javax.mail.internet.MimeMultipart) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) Iterator(java.util.Iterator) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) List(java.util.List) ArrayList(java.util.ArrayList) SMIMECapabilitiesAttribute(org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) MessagingException(javax.mail.MessagingException) CertStoreException(java.security.cert.CertStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CMSException(org.bouncycastle.cms.CMSException) IOException(java.io.IOException) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) NoSuchProviderException(java.security.NoSuchProviderException) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) ByteArrayInputStream(java.io.ByteArrayInputStream) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) Collection(java.util.Collection) MimeBodyPart(javax.mail.internet.MimeBodyPart) CertStore(java.security.cert.CertStore)

Example 7 with SignerInformationStore

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

the class CryptoExtensions method findSignerByCert.

/**
	 * Searches CMS signed data for a specific X509 certificate.
	 * @param signedData The signed data to search.
	 * @param name The certificate to search for in the signed data.
	 * @return A pair consisting of the singer's X509 certificated and signer information that matches the provided certificate.  Returns
	 * null if a signer matching the name cannot be found in the signed data.
	 */
public static SignerCertPair findSignerByCert(CMSSignedData signedData, X509Certificate searchCert) {
    if (searchCert == null) {
        throw new IllegalArgumentException();
    }
    try {
        SignerInformationStore signers = signedData.getSignerInfos();
        Collection<SignerInformation> c = signers.getSigners();
        for (SignerInformation signer : c) {
            //signer.getSID().
            SignerId signerId = signer.getSID();
            if (signerId.getIssuer().equals(searchCert.getIssuerX500Principal()) && signerId.getSerialNumber().equals(searchCert.getSerialNumber())) {
                return new SignerCertPair(signer, searchCert);
            }
        }
    } catch (Exception e) {
    }
    return null;
}
Also used : SignerCertPair(org.nhindirect.stagent.cert.SignerCertPair) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) SignerId(org.bouncycastle.cms.SignerId) SignerInformation(org.bouncycastle.cms.SignerInformation) CertificateParsingException(java.security.cert.CertificateParsingException) CertificateException(java.security.cert.CertificateException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 8 with SignerInformationStore

use of org.bouncycastle.cms.SignerInformationStore in project athenz by yahoo.

the class Crypto method validatePKCS7Signature.

public static boolean validatePKCS7Signature(String data, String signature, PublicKey publicKey) {
    try {
        SignerInformationStore signerStore = null;
        try (InputStream sigIs = new ByteArrayInputStream(Base64.decode(signature.getBytes(StandardCharsets.UTF_8)))) {
            CMSProcessable content = new CMSProcessableByteArray(data.getBytes(StandardCharsets.UTF_8));
            CMSSignedData signedData = new CMSSignedData(content, sigIs);
            signerStore = signedData.getSignerInfos();
        }
        Collection<SignerInformation> signers = signerStore.getSigners();
        Iterator<SignerInformation> it = signers.iterator();
        SignerInformationVerifier infoVerifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC_PROVIDER).build(publicKey);
        while (it.hasNext()) {
            SignerInformation signerInfo = (SignerInformation) it.next();
            if (signerInfo.verify(infoVerifier)) {
                return true;
            }
        }
    } catch (CMSException ex) {
        LOG.error("validatePKCS7Signature: unable to initialize CMSSignedData object: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error("validatePKCS7Signature: Caught OperatorCreationException when creating JcaSimpleSignerInfoVerifierBuilder: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (IOException ex) {
        LOG.error("validatePKCS7Signature: Caught IOException when closing InputStream: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (Exception ex) {
        LOG.error("validatePKCS7Signature: unable to validate signature: " + ex.getMessage());
        throw new CryptoException(ex.getMessage());
    }
    return false;
}
Also used : CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CMSProcessable(org.bouncycastle.cms.CMSProcessable) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CMSException(org.bouncycastle.cms.CMSException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) SignatureException(java.security.SignatureException) FileNotFoundException(java.io.FileNotFoundException) CertificateParsingException(java.security.cert.CertificateParsingException) PEMException(org.bouncycastle.openssl.PEMException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) ByteArrayInputStream(java.io.ByteArrayInputStream) SignerInformationVerifier(org.bouncycastle.cms.SignerInformationVerifier) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CMSException(org.bouncycastle.cms.CMSException)

Aggregations

SignerInformation (org.bouncycastle.cms.SignerInformation)8 SignerInformationStore (org.bouncycastle.cms.SignerInformationStore)8 CertStore (java.security.cert.CertStore)4 X509Certificate (java.security.cert.X509Certificate)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 CertificateException (java.security.cert.CertificateException)3 CertificateParsingException (java.security.cert.CertificateParsingException)3 ArrayList (java.util.ArrayList)3 CMSException (org.bouncycastle.cms.CMSException)3 CMSSignedData (org.bouncycastle.cms.CMSSignedData)3 FileInputStream (java.io.FileInputStream)2 InvalidKeyException (java.security.InvalidKeyException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 NoSuchProviderException (java.security.NoSuchProviderException)2 MimeMessage (javax.mail.internet.MimeMessage)2 MimeMultipart (javax.mail.internet.MimeMultipart)2 SignerId (org.bouncycastle.cms.SignerId)2 SignerInformationVerifier (org.bouncycastle.cms.SignerInformationVerifier)2