private void basicTestWithTSA(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.Sha1, "1.2");

            tsTokenGen.SetCertificates(certs);
            tsTokenGen.SetTsa(new Asn1.X509.GeneralName(new X509Name("CN=Test")));

            TimeStampRequestGenerator reqGen  = new TimeStampRequestGenerator();
            TimeStampRequest          request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100));

            TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed);

            TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow);

            tsResp = new TimeStampResponse(tsResp.GetEncoded());

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            Asn1.Cms.AttributeTable table = tsToken.SignedAttributes;

            Assert.IsNotNull(table[PkcsObjectIdentifiers.IdAASigningCertificate], "no signingCertificate attribute found");
        }
Пример #2
0
 internal protected virtual Asn1Set GetAttributeSet(
     Asn1.Cms.AttributeTable attr)
 {
     return(attr == null
         ? null
         : new DerSet(attr.ToAsn1EncodableVector()));
 }
Пример #3
0
        internal static SignerInfoGenerator MakeInfoGenerator(AsymmetricKeyParameter key, X509Certificate cert,
                                                              string digestOID, Asn1.Cms.AttributeTable signedAttr, Asn1.Cms.AttributeTable unsignedAttr)
        {
            TspUtil.ValidateCertificate(cert);

            //
            // Add the ESSCertID attribute
            //
            IDictionary signedAttrs;

            if (signedAttr != null)
            {
                signedAttrs = signedAttr.ToDictionary();
            }
            else
            {
                signedAttrs = new Hashtable();
            }

            string digestName    = TspTestUtil.GetDigestAlgName(digestOID);
            string signatureName = digestName + "with" + TspTestUtil.GetEncryptionAlgName(
                TspTestUtil.GetEncOid(key, digestOID));

            Asn1SignatureFactory sigfact = new Asn1SignatureFactory(signatureName, key);

            return(new SignerInfoGeneratorBuilder()
                   .WithSignedAttributeGenerator(
                       new DefaultSignedAttributeTableGenerator(
                           new Asn1.Cms.AttributeTable(signedAttrs)))
                   .WithUnsignedAttributeGenerator(
                       new SimpleAttributeTableGenerator(unsignedAttr))
                   .Build(sigfact, cert));
        }
        /**
         * return a table of the unprotected attributes indexed by
         * the OID of the attribute.
         * @throws IOException
         */
        public Asn1.Cms.AttributeTable GetUnprotectedAttributes()
        {
            if (_unprotectedAttributes == null && _attrNotRead)
            {
                Asn1SetParser asn1Set = this.envelopedData.GetUnprotectedAttrs();

                _attrNotRead = false;

                if (asn1Set != null)
                {
                    Asn1EncodableVector v = new Asn1EncodableVector();
                    IAsn1Convertible    o;

                    while ((o = asn1Set.ReadObject()) != null)
                    {
                        Asn1SequenceParser seq = (Asn1SequenceParser)o;

                        v.Add(seq.ToAsn1Object());
                    }

                    _unprotectedAttributes = new Asn1.Cms.AttributeTable(new DerSet(v));
                }
            }

            return(_unprotectedAttributes);
        }
        /**
         * return a table of the unauthenticated attributes indexed by
         * the OID of the attribute.
         * @exception java.io.IOException
         */
        public Asn1.Cms.AttributeTable GetUnauthAttrs()
        {
            if (unauthAttrs == null && unauthAttrNotRead)
            {
                Asn1SetParser s = authData.GetUnauthAttrs();

                unauthAttrNotRead = false;

                if (s != null)
                {
                    Asn1EncodableVector v = new Asn1EncodableVector();

                    IAsn1Convertible o;
                    while ((o = s.ReadObject()) != null)
                    {
                        Asn1SequenceParser seq = (Asn1SequenceParser)o;

                        v.Add(seq.ToAsn1Object());
                    }

                    unauthAttrs = new Asn1.Cms.AttributeTable(new DerSet(v));
                }
            }

            return(unauthAttrs);
        }
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    _out.Dispose();

                    // TODO Parent context(s) should really be be closed explicitly

                    _eiGen.Close();

                    if (_outer.unprotectedAttributeGenerator != null)
                    {
                        Asn1.Cms.AttributeTable attrTable = _outer.unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable());

                        Asn1Set unprotectedAttrs = new BerSet(attrTable.ToAsn1EncodableVector());

                        _envGen.AddObject(new DerTaggedObject(false, 1, unprotectedAttrs));
                    }

                    _envGen.Close();
                    _cGen.Close();
                }

                base.Dispose(disposing);
            }
        /**
         * create with a signer with extra signed/unsigned attributes.
         */
        public TimeStampTokenGenerator(
			AsymmetricKeyParameter	key,
			X509Certificate			cert,
			string					digestOID,
			string					tsaPolicyOID,
			Asn1.Cms.AttributeTable	signedAttr,
			Asn1.Cms.AttributeTable	unsignedAttr)
        {
            this.key = key;
            this.cert = cert;
            this.digestOID = digestOID;
            this.tsaPolicyOID = tsaPolicyOID;
            this.unsignedAttr = unsignedAttr;

            TspUtil.ValidateCertificate(cert);

            //
            // add the essCertid
            //
            Hashtable signedAttrs;
            if (signedAttr != null)
            {
                signedAttrs = signedAttr.ToHashtable();
            }
            else
            {
                signedAttrs = new Hashtable();
            }

            IDigest digest;
            try
            {
                digest = DigestUtilities.GetDigest("SHA-1");
            }
            catch (Exception e)
            {
                throw new TspException("Can't find a SHA-1 implementation.", e);
            }

            try
            {
                byte[] certEncoded = cert.GetEncoded();
                digest.BlockUpdate(certEncoded, 0, certEncoded.Length);
                byte[] hash = DigestUtilities.DoFinal(digest);

                EssCertID essCertid = new EssCertID(hash);

                Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
                    PkcsObjectIdentifiers.IdAASigningCertificate,
                    new DerSet(new SigningCertificate(essCertid)));

                signedAttrs[attr.AttrType] = attr;
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("Exception processing certificate.", e);
            }

            this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
        }
