Search in sources :

Example 6 with AttributeTable

use of org.bouncycastle.asn1.cms.AttributeTable in project robovm by robovm.

the class SignerInformation method getCounterSignatures.

/**
     * Return a SignerInformationStore containing the counter signatures attached to this
     * signer. If no counter signatures are present an empty store is returned.
     */
public SignerInformationStore getCounterSignatures() {
    // TODO There are several checks implied by the RFC3852 comments that are missing
    /*
        The countersignature attribute MUST be an unsigned attribute; it MUST
        NOT be a signed attribute, an authenticated attribute, an
        unauthenticated attribute, or an unprotected attribute.
        */
    AttributeTable unsignedAttributeTable = getUnsignedAttributes();
    if (unsignedAttributeTable == null) {
        return new SignerInformationStore(new ArrayList(0));
    }
    List counterSignatures = new ArrayList();
    /*
        The UnsignedAttributes syntax is defined as a SET OF Attributes.  The
        UnsignedAttributes in a signerInfo may include multiple instances of
        the countersignature attribute.
        */
    ASN1EncodableVector allCSAttrs = unsignedAttributeTable.getAll(CMSAttributes.counterSignature);
    for (int i = 0; i < allCSAttrs.size(); ++i) {
        Attribute counterSignatureAttribute = (Attribute) allCSAttrs.get(i);
        /*
            A countersignature attribute can have multiple attribute values.  The
            syntax is defined as a SET OF AttributeValue, and there MUST be one
            or more instances of AttributeValue present.
            */
        ASN1Set values = counterSignatureAttribute.getAttrValues();
        if (values.size() < 1) {
        // TODO Throw an appropriate exception?
        }
        for (Enumeration en = values.getObjects(); en.hasMoreElements(); ) {
            /*
                Countersignature values have the same meaning as SignerInfo values
                for ordinary signatures, except that:

                   1. The signedAttributes field MUST NOT contain a content-type
                      attribute; there is no content type for countersignatures.

                   2. The signedAttributes field MUST contain a message-digest
                      attribute if it contains any other attributes.

                   3. The input to the message-digesting process is the contents
                      octets of the DER encoding of the signatureValue field of the
                      SignerInfo value with which the attribute is associated.
                */
            SignerInfo si = SignerInfo.getInstance(en.nextElement());
            counterSignatures.add(new SignerInformation(si, null, new CMSProcessableByteArray(getSignature()), null));
        }
    }
    return new SignerInformationStore(counterSignatures);
}
Also used : SignerInfo(org.bouncycastle.asn1.cms.SignerInfo) Enumeration(java.util.Enumeration) ASN1Set(org.bouncycastle.asn1.ASN1Set) Attribute(org.bouncycastle.asn1.cms.Attribute) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) ArrayList(java.util.ArrayList) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ArrayList(java.util.ArrayList) List(java.util.List)

Example 7 with AttributeTable

use of org.bouncycastle.asn1.cms.AttributeTable in project robovm by robovm.

the class SignerInformation method replaceUnsignedAttributes.

/**
     * Return a signer information object with the passed in unsigned
     * attributes replacing the ones that are current associated with
     * the object passed in.
     * 
     * @param signerInformation the signerInfo to be used as the basis.
     * @param unsignedAttributes the unsigned attributes to add.
     * @return a copy of the original SignerInformationObject with the changed attributes.
     */
public static SignerInformation replaceUnsignedAttributes(SignerInformation signerInformation, AttributeTable unsignedAttributes) {
    SignerInfo sInfo = signerInformation.info;
    ASN1Set unsignedAttr = null;
    if (unsignedAttributes != null) {
        unsignedAttr = new DERSet(unsignedAttributes.toASN1EncodableVector());
    }
    return new SignerInformation(new SignerInfo(sInfo.getSID(), sInfo.getDigestAlgorithm(), sInfo.getAuthenticatedAttributes(), sInfo.getDigestEncryptionAlgorithm(), sInfo.getEncryptedDigest(), unsignedAttr), signerInformation.contentType, signerInformation.content, null);
}
Also used : SignerInfo(org.bouncycastle.asn1.cms.SignerInfo) ASN1Set(org.bouncycastle.asn1.ASN1Set) DERSet(org.bouncycastle.asn1.DERSet)

Example 8 with AttributeTable

use of org.bouncycastle.asn1.cms.AttributeTable in project robovm by robovm.

