Search in sources :

Example 16 with SignedData

use of org.bouncycastle.asn1.pkcs.SignedData in project nhin-d by DirectProject.

the class SplitProviderDirectSignedDataGenerator method generate.

/**
	 * {@inheritDoc}
	 */
@Override
public CMSSignedData generate(String signedContentType, CMSProcessable content, boolean encapsulate, String sigProvider, boolean addDefaultAttributes) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException {
    final ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
    final ASN1EncodableVector signerInfos = new ASN1EncodableVector();
    // clear the current preserved digest state
    _digests.clear();
    //
    // add the SignerInfo objects
    //
    DERObjectIdentifier contentTypeOID;
    boolean isCounterSignature;
    if (signedContentType != null) {
        contentTypeOID = new DERObjectIdentifier(signedContentType);
        isCounterSignature = false;
    } else {
        contentTypeOID = CMSObjectIdentifiers.data;
        isCounterSignature = true;
    }
    for (DirectTargetedSignerInf signer : privateSigners) {
        AlgorithmIdentifier digAlgId;
        try {
            digAlgId = new AlgorithmIdentifier(new DERObjectIdentifier(signer.digestOID), new DERNull());
            digestAlgs.add(digAlgId);
            try {
                signerInfos.add(signer.toSignerInfo(contentTypeOID, content, rand, sigProvider, digestProvider, addDefaultAttributes, isCounterSignature));
            } catch (ClassCastException e) {
                // try again with the digest provider... the key may need to use a different provider than the sig provider
                signerInfos.add(signer.toSignerInfo(contentTypeOID, content, rand, digestProvider, digestProvider, addDefaultAttributes, isCounterSignature));
            }
        } catch (IOException e) {
            throw new CMSException("encoding error.", e);
        } catch (InvalidKeyException e) {
            throw new CMSException("key inappropriate for signature.", e);
        } catch (SignatureException e) {
            throw new CMSException("error creating signature.", e);
        } catch (CertificateEncodingException e) {
            throw new CMSException("error creating sid.", e);
        }
    }
    ASN1Set certificates = null;
    if (_certs.size() != 0) {
        certificates = createBerSetFromList(_certs);
    }
    ASN1Set certrevlist = null;
    if (_crls.size() != 0) {
        certrevlist = createBerSetFromList(_crls);
    }
    ContentInfo encInfo;
    if (encapsulate) {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        try {
            content.write(bOut);
        } catch (IOException e) {
            throw new CMSException("encapsulation error.", e);
        }
        ASN1OctetString octs = new BERConstructedOctetString(bOut.toByteArray());
        encInfo = new ContentInfo(contentTypeOID, octs);
    } else {
        encInfo = new ContentInfo(contentTypeOID, null);
    }
    SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist, new DERSet(signerInfos));
    ContentInfo contentInfo = new ContentInfo(PKCSObjectIdentifiers.signedData, sd);
    return new CMSSignedData(content, contentInfo);
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) SignedData(org.bouncycastle.asn1.cms.SignedData) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) SignatureException(java.security.SignatureException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InvalidKeyException(java.security.InvalidKeyException) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) DERSet(org.bouncycastle.asn1.DERSet) CMSSignedData(org.bouncycastle.cms.CMSSignedData) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) ASN1Set(org.bouncycastle.asn1.ASN1Set) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) DERNull(org.bouncycastle.asn1.DERNull) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) BERConstructedOctetString(org.bouncycastle.asn1.BERConstructedOctetString) CMSException(org.bouncycastle.cms.CMSException)

Example 17 with SignedData

use of org.bouncycastle.asn1.pkcs.SignedData 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)

Aggregations

ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)10 IOException (java.io.IOException)7 X509Certificate (java.security.cert.X509Certificate)6 ASN1Set (org.bouncycastle.asn1.ASN1Set)6 ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)6 ArrayList (java.util.ArrayList)5 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)5 DERSet (org.bouncycastle.asn1.DERSet)5 SignedData (org.bouncycastle.asn1.cms.SignedData)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 CertificateEncodingException (java.security.cert.CertificateEncodingException)4 Iterator (java.util.Iterator)4 List (java.util.List)4 BERSequence (org.bouncycastle.asn1.BERSequence)4 DERTaggedObject (org.bouncycastle.asn1.DERTaggedObject)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 DERObjectIdentifier (org.bouncycastle.asn1.DERObjectIdentifier)3 CMSSignedData (org.bouncycastle.cms.CMSSignedData)3 InputStream (java.io.InputStream)2 OutputStream (java.io.OutputStream)2