Пример #8
0
        internal static SignerInfoGenerator makeInfoGenerator(
            AsymmetricKeyParameter key,
            X509Certificate cert,
            string digestOID,

            Asn1.Cms.AttributeTable signedAttr,
            Asn1.Cms.AttributeTable unsignedAttr)
        {
            TspUtil.ValidateCertificate(cert);

            //
            // Add the ESSCertID attribute
            //
            IDictionary signedAttrs;

            if (signedAttr != null)
            {
                signedAttrs = signedAttr.ToDictionary();
            }
            else
            {
                signedAttrs = Platform.CreateHashtable();
            }

            //try
            //{
            //    byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());

            //    EssCertID essCertid = new EssCertID(hash);

            //    Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
            //        PkcsObjectIdentifiers.IdAASigningCertificate,
            //        new DerSet(new SigningCertificate(essCertid)));

            //    signedAttrs[attr.AttrType] = attr;
            //}
            //catch (CertificateEncodingException e)
            //{
            //    throw new TspException("Exception processing certificate.", e);
            //}
            //catch (SecurityUtilityException e)
            //{
            //    throw new TspException("Can't find a SHA-1 implementation.", e);
            //}


            string digestName    = CmsSignedHelper.Instance.GetDigestAlgName(digestOID);
            string signatureName = digestName + "with" + CmsSignedHelper.Instance.GetEncryptionAlgName(CmsSignedHelper.Instance.GetEncOid(key, digestOID));

            Asn1SignatureFactory sigfact = new Asn1SignatureFactory(signatureName, key);

            return(new SignerInfoGeneratorBuilder()
                   .WithSignedAttributeGenerator(
                       new DefaultSignedAttributeTableGenerator(
                           new Asn1.Cms.AttributeTable(signedAttrs)))
                   .WithUnsignedAttributeGenerator(
                       new SimpleAttributeTableGenerator(unsignedAttr))
                   .Build(sigfact, cert));
        }
        private CmsEnvelopedData doGenerate(
            ICmsTypedData content,
            ICipherBuilderWithKey<AlgorithmIdentifier> contentEncryptor)
        {
            Asn1EncodableVector recipientInfos = new Asn1EncodableVector();
            AlgorithmIdentifier encAlgId;
            Asn1OctetString encContent;

            MemoryOutputStream bOut = new MemoryOutputStream();

            try
            {
                ICipher cOut = contentEncryptor.BuildCipher(bOut);

                content.Write(cOut.Stream);

                cOut.Stream.Close();
            }
            catch (IOException e)
            {
                throw new CmsException(e.Message, e);
            }

            byte[] encryptedContent = bOut.ToArray();

            encAlgId = contentEncryptor.AlgorithmDetails;

            encContent = new BerOctetString(encryptedContent);

            ISymmetricKey encKey = contentEncryptor.Key;

            for (IEnumerator<IRecipientInfoGenerator> it = recipientInfoGenerators.GetEnumerator(); it.MoveNext();)
            {
                IRecipientInfoGenerator recipient = (IRecipientInfoGenerator)it.Current;

                recipientInfos.Add(recipient.Generate(encKey));
            }

            EncryptedContentInfo eci = new EncryptedContentInfo(
                            content.ContentType,
                            encAlgId,
                            encContent);

            Asn1Set unprotectedAttrSet = null;
            if (unprotectedAttributeGenerator != null)
            {
                Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(new Dictionary<string, object>());

                unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector());
            }

            ContentInfo contentInfo = new ContentInfo(
                    CmsObjectIdentifiers.EnvelopedData,
                    new EnvelopedData(originatorInfo, new DerSet(recipientInfos), eci, unprotectedAttrSet));

            return new CmsEnvelopedData(contentInfo);
        }
Пример #10
0
 public Asn1.Cms.AttributeTable GetAttributes(IDictionary parameters)
 {
     Asn1.Cms.AttributeTable tab = infoGen.signedGen.GetAttributes(parameters);
     if (tab[PkcsObjectIdentifiers.IdAASigningCertificateV2] == null)
     {
         return(tab.Add(PkcsObjectIdentifiers.IdAASigningCertificateV2, new SigningCertificateV2(essCertID)));
     }
     return(tab);
 }
Пример #11
0
//			internal Asn1.Cms.AttributeTable SignedAttributes
//            {
//				get { return _sAttr; }
//            }
//
//			internal Asn1.Cms.AttributeTable UnsignedAttributes
//            {
//				get { return _unsAttr; }
//            }

            internal SignerInfo ToSignerInfo(
                DerObjectIdentifier contentType)
            {
                AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(
                    new DerObjectIdentifier(this.DigestAlgOid), DerNull.Instance);
                AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(this.EncryptionAlgOid);

                byte[] hash = DigestUtilities.DoFinal(_digest);

                outer._digests.Add(_digestOID, hash.Clone());

                IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);

                Asn1.Cms.AttributeTable signed = (_sAttr != null)