the class SignerInfoGenerator method generate.

public SignerInfo generate(ASN1ObjectIdentifier contentType) throws CMSException {
    try {
        /* RFC 3852 5.4
             * The result of the message digest calculation process depends on
             * whether the signedAttrs field is present.  When the field is absent,
             * the result is just the message digest of the content as described
             *
             * above.  When the field is present, however, the result is the message
             * digest of the complete DER encoding of the SignedAttrs value
             * contained in the signedAttrs field.
             */
        ASN1Set signedAttr = null;
        AlgorithmIdentifier digestAlg = null;
        if (sAttrGen != null) {
            digestAlg = digester.getAlgorithmIdentifier();
            calculatedDigest = digester.getDigest();
            Map parameters = getBaseParameters(contentType, digester.getAlgorithmIdentifier(), calculatedDigest);
            AttributeTable signed = sAttrGen.getAttributes(Collections.unmodifiableMap(parameters));
            signedAttr = getAttributeSet(signed);
            // sig must be composed from the DER encoding.
            OutputStream sOut = signer.getOutputStream();
            sOut.write(signedAttr.getEncoded(ASN1Encoding.DER));
            sOut.close();
        } else {
            if (digester != null) {
                digestAlg = digester.getAlgorithmIdentifier();
                calculatedDigest = digester.getDigest();
            } else {
                digestAlg = digAlgFinder.find(signer.getAlgorithmIdentifier());
                calculatedDigest = null;
            }
        }
        byte[] sigBytes = signer.getSignature();
        ASN1Set unsignedAttr = null;
        if (unsAttrGen != null) {
            Map parameters = getBaseParameters(contentType, digestAlg, calculatedDigest);
            parameters.put(CMSAttributeTableGenerator.SIGNATURE, sigBytes.clone());
            AttributeTable unsigned = unsAttrGen.getAttributes(Collections.unmodifiableMap(parameters));
            unsignedAttr = getAttributeSet(unsigned);
        }
        AlgorithmIdentifier digestEncryptionAlgorithm = sigEncAlgFinder.findEncryptionAlgorithm(signer.getAlgorithmIdentifier());
        return new SignerInfo(signerIdentifier, digestAlg, signedAttr, digestEncryptionAlgorithm, new DEROctetString(sigBytes), unsignedAttr);
    } catch (IOException e) {
        throw new CMSException("encoding error.", e);
    }
}
Also used : SignerInfo(org.bouncycastle.asn1.cms.SignerInfo) ASN1Set(org.bouncycastle.asn1.ASN1Set) OutputStream(java.io.OutputStream) TeeOutputStream(org.bouncycastle.util.io.TeeOutputStream) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 9 with AttributeTable

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

the class SplitProviderDirectSignedDataGenerator method addSigner.

/**
	 * {@inheritDoc}
	 */
@Override
public void addSigner(PrivateKey key, X509Certificate cert, String digestOID, AttributeTable signedAttr, AttributeTable unsignedAttr) throws IllegalArgumentException {
    final String encOID = getEncOID(key, digestOID);
    privateSigners.add(new DirectTargetedSignerInf(key, cert, digestOID, encOID, new DefaultSignedAttributeTableGenerator(signedAttr), new SimpleAttributeTableGenerator(unsignedAttr), signedAttr));
}
Also used : SimpleAttributeTableGenerator(org.bouncycastle.cms.SimpleAttributeTableGenerator) DefaultSignedAttributeTableGenerator(org.bouncycastle.cms.DefaultSignedAttributeTableGenerator) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) BERConstructedOctetString(org.bouncycastle.asn1.BERConstructedOctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString)

Example 10 with AttributeTable

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

AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)7 Attribute (org.bouncycastle.asn1.cms.Attribute)6 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)5 ASN1Set (org.bouncycastle.asn1.ASN1Set)4 SignerInfo (org.bouncycastle.asn1.cms.SignerInfo)4 IOException (java.io.IOException)3 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)3 DEROctetString (org.bouncycastle.asn1.DEROctetString)3 DERSet (org.bouncycastle.asn1.DERSet)3 OutputStream (java.io.OutputStream)2 ArrayList (java.util.ArrayList)2 Iterator (java.util.Iterator)2 List (java.util.List)2 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)2 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 InvalidKeyException (java.security.InvalidKeyException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 NoSuchProviderException (java.security.NoSuchProviderException)1