//					?	_sAttr.GetAttributes(Collections.unmodifiableMap(parameters))
                                        ?       _sAttr.GetAttributes(parameters)
                                        :       null;

                Asn1Set signedAttr = outer.GetAttributeSet(signed);

                //
                // sig must be composed from the DER encoding.
                //
                byte[] bOutBytes;
                if (signedAttr != null)
                {
                    bOutBytes = signedAttr.GetDerEncoded();
                }
                else
                {
                    throw new Exception("signatures without signed attributes not implemented.");
                }

                _signature.BlockUpdate(bOutBytes, 0, bOutBytes.Length);

                Asn1OctetString encDigest = new DerOctetString(_signature.GenerateSignature());

                parameters = outer.GetBaseParameters(contentType, digAlgId, hash);
                parameters[CmsAttributeTableParameter.Signature] = encDigest.GetOctets().Clone();

                Asn1.Cms.AttributeTable unsigned = (_unsAttr != null)
//					?	_unsAttr.getAttributes(Collections.unmodifiableMap(parameters))
                                        ?       _unsAttr.GetAttributes(parameters)
                                        :       null;

                Asn1Set unsignedAttr = outer.GetAttributeSet(unsigned);

                X509Certificate         cert = this.Certificate;
                TbsCertificateStructure tbs  = TbsCertificateStructure.GetInstance(
                    Asn1Object.FromByteArray(cert.GetTbsCertificate()));
                IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(
                    tbs.Issuer, tbs.SerialNumber.Value);

                return(new SignerInfo(new SignerIdentifier(encSid), digAlgId,
                                      signedAttr, encAlgId, encDigest, unsignedAttr));
            }
Пример #12
0
 /**
  * add a signer with extra signed/unsigned attributes.
  *
  * @param key signing key to use
  * @param subjectKeyID subjectKeyID of corresponding public key
  * @param digestOID digest algorithm OID
  * @param signedAttr table of attributes to be included in signature
  * @param unsignedAttr table of attributes to be included as unsigned
  */
 public void AddSigner(
     AsymmetricKeyParameter privateKey,
     byte[]                                  subjectKeyID,
     string digestOID,
     Asn1.Cms.AttributeTable signedAttr,
     Asn1.Cms.AttributeTable unsignedAttr)
 {
     AddSigner(privateKey, subjectKeyID, Helper.GetEncOid(privateKey, digestOID), digestOID,
               signedAttr, unsignedAttr);
 }
Пример #13
0
        private Asn1Set getAttributeSet(
            Asn1.Cms.AttributeTable attr)
        {
            if (attr != null)
            {
                return(new DerSet(attr.ToAsn1EncodableVector()));
            }

            return(null);
        }
 /**
  * add a signer with extra signed/unsigned attributes.
  *
  * @param key signing key to use
  * @param cert certificate containing corresponding public key
  * @param digestOID digest algorithm OID
  * @param signedAttr table of attributes to be included in signature
  * @param unsignedAttr table of attributes to be included as unsigned
  */
 public void AddSigner(
     AsymmetricKeyParameter privateKey,
     X509Certificate cert,
     string digestOID,
     Asn1.Cms.AttributeTable signedAttr,
     Asn1.Cms.AttributeTable unsignedAttr)
 {
     AddSigner(privateKey, cert, GetEncOid(privateKey, digestOID), digestOID,
               signedAttr, unsignedAttr);
 }
            public Asn1.Cms.AttributeTable GetAttributes(IDictionary parameters)
            {
                CmsAttributeTableGenerator attrGen = new DefaultSignedAttributeTableGenerator();

                Asn1.Cms.AttributeTable table = attrGen.GetAttributes(parameters);
                table = table.Add(PkcsObjectIdentifiers.IdAASigningCertificate, new SigningCertificate(EssCertID));
                table = table.Add(PkcsObjectIdentifiers.IdAASigningCertificateV2, new SigningCertificateV2(new EssCertIDv2[] { EssCertIDv2 }));

                return(table);
            }
 /**
  * add a signer with extra signed/unsigned attributes.
  * @throws NoSuchAlgorithmException
  * @throws InvalidKeyException
  */
 public void AddSigner(
     AsymmetricKeyParameter privateKey,
     X509Certificate cert,
     string digestOid,
     Asn1.Cms.AttributeTable signedAttr,
     Asn1.Cms.AttributeTable unsignedAttr)
 {
     AddSigner(privateKey, cert, digestOid,
               new DefaultSignedAttributeTableGenerator(signedAttr),
               new SimpleAttributeTableGenerator(unsignedAttr));
 }
 /**
  * add a signer with extra signed/unsigned attributes.
  * @throws NoSuchAlgorithmException
  * @throws InvalidKeyException
  */
 public void AddSigner(
     AsymmetricKeyParameter privateKey,
     byte[]                                  subjectKeyID,
     string digestOid,
     Asn1.Cms.AttributeTable signedAttr,
     Asn1.Cms.AttributeTable unsignedAttr)
 {
     AddSigner(privateKey, subjectKeyID, digestOid,
               new DefaultSignedAttributeTableGenerator(signedAttr),
               new SimpleAttributeTableGenerator(unsignedAttr));
 }
Пример #18
0
        /**
         * create with a signer with extra signed/unsigned attributes.
         */
        public TimeStampTokenGenerator(
            AsymmetricKeyParameter key,
            X509Certificate cert,
            string digestOID,
            string tsaPolicyOID,
            Asn1.Cms.AttributeTable signedAttr,
            Asn1.Cms.AttributeTable unsignedAttr)
        {
            this.key          = key;
            this.cert         = cert;
            this.digestOID    = digestOID;
            this.tsaPolicyOID = tsaPolicyOID;
            this.unsignedAttr = unsignedAttr;

            TspUtil.ValidateCertificate(cert);

            //
            // Add the ESSCertID attribute
            //
            IDictionary signedAttrs;

            if (signedAttr != null)
            {
                signedAttrs = signedAttr.ToDictionary();
            }
            else
            {
                signedAttrs = Platform.CreateHashtable();
            }

            try
            {
                byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());

                EssCertID essCertid = new EssCertID(hash);

                Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
                    PkcsObjectIdentifiers.IdAASigningCertificate,
                    new DerSet(new SigningCertificate(essCertid)));

                signedAttrs[attr.AttrType] = attr;
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("Exception processing certificate.", e);
            }
            catch (SecurityUtilityException e)
            {
                throw new TspException("Can't find a SHA-1 implementation.", e);
            }

            this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
        }
Пример #19
0
 /**
  * create with a signer with extra signed/unsigned attributes.
  */
 public TimeStampTokenGenerator(
     AsymmetricKeyParameter key,
     X509Certificate cert,
     string digestOID,
     string tsaPolicyOID,
     Asn1.Cms.AttributeTable signedAttr,
     Asn1.Cms.AttributeTable unsignedAttr) : this(
         makeInfoGenerator(key, cert, digestOID, signedAttr, unsignedAttr),
         Asn1DigestFactory.Get(OiwObjectIdentifiers.IdSha1),
         tsaPolicyOID != null?new DerObjectIdentifier(tsaPolicyOID):null, false)
 {
 }
Пример #20
0
 private void doAddSigner(
     AsymmetricKeyParameter privateKey,
     SignerIdentifier signerIdentifier,
     string encryptionOID,
     string digestOID,
     CmsAttributeTableGenerator signedAttrGen,
     CmsAttributeTableGenerator unsignedAttrGen,
     Asn1.Cms.AttributeTable baseSignedTable)
 {
     signerInfs.Add(new SignerInf(this, privateKey, signerIdentifier, digestOID, encryptionOID,
                                  signedAttrGen, unsignedAttrGen, baseSignedTable));
 }
		/**
		 * create with a signer with extra signed/unsigned attributes.
		 */
		public TimeStampTokenGenerator(
			AsymmetricKeyParameter	key,
			X509Certificate			cert,
			string					digestOID,
			string					tsaPolicyOID,
			Asn1.Cms.AttributeTable	signedAttr,
			Asn1.Cms.AttributeTable	unsignedAttr)
		{
			this.key = key;
			this.cert = cert;
			this.digestOID = digestOID;
			this.tsaPolicyOID = tsaPolicyOID;
			this.unsignedAttr = unsignedAttr;

			TspUtil.ValidateCertificate(cert);

			//
			// Add the ESSCertID attribute
			//
			IDictionary signedAttrs;
			if (signedAttr != null)
			{
				signedAttrs = signedAttr.ToDictionary();
			}
			else
			{
				signedAttrs = Platform.CreateHashtable();
			}

			try
			{
				byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());

				EssCertID essCertid = new EssCertID(hash);

				Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
					PkcsObjectIdentifiers.IdAASigningCertificate,
					new DerSet(new SigningCertificate(essCertid)));

				signedAttrs[attr.AttrType] = attr;
			}
			catch (CertificateEncodingException e)
			{
				throw new TspException("Exception processing certificate.", e);
			}
			catch (SecurityUtilityException e)
			{
				throw new TspException("Can't find a SHA-1 implementation.", e);
			}

			this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
		}
 /**
  * add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
  *
  * @param key signing key to use
  * @param cert certificate containing corresponding public key
  * @param encryptionOID digest encryption algorithm OID
  * @param digestOID digest algorithm OID
  * @param signedAttr table of attributes to be included in signature
  * @param unsignedAttr table of attributes to be included as unsigned
  */
 public void AddSigner(
     IAsymmetricKeyParameter privateKey,
     X509Certificate cert,
     string encryptionOID,
     string digestOID,
     Asn1.Cms.AttributeTable signedAttr,
     Asn1.Cms.AttributeTable unsignedAttr)
 {
     doAddSigner(privateKey, GetSignerIdentifier(cert), encryptionOID, digestOID,
                 new DefaultSignedAttributeTableGenerator(signedAttr),
                 new SimpleAttributeTableGenerator(unsignedAttr),
                 signedAttr);
 }
Пример #23
0
 /**
  * add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
  *
  * @param key signing key to use
  * @param subjectKeyID subjectKeyID of corresponding public key
  * @param encryptionOID digest encryption algorithm OID
  * @param digestOID digest algorithm OID
  * @param signedAttr table of attributes to be included in signature
  * @param unsignedAttr table of attributes to be included as unsigned
  */
 public void AddSigner(
     AsymmetricKeyParameter privateKey,
     byte[]                                  subjectKeyID,
     string encryptionOID,
     string digestOID,
     Asn1.Cms.AttributeTable signedAttr,
     Asn1.Cms.AttributeTable unsignedAttr)
 {
     doAddSigner(privateKey, GetSignerIdentifier(subjectKeyID), encryptionOID, digestOID,
                 new DefaultSignedAttributeTableGenerator(signedAttr),
                 new SimpleAttributeTableGenerator(unsignedAttr),
                 signedAttr);
 }
        /**
         * add a signer with extra signed/unsigned attributes.
         */
        public void AddSigner(
            AsymmetricKeyParameter privateKey,
            byte[]                                  subjectKeyID,
            string digestOID,
            Asn1.Cms.AttributeTable signedAttr,
            Asn1.Cms.AttributeTable unsignedAttr)
        {
            string encOID = GetEncOid(privateKey, digestOID);

            signerInfs.Add(new SignerInf(this, privateKey, subjectKeyID, digestOID, encOID,
                                         new DefaultSignedAttributeTableGenerator(signedAttr),
                                         new SimpleAttributeTableGenerator(unsignedAttr),
                                         signedAttr));
        }
Пример #25
0
        private void VerifyContentHint(SignerInformation signInfo)
        {
            Asn1.Cms.AttributeTable attrTable = signInfo.UnsignedAttributes;

            Asn1.Cms.Attribute attr = attrTable[CmsAttributes.ContentHint];

            Assert.AreEqual(1, attr.AttrValues.Count);

            Asn1EncodableVector v = new Asn1EncodableVector(
                new DerUtf8String("Content Hints Description Buffer"),
                CmsObjectIdentifiers.Data);

            Assert.IsTrue(attr.AttrValues[0].Equals(new DerSequence(v)));
        }
        private CmsEncryptedData doGenerate(
            ICmsTypedData content,
            ICipherBuilder <AlgorithmIdentifier> contentEncryptor)
        {
            AlgorithmIdentifier encAlgId;
            Asn1OctetString     encContent;

            MemoryOutputStream bOut = new MemoryOutputStream();

            try
            {
                ICipher cipher = contentEncryptor.BuildCipher(bOut);

                content.Write(cipher.Stream);

                cipher.Stream.Close();
            }
            catch (IOException)
            {
                throw new CmsException("");
            }

            byte[] encryptedContent = bOut.ToArray();

            encAlgId = contentEncryptor.AlgorithmDetails;

            encContent = new BerOctetString(encryptedContent);

            EncryptedContentInfo eci = new EncryptedContentInfo(
                content.ContentType,
                encAlgId,
                encContent);

            Asn1Set unprotectedAttrSet = null;

            if (unprotectedAttributeGenerator != null)
            {
                Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(new Dictionary <string, object>());

                unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector());
            }

            ContentInfo contentInfo = new ContentInfo(
                CmsObjectIdentifiers.EncryptedData,
                new EncryptedData(eci, unprotectedAttrSet));

            return(new CmsEncryptedData(contentInfo));
        }
Пример #27
0
 /**
  * Protected constructor. In some cases clients have their own idea about how to encode
  * the signed attributes and calculate the signature. This constructor is to allow developers
  * to deal with that by extending off the class and overridng methods like getSignedAttributes().
  *
  * @param baseInfo the SignerInformation to base this one on.
  */
 protected SignerInformation(SignerInformation baseInfo)
 {
     this.info               = baseInfo.info;
     this.contentType        = baseInfo.contentType;
     this.isCounterSignature = baseInfo.IsCounterSignature;
     this.sid                    = baseInfo.SignerID;
     this.digestAlgorithm        = info.DigestAlgorithm;
     this.signedAttributeSet     = info.AuthenticatedAttributes;
     this.unsignedAttributeSet   = info.UnauthenticatedAttributes;
     this.encryptionAlgorithm    = info.DigestEncryptionAlgorithm;
     this.signature              = info.EncryptedDigest.GetOctets();
     this.content                = baseInfo.content;
     this.resultDigest           = baseInfo.resultDigest;
     this.signedAttributeTable   = baseInfo.signedAttributeTable;
     this.unsignedAttributeTable = baseInfo.unsignedAttributeTable;
 }
Пример #28
0
 internal SignerInf(
     CmsSignedGenerator outer,
     ISignatureFactory sigCalc,
     SignerIdentifier signerIdentifier,
     CmsAttributeTableGenerator sAttr,
     CmsAttributeTableGenerator unsAttr,
     Asn1.Cms.AttributeTable baseSignedTable)
 {
     this.outer            = outer;
     this.sigCalc          = sigCalc;
     this.signerIdentifier = signerIdentifier;
     this.digestOID        = new DefaultDigestAlgorithmIdentifierFinder().find((AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id;
     this.encOID           = ((AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id;
     this.sAttr            = sAttr;
     this.unsAttr          = unsAttr;
     this.baseSignedTable  = baseSignedTable;
 }
Пример #29
0
        /**
         * Fetches the signature time-stamp attributes from a SignerInformation object.
         * Checks that the MessageImprint for each time-stamp matches the signature field.
         * (see RFC 3161 Appendix A).
         *
         * @param signerInfo a SignerInformation to search for time-stamps
         * @return a collection of TimeStampToken objects
         * @throws TSPValidationException
         */
        public static ICollection GetSignatureTimestamps(
            SignerInformation signerInfo)
        {
            IList timestamps = Platform.CreateArrayList();

            Asn1.Cms.AttributeTable unsignedAttrs = signerInfo.UnsignedAttributes;
            if (unsignedAttrs != null)
            {
                foreach (Asn1.Cms.Attribute tsAttr in unsignedAttrs.GetAll(
                             PkcsObjectIdentifiers.IdAASignatureTimeStampToken))
                {
                    foreach (Asn1Encodable asn1 in tsAttr.AttrValues)
                    {
                        try
                        {
                            Asn1.Cms.ContentInfo contentInfo = Asn1.Cms.ContentInfo.GetInstance(
                                asn1.ToAsn1Object());
                            TimeStampToken     timeStampToken = new TimeStampToken(contentInfo);
                            TimeStampTokenInfo tstInfo        = timeStampToken.TimeStampInfo;

                            byte[] expectedDigest = DigestUtilities.CalculateDigest(
                                GetDigestAlgName(tstInfo.MessageImprintAlgOid),
                                signerInfo.GetSignature());

                            if (!Arrays.ConstantTimeAreEqual(expectedDigest, tstInfo.GetMessageImprintDigest()))
                            {
                                throw new TspValidationException("Incorrect digest in message imprint");
                            }

                            timestamps.Add(timeStampToken);
                        }
                        catch (SecurityUtilityException)
                        {
                            throw new TspValidationException("Unknown hash algorithm specified in timestamp");
                        }
                        catch (Exception)
                        {
                            throw new TspValidationException("Timestamp could not be parsed");
                        }
                    }
                }
            }

            return(timestamps);
        }
Пример #30
0
        private void basicSha256Test(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            var sInfoGenerator = makeInfoGenerator(privateKey, cert, TspAlgorithms.Sha256, null, null);
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                sInfoGenerator,
                Asn1DigestFactory.Get(NistObjectIdentifiers.IdSha256), new DerObjectIdentifier("1.2"), true);


            tsTokenGen.SetCertificates(certs);

            TimeStampRequestGenerator reqGen  = new TimeStampRequestGenerator();
            TimeStampRequest          request = reqGen.Generate(TspAlgorithms.Sha256, new byte[32], BigInteger.ValueOf(100));

            TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed);

            TimeStampResponse tsResp = tsRespGen.Generate(request, new BigInteger("23"), DateTime.Now);

            Assert.AreEqual((int)PkiStatus.Granted, tsResp.Status);

            tsResp = new TimeStampResponse(tsResp.GetEncoded());

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            Asn1.Cms.AttributeTable table = tsToken.SignedAttributes;

            Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificateV2]);

            Asn1DigestFactory digCalc = Asn1DigestFactory.Get(NistObjectIdentifiers.IdSha256);
            IStreamCalculator calc    = digCalc.CreateCalculator();

            using (Stream s = calc.Stream)
            {
                var crt = cert.GetEncoded();
                s.Write(crt, 0, crt.Length);
            }

            byte[] certHash = ((SimpleBlockResult)calc.GetResult()).Collect();

            SigningCertificateV2 sigCertV2 = SigningCertificateV2.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificateV2].AttrValues[0]);

            Assert.IsTrue(Arrays.AreEqual(certHash, sigCertV2.GetCerts()[0].GetCertHash()));
        }
 internal SignerInf(
     CmsSignedGenerator outer,
     AsymmetricKeyParameter key,
     byte[]                                          keyIdentifier,
     string digestOID,
     string encOID,
     CmsAttributeTableGenerator sAttr,
     CmsAttributeTableGenerator unsAttr,
     Asn1.Cms.AttributeTable baseSignedTable)
 {
     this.outer           = outer;
     this.key             = key;
     this.keyIdentifier   = keyIdentifier;
     this.digestOID       = digestOID;
     this.encOID          = encOID;
     this.sAttr           = sAttr;
     this.unsAttr         = unsAttr;
     this.baseSignedTable = baseSignedTable;
 }
			internal SignerInf(
                CmsSignedGenerator			outer,
	            AsymmetricKeyParameter		key,
	            SignerIdentifier			signerIdentifier,
	            string						digestOID,
	            string						encOID,
	            CmsAttributeTableGenerator	sAttr,
	            CmsAttributeTableGenerator	unsAttr,
	            Asn1.Cms.AttributeTable		baseSignedTable)
	        {
                this.outer = outer;
                this.key = key;
                this.signerIdentifier = signerIdentifier;
                this.digestOID = digestOID;
                this.encOID = encOID;
	            this.sAttr = sAttr;
	            this.unsAttr = unsAttr;
	            this.baseSignedTable = baseSignedTable;
            }
 internal SignerInf(
     CmsSignedGenerator outer,
     AsymmetricKeyParameter key,
     X509Certificate cert,
     string digestOID,
     string encOID,
     CmsAttributeTableGenerator sAttr,
     CmsAttributeTableGenerator unsAttr,
     Asn1.Cms.AttributeTable baseSignedTable)
 {
     this.outer           = outer;
     this.key             = key;
     this.cert            = cert;
     this.digestOID       = digestOID;
     this.encOID          = encOID;
     this.sAttr           = sAttr;
     this.unsAttr         = unsAttr;
     this.baseSignedTable = baseSignedTable;
 }
			internal SignerInf(
                CmsSignedGenerator			outer,
	            AsymmetricKeyParameter		key,
	            SignerIdentifier			signerIdentifier,
	            string						digestOID,
	            string						encOID,
	            CmsAttributeTableGenerator	sAttr,
	            CmsAttributeTableGenerator	unsAttr,
	            Asn1.Cms.AttributeTable		baseSignedTable)
	        {
                string digestName = Helper.GetDigestAlgName(digestOID);

                string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);

                this.outer = outer;
                this.sigCalc = new Asn1SignatureFactory(signatureName, key);
                this.signerIdentifier = signerIdentifier;
                this.digestOID = digestOID;
                this.encOID = encOID;
	            this.sAttr = sAttr;
	            this.unsAttr = unsAttr;
	            this.baseSignedTable = baseSignedTable;
            }
			internal SignerInfo ToSignerInfo(
                DerObjectIdentifier	contentType,
                CmsProcessable		content,
				SecureRandom		random)
            {
                AlgorithmIdentifier digAlgId = DigestAlgorithmID;
				string digestName = Helper.GetDigestAlgName(digestOID);

				string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);
				ISigner sig = Helper.GetSignatureInstance(signatureName);

                byte[] hash;
                if (outer._digests.Contains(digestOID))
                {
                    hash = (byte[])outer._digests[digestOID];
                }
                else
                {
                    IDigest dig = Helper.GetDigestInstance(digestName);
                    if (content != null)
                    {
                        content.Write(new DigOutputStream(dig));
                    }
                    hash = DigestUtilities.DoFinal(dig);
                    outer._digests.Add(digestOID, hash.Clone());
                }

				sig.Init(true, new ParametersWithRandom(key, random));
#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT
				Stream sigStr = new SigOutputStream(sig);
#else
				Stream sigStr = new BufferedStream(new SigOutputStream(sig));
#endif

				Asn1Set signedAttr = null;
				if (sAttr != null)
				{
					IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);

//					Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters));
					Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters);

                    if (contentType == null) //counter signature
                    {
                        if (signed != null && signed[CmsAttributes.ContentType] != null)
                        {
                            IDictionary tmpSigned = signed.ToDictionary();
                            tmpSigned.Remove(CmsAttributes.ContentType);
                            signed = new Asn1.Cms.AttributeTable(tmpSigned);
                        }
                    }

					// TODO Validate proposed signed attributes

					signedAttr = outer.GetAttributeSet(signed);

					// sig must be composed from the DER encoding.
					new DerOutputStream(sigStr).WriteObject(signedAttr);
				}
                else if (content != null)
                {
					// TODO Use raw signature of the hash value instead
					content.Write(sigStr);
                }

				sigStr.Close();
				byte[] sigBytes = sig.GenerateSignature();

				Asn1Set unsignedAttr = null;
				if (unsAttr != null)
				{
					IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash);
					baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();

//					Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters));
					Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters);

					// TODO Validate proposed unsigned attributes

					unsignedAttr = outer.GetAttributeSet(unsigned);
				}

				// TODO[RSAPSS] Need the ability to specify non-default parameters
				Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName);
				AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(
					new DerObjectIdentifier(encOID), sigX509Parameters);
				
                return new SignerInfo(signerIdentifier, digAlgId,
                    signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr);
            }
		/**
		* return a table of the unauthenticated attributes indexed by
		* the OID of the attribute.
		* @exception java.io.IOException
		*/
		public Asn1.Cms.AttributeTable GetUnauthAttrs()
		{
			if (unauthAttrs == null && unauthAttrNotRead)
			{
				Asn1SetParser s = authData.GetUnauthAttrs();

				unauthAttrNotRead = false;

				if (s != null)
				{
					Asn1EncodableVector v = new Asn1EncodableVector();

					IAsn1Convertible o;
					while ((o = s.ReadObject()) != null)
					{
						Asn1SequenceParser seq = (Asn1SequenceParser)o;

						v.Add(seq.ToAsn1Object());
					}

					unauthAttrs = new Asn1.Cms.AttributeTable(new DerSet(v));
				}
			}

			return unauthAttrs;
		}
Пример #37
0
			internal Asn1.Cms.SignerInfo ToSignerInfo(
                DerObjectIdentifier	contentType,
                CmsProcessable		content,
				SecureRandom		random,
				bool				isCounterSignature)
            {
                AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(
                    new DerObjectIdentifier(this.DigestAlgOid), DerNull.Instance);
				AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(this.EncryptionAlgOid);
				string digestName = Helper.GetDigestAlgName(digestOID);
				string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);
				ISigner sig = Helper.GetSignatureInstance(signatureName);
				IDigest dig = Helper.GetDigestInstance(digestName);

                byte[] hash = null;

                if (content != null)
                {
                    content.Write(new DigOutputStream(dig));

					hash = DigestUtilities.DoFinal(dig);

					outer._digests.Add(digestOID, hash.Clone());
				}

				IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);
				Asn1.Cms.AttributeTable signed = (sAttr != null)
//					?	sAttr.GetAttributes(Collections.unmodifiableMap(parameters))
					?	sAttr.GetAttributes(parameters)
					:	null;

				if (isCounterSignature)
				{
					Hashtable ats = signed.ToHashtable();

					ats.Remove(CmsAttributes.ContentType);

					signed = new Asn1.Cms.AttributeTable(ats);
				}

				Asn1Set signedAttr = outer.GetAttributeSet(signed);


				//
                // sig must be composed from the DER encoding.
                //
				byte[] tmp;
				if (signedAttr != null)
                {
					tmp = signedAttr.GetEncoded(Asn1Encodable.Der);
                }
                else
                {
					MemoryStream bOut = new MemoryStream();
					content.Write(bOut);
					tmp = bOut.ToArray();
                }

				sig.Init(true, new ParametersWithRandom(key, random));
				sig.BlockUpdate(tmp, 0, tmp.Length);

				Asn1OctetString encDigest = new DerOctetString(sig.GenerateSignature());

				IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash);
				baseParameters[CmsAttributeTableParameter.Signature] = encDigest.GetOctets().Clone();

				Asn1.Cms.AttributeTable unsigned = (unsAttr != null)
//					?	unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters))
					?	unsAttr.GetAttributes(baseParameters)
					:	null;

				Asn1Set unsignedAttr = outer.GetAttributeSet(unsigned);

                X509Certificate cert = this.GetCertificate();
	            SignerIdentifier identifier;
	            if (cert != null)
	            {
					TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
						Asn1Object.FromByteArray(cert.GetTbsCertificate()));
					Asn1.Cms.IssuerAndSerialNumber encSid = new Asn1.Cms.IssuerAndSerialNumber(
						tbs.Issuer, tbs.SerialNumber.Value);
	            	identifier = new SignerIdentifier(encSid);
	            }
	            else
	            {
	                identifier = new SignerIdentifier(new DerOctetString(keyIdentifier));
	            }

                return new Asn1.Cms.SignerInfo(identifier, digAlgId,
                    signedAttr, encAlgId, encDigest, unsignedAttr);
            }
        /**
         * return a table of the unprotected attributes indexed by
         * the OID of the attribute.
         * @throws IOException
         */
        public Asn1.Cms.AttributeTable GetUnprotectedAttributes()
        {
            if (_unprotectedAttributes == null && _attrNotRead)
            {
                Asn1SetParser asn1Set = this.envelopedData.GetUnprotectedAttrs();

                _attrNotRead = false;

                if (asn1Set != null)
                {
                    Asn1EncodableVector v = new Asn1EncodableVector();
                    IAsn1Convertible o;

                    while ((o = asn1Set.ReadObject()) != null)
                    {
                        Asn1SequenceParser seq = (Asn1SequenceParser)o;

                        v.Add(seq.ToAsn1Object());
                    }

                    _unprotectedAttributes = new Asn1.Cms.AttributeTable(new DerSet(v));
                }
            }

            return _unprotectedAttributes;
        }
 internal SignerInf(
     CmsSignedGenerator outer,
     ISignatureFactory sigCalc,
     SignerIdentifier signerIdentifier,
     CmsAttributeTableGenerator sAttr,
     CmsAttributeTableGenerator unsAttr,
     Asn1.Cms.AttributeTable baseSignedTable)
 {
     this.outer = outer;
     this.sigCalc = sigCalc;
     this.signerIdentifier = signerIdentifier;
     this.digestOID = new DefaultDigestAlgorithmIdentifierFinder().find((AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id;
     this.encOID = ((AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id;
     this.sAttr = sAttr;
     this.unsAttr = unsAttr;
     this.baseSignedTable = baseSignedTable;
 }
			public SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier digestAlgorithm,
        		byte[] calculatedDigest)
			{
				try
				{
					string digestName = Helper.GetDigestAlgName(_digestOID);
					string signatureName = digestName + "with" + _encName;

//					AlgorithmIdentifier digAlgId = DigestAlgorithmID;
//
//					byte[] hash = (byte[])outer._messageHashes[Helper.GetDigestAlgName(this._digestOID)];
//					outer._digests[_digestOID] = hash.Clone();

					byte[] bytesToSign = calculatedDigest;

					/* 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;
					if (_sAttr != null)
					{
						IDictionary parameters = outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest);

//						Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(Collections.unmodifiableMap(parameters));
						Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(parameters);

                        if (contentType == null) //counter signature
                        {
                            if (signed != null && signed[CmsAttributes.ContentType] != null)
                            {
                                IDictionary tmpSigned = signed.ToDictionary();
                                tmpSigned.Remove(CmsAttributes.ContentType);
                                signed = new Asn1.Cms.AttributeTable(tmpSigned);
                            }
                        }

                        signedAttr = outer.GetAttributeSet(signed);

                		// sig must be composed from the DER encoding.
						bytesToSign = signedAttr.GetEncoded(Asn1Encodable.Der);
					}
					else
					{
						// Note: Need to use raw signatures here since we have already calculated the digest
						if (_encName.Equals("RSA"))
						{
							DigestInfo dInfo = new DigestInfo(digestAlgorithm, calculatedDigest);
							bytesToSign = dInfo.GetEncoded(Asn1Encodable.Der);
						}
					}

					_sig.BlockUpdate(bytesToSign, 0, bytesToSign.Length);
					byte[] sigBytes = _sig.GenerateSignature();

					Asn1Set unsignedAttr = null;
					if (_unsAttr != null)
					{
						IDictionary parameters = outer.GetBaseParameters(
							contentType, digestAlgorithm, calculatedDigest);
						parameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();

//						Asn1.Cms.AttributeTable unsigned = _unsAttr.getAttributes(Collections.unmodifiableMap(parameters));
						Asn1.Cms.AttributeTable unsigned = _unsAttr.GetAttributes(parameters);

						unsignedAttr = outer.GetAttributeSet(unsigned);
					}

					// TODO[RSAPSS] Need the ability to specify non-default parameters
					Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName);
					AlgorithmIdentifier digestEncryptionAlgorithm = CmsSignedGenerator.GetEncAlgorithmIdentifier(
						new DerObjectIdentifier(_encOID), sigX509Parameters);

					return new SignerInfo(_signerIdentifier, digestAlgorithm,
						signedAttr, digestEncryptionAlgorithm, new DerOctetString(sigBytes), unsignedAttr);
				}
	            catch (IOException e)
	            {
	                throw new CmsStreamException("encoding error.", e);
	            }
	            catch (SignatureException e)
	            {
	                throw new CmsStreamException("error creating signature.", e);
	            }
            }