public AttributeCertificateInfo GenerateAttributeCertificateInfo()
        {
            if ((serialNumber == null) || (signature == null)
                || (issuer == null) || (startDate == null) || (endDate == null)
                || (holder == null) || (attributes == null))
            {
                throw new InvalidOperationException("not all mandatory fields set in V2 AttributeCertificateInfo generator");
            }

            Asn1EncodableVector v = new Asn1EncodableVector(
                version, holder, issuer, signature, serialNumber);

            //
            // before and after dates => AttCertValidityPeriod
            //
            v.Add(new AttCertValidityPeriod(startDate, endDate));

            // Attributes
            v.Add(new DerSequence(attributes));

            if (issuerUniqueID != null)
            {
                v.Add(issuerUniqueID);
            }

            if (extensions != null)
            {
                v.Add(extensions);
            }

            return AttributeCertificateInfo.GetInstance(new DerSequence(v));
        }
Exemplo n.º 2
0
		/**
         * Constructor for elliptic curves over binary fields
         * <code>F<sub>2<sup>m</sup></sub></code>.
         * @param m  The exponent <code>m</code> of
         * <code>F<sub>2<sup>m</sup></sub></code>.
         * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
         * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
         * represents the reduction polynomial <code>f(z)</code>.
         * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
         * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
         * represents the reduction polynomial <code>f(z)</code>.
         * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
         * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
         * represents the reduction polynomial <code>f(z)</code>..
         */
		public X9FieldID(
			int m,
			int k1,
			int k2,
			int k3)
		{
			this.id = X9ObjectIdentifiers.CharacteristicTwoField;

			Asn1EncodableVector fieldIdParams = new Asn1EncodableVector(new DerInteger(m));

			if(k2 == 0)
			{
				if(k3 != 0)
					throw new ArgumentException("inconsistent k values");

				fieldIdParams.Add(
					X9ObjectIdentifiers.TPBasis,
					new DerInteger(k1));
			}
			else
			{
				if(k2 <= k1 || k3 <= k2)
					throw new ArgumentException("inconsistent k values");

				fieldIdParams.Add(
					X9ObjectIdentifiers.PPBasis,
					new DerSequence(
						new DerInteger(k1),
						new DerInteger(k2),
						new DerInteger(k3)));
			}

			this.parameters = new DerSequence(fieldIdParams);
		}
Exemplo n.º 3
0
		private void AddOptional(Asn1EncodableVector v, int tagNo, Asn1Encodable obj)
		{
			if (obj != null)
			{
				v.Add(new DerTaggedObject(true, tagNo, obj));
			}
		}
Exemplo n.º 4
0
        private static Asn1EncodableVector ConvertVector(IList numbers)
        {
            Asn1EncodableVector av = new Asn1EncodableVector();

            foreach (object o in numbers)
            {
                DerInteger di;

                if (o is BigInteger)
                {
                    di = new DerInteger((BigInteger)o);
                }
                else if (o is int)
                {
                    di = new DerInteger((int)o);
                }
                else
                {
                    throw new ArgumentException();
                }

                av.Add(di);
            }
            return av;
        }
Exemplo n.º 5
0
		/**
		 * Constructor for elliptic curves over binary fields
		 * <code>F<sub>2<sup>m</sup></sub></code>.
		 * @param m  The exponent <code>m</code> of
		 * <code>F<sub>2<sup>m</sup></sub></code>.
		 * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
		 * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
		 * represents the reduction polynomial <code>f(z)</code>.
		 * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
		 * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
		 * represents the reduction polynomial <code>f(z)</code>.
		 * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
		 * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
		 * represents the reduction polynomial <code>f(z)</code>..
		 */
		public X9FieldID(
			int m,
			int k1,
			int k2,
			int k3)
		{
			this.id = X9ObjectIdentifiers.CharacteristicTwoField;

			Asn1EncodableVector fieldIdParams = new Asn1EncodableVector(new DerInteger(m));

			if (k2 == 0)
			{
				fieldIdParams.Add(
					X9ObjectIdentifiers.TPBasis,
					new DerInteger(k1));
			}
			else
			{
				fieldIdParams.Add(
					X9ObjectIdentifiers.PPBasis,
					new DerSequence(
						new DerInteger(k1),
						new DerInteger(k2),
						new DerInteger(k3)));
			}

			this.parameters = new DerSequence(fieldIdParams);
		}
Exemplo n.º 6
0
		/**
		 * <pre>
		 * Challenge ::= SEQUENCE {
		 *                 owf                 AlgorithmIdentifier  OPTIONAL,
		 *
		 *                 -- MUST be present in the first Challenge; MAY be omitted in
		 *                 -- any subsequent Challenge in POPODecKeyChallContent (if
		 *                 -- omitted, then the owf used in the immediately preceding
		 *                 -- Challenge is to be used).
		 *
		 *                 witness             OCTET STRING,
		 *                 -- the result of applying the one-way function (owf) to a
		 *                 -- randomly-generated INTEGER, A.  [Note that a different
		 *                 -- INTEGER MUST be used for each Challenge.]
		 *                 challenge           OCTET STRING
		 *                 -- the encryption (under the public key for which the cert.
		 *                 -- request is being made) of Rand, where Rand is specified as
		 *                 --   Rand ::= SEQUENCE {
		 *                 --      int      INTEGER,
		 *                 --       - the randomly-generated INTEGER A (above)
		 *                 --      sender   GeneralName
		 *                 --       - the sender's name (as included in PKIHeader)
		 *                 --   }
		 *      }
		 * </pre>
		 * @return a basic ASN.1 object representation.
		 */
		public override Asn1Object ToAsn1Object()
		{
			Asn1EncodableVector v = new Asn1EncodableVector();
			v.AddOptional(owf);
			v.Add(witness);
			v.Add(challenge);
			return new DerSequence(v);
		}
Exemplo n.º 7
0
		/**
		 * <pre>
		 * OobCertHash ::= SEQUENCE {
		 *                      hashAlg     [0] AlgorithmIdentifier     OPTIONAL,
		 *                      certId      [1] CertId                  OPTIONAL,
		 *                      hashVal         BIT STRING
		 *                      -- hashVal is calculated over the Der encoding of the
		 *                      -- self-signed certificate with the identifier certID.
		 *       }
		 * </pre>
		 * @return a basic ASN.1 object representation.
		 */
		public override Asn1Object ToAsn1Object()
		{
			Asn1EncodableVector v = new Asn1EncodableVector();
			AddOptional(v, 0, hashAlg);
			AddOptional(v, 1, certId);
			v.Add(hashVal);
			return new DerSequence(v);
		}
Exemplo n.º 8
0
		/**
         * Produce an object suitable for an Asn1OutputStream.
         * <pre>
         * OcspRequest     ::=     Sequence {
         *     tbsRequest                  TBSRequest,
         *     optionalSignature   [0]     EXPLICIT Signature OPTIONAL }
         * </pre>
         */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(tbsRequest);

			if (optionalSignature != null)
            {
                v.Add(new DerTaggedObject(true, 0, optionalSignature));
            }

			return new DerSequence(v);
        }
Exemplo n.º 9
0
		/**
         * Produce an object suitable for an Asn1OutputStream.
         * <pre>
         * OcspResponse ::= Sequence {
         *     responseStatus         OcspResponseStatus,
         *     responseBytes          [0] EXPLICIT ResponseBytes OPTIONAL }
         * </pre>
         */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(responseStatus);

			if (responseBytes != null)
            {
                v.Add(new DerTaggedObject(true, 0, responseBytes));
            }

			return new DerSequence(v);
        }
Exemplo n.º 10
0
		/**
		 * <pre>
		 * MacData ::= SEQUENCE {
		 *     mac      DigestInfo,
		 *     macSalt  OCTET STRING,
		 *     iterations INTEGER DEFAULT 1
		 *     -- Note: The default is for historic reasons and its use is deprecated. A
		 *     -- higher value, like 1024 is recommended.
		 * </pre>
		 * @return the basic DERObject construction.
		 */
		public override Asn1Object ToAsn1Object()
        {
			Asn1EncodableVector v = new Asn1EncodableVector(digInfo, new DerOctetString(salt));

			if (!iterationCount.Equals(BigInteger.One))
			{
				v.Add(new DerInteger(iterationCount));
			}

			return new DerSequence(v);
        }
		/**
        * <pre>
        * CommitmentTypeIndication ::= SEQUENCE {
        *      commitmentTypeId   CommitmentTypeIdentifier,
        *      commitmentTypeQualifier   SEQUENCE SIZE (1..MAX) OF
        *              CommitmentTypeQualifier OPTIONAL }
        * </pre>
        */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(commitmentTypeId);

			if (commitmentTypeQualifier != null)
            {
                v.Add(commitmentTypeQualifier);
            }

			return new DerSequence(v);
        }
Exemplo n.º 12
0
        public AttributeTable(Asn1EncodableVector v)
        {
            _attributes = Platform.CreateHashtable(v.Count);

            for (int i = 0; i != v.Count; i++)
            {
                AttributeX509 a = AttributeX509.GetInstance(v[i]);

                _attributes.Add(a.AttrType, a);
            }
        }
        /*
         * PolicyInformation ::= Sequence {
         *      policyIdentifier   CertPolicyId,
         *      policyQualifiers   Sequence SIZE (1..MAX) OF
         *              PolicyQualifierInfo OPTIONAL }
         */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(policyIdentifier);

            if (policyQualifiers != null)
            {
                v.Add(policyQualifiers);
            }

            return new DerSequence(v);
        }
Exemplo n.º 14
0
		/**
         * Produce an object suitable for an Asn1OutputStream.
         * <pre>
         * RevokedInfo ::= Sequence {
         *      revocationTime              GeneralizedTime,
         *      revocationReason    [0]     EXPLICIT CRLReason OPTIONAL }
         * </pre>
         */
        public override Asn1Object ToAsn1Object()
        {
			Asn1EncodableVector v = new Asn1EncodableVector(revocationTime);

			if (revocationReason != null)
            {
                v.Add(new DerTaggedObject(true, 0, revocationReason));
            }

			return new DerSequence(v);
        }
Exemplo n.º 15
0
		/**
		* <pre>
		*       EncryptedData ::= SEQUENCE {
		*                     version CMSVersion,
		*                     encryptedContentInfo EncryptedContentInfo,
		*                     unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL }
		* </pre>
		* @return a basic ASN.1 object representation.
		*/
		public override Asn1Object ToAsn1Object()
		{
			Asn1EncodableVector v = new Asn1EncodableVector(version, encryptedContentInfo);

			if (unprotectedAttrs != null)
			{
				v.Add(new BerTaggedObject(false, 1, unprotectedAttrs));
			}

			return new BerSequence(v);
		}
Exemplo n.º 16
0
		public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector seq = new Asn1EncodableVector(qcStatementId);

			if (qcStatementInfo != null)
            {
                seq.Add(qcStatementInfo);
            }

			return new DerSequence(seq);
        }
Exemplo n.º 17
0
        /**
         * Produce an object suitable for an Asn1OutputStream.
         * <pre>
         * ContentInfo ::= Sequence {
         *          contentType ContentType,
         *          content
         *          [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
         * </pre>
         */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(contentType);

            if (content != null)
            {
                v.Add(new BerTaggedObject(0, content));
            }

            return new BerSequence(v);
        }
Exemplo n.º 18
0
		/**
         * Produce an object suitable for an Asn1OutputStream.
         * <pre>
         * ServiceLocator ::= Sequence {
         *     issuer    Name,
         *     locator   AuthorityInfoAccessSyntax OPTIONAL }
         * </pre>
         */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(issuer);

			if (locator != null)
            {
                v.Add(locator);
            }

			return new DerSequence(v);
        }
Exemplo n.º 19
0
		public override Asn1Object ToAsn1Object()
		{
			Asn1EncodableVector v = new Asn1EncodableVector(crlHash.ToAsn1Object());

			if (crlIdentifier != null)
			{
				v.Add(crlIdentifier.ToAsn1Object());
			}

			return new DerSequence(v);
		}
Exemplo n.º 20
0
        /**
         * <pre>
         * TimeStampResp ::= SEQUENCE  {
         *   status                  PkiStatusInfo,
         *   timeStampToken          TimeStampToken     OPTIONAL  }
         * </pre>
         */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(pkiStatusInfo);

            if (timeStampToken != null)
            {
                v.Add(timeStampToken);
            }

            return new DerSequence(v);
        }
Exemplo n.º 21
0
		/**
		 * <pre>
		 * EssCertID ::= SEQUENCE {
		 *     certHash Hash,
		 *     issuerSerial IssuerSerial OPTIONAL }
		 * </pre>
		 */
		public override Asn1Object ToAsn1Object()
		{
			Asn1EncodableVector v = new Asn1EncodableVector(certHash);

			if (issuerSerial != null)
			{
				v.Add(issuerSerial);
			}

			return new DerSequence(v);
		}
Exemplo n.º 22
0
        public AttributeTable(Asn1EncodableVector v)
        {
            _attributes = Platform.CreateHashtable(v.Count);

            foreach (Asn1Encodable o in v)
            {
                Attribute a = Attribute.GetInstance(o);

                AddAttribute(a);
            }
        }
Exemplo n.º 23
0
		public override Asn1Object ToAsn1Object()
		{
			Asn1EncodableVector v = new Asn1EncodableVector(
				octStr, iterationCount);

			if (keyLength != null)
			{
				v.Add(keyLength);
			}

			return new DerSequence(v);
		}
Exemplo n.º 24
0
		/**
         * Produce an object suitable for an Asn1OutputStream.
         * <pre>
         * EncryptedContentInfo ::= Sequence {
         *     contentType ContentType,
         *     contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
         *     encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL
         * }
         * </pre>
         */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(
				contentType, contentEncryptionAlgorithm);

			if (encryptedContent != null)
            {
                v.Add(new BerTaggedObject(false, 0, encryptedContent));
            }

			return new BerSequence(v);
        }
Exemplo n.º 25
0
		public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector();

			if (version != null)
            {
                v.Add(version);
            }

			v.Add(iv);

			return new DerSequence(v);
        }
Exemplo n.º 26
0
        public ExtendedKeyUsage(IEnumerable usages)
        {
            var v = new Asn1EncodableVector();

            foreach (Asn1Object o in usages)
            {
                v.Add(o);

                _usageTable.Add(o, o);
            }

            _seq = new DerSequence(v);
        }
Exemplo n.º 27
0
		/**
		 * <pre>
		 * ContentHints ::= SEQUENCE {
		 *   contentDescription UTF8String (SIZE (1..MAX)) OPTIONAL,
		 *   contentType ContentType }
		 * </pre>
		 */
		public override Asn1Object ToAsn1Object()
		{
			Asn1EncodableVector v = new Asn1EncodableVector();

			if (contentDescription != null)
			{
				v.Add(contentDescription);
			}

			v.Add(contentType);

			return new DerSequence(v);
		}
Exemplo n.º 28
0
		/**
		 * <pre>
		 * CertRepMessage ::= SEQUENCE {
		 *                          caPubs       [1] SEQUENCE SIZE (1..MAX) OF CMPCertificate
		 *                                                                             OPTIONAL,
		 *                          response         SEQUENCE OF CertResponse
		 * }
		 * </pre>
		 * @return a basic ASN.1 object representation.
		 */
		public override Asn1Object ToAsn1Object()
		{
			Asn1EncodableVector v = new Asn1EncodableVector();

			if (caPubs != null)
			{
				v.Add(new DerTaggedObject(true, 1, caPubs));
			}

			v.Add(response);

			return new DerSequence(v);
		}
Exemplo n.º 29
0
		/**
         * Produce an object suitable for an Asn1OutputStream.
         * <pre>
         *  OtherInfo ::= Sequence {
         *      keyInfo KeySpecificInfo,
         *      partyAInfo [0] OCTET STRING OPTIONAL,
         *      suppPubInfo [2] OCTET STRING
         *  }
         * </pre>
         */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(keyInfo);

			if (partyAInfo != null)
            {
                v.Add(new DerTaggedObject(0, partyAInfo));
            }

			v.Add(new DerTaggedObject(2, suppPubInfo));

			return new DerSequence(v);
        }
Exemplo n.º 30
0
        public ExtendedKeyUsage(
            ArrayList usages)
        {
            Asn1EncodableVector v = new Asn1EncodableVector();

            foreach (Asn1Object o in usages)
            {
                v.Add(o);

                this.usageTable.Add(o, o);
            }

            this.seq = new DerSequence(v);
        }
Exemplo n.º 31
0
 public static new BerSequence FromVector(
     Asn1EncodableVector v)
 {
     return(v.Count < 1 ? Empty : new BerSequence(v));
 }
Exemplo n.º 32
0
 internal BerSet(Asn1EncodableVector v, bool needsSorting)
     : base(v, needsSorting)
 {
 }
        /**
         * generate an enveloped object that contains an CMS Enveloped Data
         * object using the given provider and the passed in key generator.
         */
        private CmsAuthenticatedData Generate(
            CmsProcessable content,
            string macOid,
            CipherKeyGenerator keyGen)
        {
            AlgorithmIdentifier macAlgId;
            KeyParameter        encKey;
            Asn1OctetString     encContent;
            Asn1OctetString     macResult;

            try
            {
                // FIXME Will this work for macs?
                byte[] encKeyBytes = keyGen.GenerateKey();
                encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes);

                Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes);

                ICipherParameters cipherParameters;
                macAlgId = GetAlgorithmIdentifier(
                    macOid, encKey, asn1Params, out cipherParameters);

                IMac mac = MacUtilities.GetMac(macOid);
                // TODO Confirm no ParametersWithRandom needed
                // FIXME Only passing key at the moment
//	            mac.Init(cipherParameters);
                mac.Init(encKey);

                MemoryStream bOut = new MemoryStream();
                MacStream    mOut = new MacStream(bOut, null, mac);

                content.Write(mOut);

                mOut.Close();
                bOut.Close();

                encContent = new BerOctetString(bOut.ToArray());

                byte[] macOctets = MacUtilities.DoFinal(mOut.WriteMac());
                macResult = new DerOctetString(macOctets);
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("exception decoding algorithm parameters.", e);
            }


            Asn1EncodableVector recipientInfos = new Asn1EncodableVector();

            foreach (RecipientInfoGenerator rig in recipientInfoGenerators)
            {
                try
                {
                    recipientInfos.Add(rig.Generate(encKey, rand));
                }
                catch (InvalidKeyException e)
                {
                    throw new CmsException("key inappropriate for algorithm.", e);
                }
                catch (GeneralSecurityException e)
                {
                    throw new CmsException("error making encrypted content.", e);
                }
            }

            ContentInfo eci = new ContentInfo(CmsObjectIdentifiers.Data, encContent);

            ContentInfo contentInfo = new ContentInfo(
                CmsObjectIdentifiers.AuthenticatedData,
                new AuthenticatedData(null, new DerSet(recipientInfos), macAlgId, null, eci, null, macResult, null));

            return(new CmsAuthenticatedData(contentInfo));
        }
Exemplo n.º 34
0
        private Stream Open(
            Stream outStream,
            AlgorithmIdentifier encAlgID,
            ICipherParameters cipherParameters,
            Asn1EncodableVector recipientInfos)
        {
            try
            {
                //
                // ContentInfo
                //
                BerSequenceGenerator cGen = new BerSequenceGenerator(outStream);

                cGen.AddObject(CmsObjectIdentifiers.EnvelopedData);

                //
                // Encrypted Data
                //
                BerSequenceGenerator envGen = new BerSequenceGenerator(
                    cGen.GetRawOutputStream(), 0, true);

                envGen.AddObject(this.Version);

                Stream        envRaw   = envGen.GetRawOutputStream();
                Asn1Generator recipGen = _berEncodeRecipientSet
                    ? (Asn1Generator) new BerSetGenerator(envRaw)
                    : new DerSetGenerator(envRaw);

                foreach (Asn1Encodable ae in recipientInfos)
                {
                    recipGen.AddObject(ae);
                }

                recipGen.Close();

                BerSequenceGenerator eiGen = new BerSequenceGenerator(envRaw);
                eiGen.AddObject(CmsObjectIdentifiers.Data);
                eiGen.AddObject(encAlgID);

                Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream(
                    eiGen.GetRawOutputStream(), 0, false, _bufferSize);

                IBufferedCipher cipher = CipherUtilities.GetCipher(encAlgID.ObjectID);
                cipher.Init(true, new ParametersWithRandom(cipherParameters, rand));
                CipherStream cOut = new CipherStream(octetOutputStream, null, cipher);

                return(new CmsEnvelopedDataOutputStream(this, cOut, cGen, envGen, eiGen));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("exception decoding algorithm parameters.", e);
            }
        }
            public override void Close()
            {
                _out.Close();
                _eiGen.Close();

                outer._digests.Clear();                    // clear the current preserved digest state

                if (outer._certs.Count > 0)
                {
                    Asn1Set certs = CmsUtilities.CreateBerSetFromList(outer._certs);

                    WriteToGenerator(_sigGen, new BerTaggedObject(false, 0, certs));
                }

                if (outer._crls.Count > 0)
                {
                    Asn1Set crls = CmsUtilities.CreateBerSetFromList(outer._crls);

                    WriteToGenerator(_sigGen, new BerTaggedObject(false, 1, crls));
                }

                //
                // Calculate the digest hashes
                //
                foreach (DictionaryEntry de in outer._messageDigests)
                {
                    outer._messageHashes.Add(de.Key, DigestUtilities.DoFinal((IDigest)de.Value));
                }

                // TODO If the digest OIDs for precalculated signers weren't mixed in with
                // the others, we could fill in outer._digests here, instead of SignerInf.ToSignerInfo

                //
                // add the precalculated SignerInfo objects.
                //
                Asn1EncodableVector signerInfos = new Asn1EncodableVector();

                foreach (SignerInformation signer in outer._signers)
                {
                    signerInfos.Add(signer.ToSignerInfo());
                }

                //
                // add the SignerInfo objects
                //
                foreach (SignerInf signer in outer._signerInfs)
                {
                    try
                    {
                        signerInfos.Add(signer.ToSignerInfo(_contentOID));
                    }
                    catch (IOException e)
                    {
                        throw new CmsStreamException("encoding error." + e);
                    }
                    catch (InvalidKeyException e)
                    {
                        throw new CmsStreamException("key inappropriate for signature.", e);
                    }
                    catch (SignatureException e)
                    {
                        throw new CmsStreamException("error creating signature." + e);
                    }
                    catch (CertificateEncodingException e)
                    {
                        throw new CmsStreamException("error creating sid." + e);
                    }
                    catch (SecurityUtilityException e)
                    {
                        throw new CmsStreamException("unknown signature algorithm." + e);
                    }
                }

                WriteToGenerator(_sigGen, new DerSet(signerInfos));

                _sigGen.Close();
                _sGen.Close();
                base.Close();
            }
Exemplo n.º 36
0
 /**
  * create a set containing a vector of objects.
  */
 public BerSet(Asn1EncodableVector elementVector)
     : base(elementVector, false)
 {
 }
        private CmsAuthenticatedData Generate(CmsProcessable content, string macOid, CipherKeyGenerator keyGen)
        {
            KeyParameter        keyParameter;
            AlgorithmIdentifier algorithmIdentifier;
            Asn1OctetString     content2;
            Asn1OctetString     mac2;

            try
            {
                byte[] array = keyGen.GenerateKey();
                keyParameter = ParameterUtilities.CreateKeyParameter(macOid, array);
                Asn1Encodable     asn1Params = this.GenerateAsn1Parameters(macOid, array);
                ICipherParameters cipherParameters;
                algorithmIdentifier = this.GetAlgorithmIdentifier(macOid, keyParameter, asn1Params, out cipherParameters);
                IMac mac = MacUtilities.GetMac(macOid);
                mac.Init(keyParameter);
                MemoryStream memoryStream = new MemoryStream();
                Stream       stream       = new TeeOutputStream(memoryStream, new MacOutputStream(mac));
                content.Write(stream);
                stream.Close();
                memoryStream.Close();
                content2 = new BerOctetString(memoryStream.ToArray());
                byte[] str = MacUtilities.DoFinal(mac);
                mac2 = new DerOctetString(str);
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e2)
            {
                throw new CmsException("key invalid in message.", e2);
            }
            catch (IOException e3)
            {
                throw new CmsException("exception decoding algorithm parameters.", e3);
            }
            Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(new Asn1Encodable[0]);

            foreach (RecipientInfoGenerator recipientInfoGenerator in this.recipientInfoGenerators)
            {
                try
                {
                    asn1EncodableVector.Add(new Asn1Encodable[]
                    {
                        recipientInfoGenerator.Generate(keyParameter, this.rand)
                    });
                }
                catch (InvalidKeyException e4)
                {
                    throw new CmsException("key inappropriate for algorithm.", e4);
                }
                catch (GeneralSecurityException e5)
                {
                    throw new CmsException("error making encrypted content.", e5);
                }
            }
            ContentInfo encapsulatedContent = new ContentInfo(CmsObjectIdentifiers.Data, content2);
            ContentInfo contentInfo         = new ContentInfo(CmsObjectIdentifiers.AuthenticatedData, new AuthenticatedData(null, new DerSet(asn1EncodableVector), algorithmIdentifier, null, encapsulatedContent, null, mac2, null));

            return(new CmsAuthenticatedData(contentInfo));
        }
Exemplo n.º 38
0
        /**
         * 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.
             */
            Asn1.Cms.AttributeTable unsignedAttributeTable = UnsignedAttributes;
            if (unsignedAttributeTable == null)
            {
                return(new SignerInformationStore(Platform.CreateArrayList(0)));
            }

            IList counterSignatures = Platform.CreateArrayList();

            /*
             * 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);

            foreach (Asn1.Cms.Attribute counterSignatureAttribute in allCSAttrs)
            {
                /*
                 * 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.AttrValues;
                if (values.Count < 1)
                {
                    // TODO Throw an appropriate exception?
                }

                foreach (Asn1Encodable asn1Obj in values)
                {
                    /*
                     * 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(asn1Obj.ToAsn1Object());

                    string digestName = CmsSignedHelper.Instance.GetDigestAlgName(si.DigestAlgorithm.Algorithm.Id);

                    counterSignatures.Add(new SignerInformation(si, null, null, new CounterSignatureDigestCalculator(digestName, GetSignature())));
                }
            }

            return(new SignerInformationStore(counterSignatures));
        }
        /**
         * generate a signed object that for a CMS Signed Data
         * object  - if encapsulate is true a copy
         * of the message will be included in the signature. The content type
         * is set according to the OID represented by the string signedContentType.
         */
        public CmsSignedData Generate(
            // FIXME Avoid accessing more than once to support CmsProcessableInputStream
            ICmsTypedData content,
            bool encapsulate)
        {
            // TODO
            //        if (signerInfs.isEmpty())
            //        {
            //            /* RFC 3852 5.2
            //             * "In the degenerate case where there are no signers, the
            //             * EncapsulatedContentInfo value being "signed" is irrelevant.  In this
            //             * case, the content type within the EncapsulatedContentInfo value being
            //             * "signed" MUST be id-data (as defined in section 4), and the content
            //             * field of the EncapsulatedContentInfo value MUST be omitted."
            //             */
            //            if (encapsulate)
            //            {
            //                throw new IllegalArgumentException("no signers, encapsulate must be false");
            //            }
            //            if (!DATA.equals(eContentType))
            //            {
            //                throw new IllegalArgumentException("no signers, eContentType must be id-data");
            //            }
            //        }
            //
            //        if (!DATA.equals(eContentType))
            //        {
            //            /* RFC 3852 5.3
            //             * [The 'signedAttrs']...
            //             * field is optional, but it MUST be present if the content type of
            //             * the EncapsulatedContentInfo value being signed is not id-data.
            //             */
            //            // TODO signedAttrs must be present for all signers
            //        }

            Asn1EncodableVector digestAlgs  = new Asn1EncodableVector();
            Asn1EncodableVector signerInfos = new Asn1EncodableVector();

            _digests.Clear();  // clear the current preserved digest state

            //
            // add the precalculated SignerInfo objects.
            //
            for (IEnumerator it = _signers.GetEnumerator(); it.MoveNext();)
            {
                SignerInformation signer = (SignerInformation)it.Current;
                digestAlgs.Add(CmsUtilities.fixAlgID(signer.DigestAlgorithmID));

                // TODO Verify the content type and calculated digest match the precalculated SignerInfo
                signerInfos.Add(signer.ToAsn1Structure());
            }

            //
            // add the SignerInfo objects
            //
            DerObjectIdentifier contentTypeOID = content.ContentType;

            Asn1OctetString octs = null;

            if (content.GetContent() != null)
            {
                MemoryOutputStream bOut = null;

                if (encapsulate)
                {
                    bOut = new MemoryOutputStream();
                }

                Stream cOut = CmsUtilities.attachSignersToOutputStream(_signerGens, bOut);

                // Just in case it's unencapsulated and there are no signers!
                cOut = CmsUtilities.getSafeOutputStream(cOut);

                try
                {
                    content.Write(cOut);

                    cOut.Close();
                }
                catch (IOException e)
                {
                    throw new CmsException("data processing exception: " + e.Message, e);
                }

                if (encapsulate)
                {
                    octs = new BerOctetString(bOut.ToArray());
                }
            }

            for (IEnumerator it = _signerGens.GetEnumerator(); it.MoveNext();)
            {
                SignerInfoGenerator sGen = (SignerInfoGenerator)it.Current;
                SignerInfo          inf  = sGen.Generate(contentTypeOID);

                digestAlgs.Add(inf.DigestAlgorithm);
                signerInfos.Add(inf);

                byte[] calcDigest = sGen.getCalculatedDigest();

                if (calcDigest != null)
                {
                    _digests.Add(inf.DigestAlgorithm.Algorithm.Id, calcDigest);
                }
            }

            Asn1Set certificates = null;

            if (_certs.Count != 0)
            {
                certificates = CmsUtilities.CreateBerSetFromList(_certs);
            }

            Asn1Set certrevlist = null;

            if (_crls.Count != 0)
            {
                certrevlist = CmsUtilities.CreateBerSetFromList(_crls);
            }

            ContentInfo encInfo = new ContentInfo(contentTypeOID, octs);

            SignedData sd = new SignedData(
                new DerSet(digestAlgs),
                encInfo,
                certificates,
                certrevlist,
                new DerSet(signerInfos));

            ContentInfo contentInfo = new ContentInfo(
                CmsObjectIdentifiers.SignedData, sd);

            return(new CmsSignedData(content, contentInfo));
        }
        private BasicOcspResp GenerateResponse(ISignatureFactory signatureCalculator, X509Certificate[] chain, global::System.DateTime producedAt)
        {
            //IL_016c: Expected O, but got Unknown
            AlgorithmIdentifier algorithmIdentifier = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;
            DerObjectIdentifier algorithm           = algorithmIdentifier.Algorithm;
            Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();

            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)list).GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    ResponseObject responseObject = (ResponseObject)enumerator.get_Current();
                    try
                    {
                        asn1EncodableVector.Add(responseObject.ToResponse());
                    }
                    catch (global::System.Exception e)
                    {
                        throw new OcspException("exception creating Request", e);
                    }
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            ResponseData responseData = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(asn1EncodableVector), responseExtensions);
            DerBitString derBitString = null;

            try
            {
                IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();
                byte[]            derEncoded       = responseData.GetDerEncoded();
                streamCalculator.Stream.Write(derEncoded, 0, derEncoded.Length);
                Platform.Dispose(streamCalculator.Stream);
                derBitString = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
            }
            catch (global::System.Exception ex)
            {
                throw new OcspException(string.Concat((object)"exception processing TBSRequest: ", (object)ex), ex);
            }
            AlgorithmIdentifier sigAlgID = OcspUtilities.GetSigAlgID(algorithm);
            DerSequence         certs    = null;

            if (chain != null && chain.Length > 0)
            {
                Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector();
                try
                {
                    for (int i = 0; i != chain.Length; i++)
                    {
                        asn1EncodableVector2.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(chain[i].GetEncoded())));
                    }
                }
                catch (IOException val)
                {
                    IOException e2 = val;
                    throw new OcspException("error processing certs", (global::System.Exception)(object) e2);
                }
                catch (CertificateEncodingException e3)
                {
                    throw new OcspException("error encoding certs", e3);
                }
                certs = new DerSequence(asn1EncodableVector2);
            }
            return(new BasicOcspResp(new BasicOcspResponse(responseData, sigAlgID, derBitString, certs)));
        }
Exemplo n.º 41
0
        public void Save(
            Stream stream,
            char[]                      password,
            SecureRandom random)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (random == null)
            {
                throw new ArgumentNullException("random");
            }

            //
            // handle the keys
            //
            Asn1EncodableVector keyBags = new Asn1EncodableVector();

            foreach (string name in keys.Keys)
            {
                byte[] kSalt = new byte[SaltSize];
                random.NextBytes(kSalt);

                AsymmetricKeyEntry privKey = (AsymmetricKeyEntry)keys[name];

                DerObjectIdentifier bagOid;
                Asn1Encodable       bagData;

                if (password == null)
                {
                    bagOid  = PkcsObjectIdentifiers.KeyBag;
                    bagData = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey.Key);
                }
                else
                {
                    bagOid = PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag;
                    if (keyPrfAlgorithm != null)
                    {
                        bagData = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                            keyAlgorithm, keyPrfAlgorithm, password, kSalt, MinIterations, random, privKey.Key);
                    }
                    else
                    {
                        bagData = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                            keyAlgorithm, password, kSalt, MinIterations, privKey.Key);
                    }
                }

                Asn1EncodableVector kName = new Asn1EncodableVector();

                foreach (string oid in privKey.BagAttributeKeys)
                {
                    Asn1Encodable entry = privKey[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                    {
                        continue;
                    }

                    kName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'name'
                //if (privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                //
                // make sure we have a local key-id
                //
                if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    X509CertificateEntry   ct           = GetCertificate(name);
                    AsymmetricKeyParameter pubKey       = ct.Certificate.GetPublicKey();
                    SubjectKeyIdentifier   subjectKeyID = CreateSubjectKeyID(pubKey);

                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(subjectKeyID)));
                }

                keyBags.Add(new SafeBag(bagOid, bagData.ToAsn1Object(), new DerSet(kName)));
            }

            byte[]      keyBagsEncoding = new DerSequence(keyBags).GetDerEncoded();
            ContentInfo keysInfo        = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(keyBagsEncoding));

            //
            // certificate processing
            //
            byte[] cSalt = new byte[SaltSize];

            random.NextBytes(cSalt);

            Asn1EncodableVector certBags = new Asn1EncodableVector();
            Pkcs12PbeParams     cParams  = new Pkcs12PbeParams(cSalt, MinIterations);
            AlgorithmIdentifier cAlgId   = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object());
            ISet doneCerts = new HashSet();

            foreach (string name in keys.Keys)
            {
                X509CertificateEntry certEntry = GetCertificate(name);
                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(certEntry.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in certEntry.BagAttributeKeys)
                {
                    Asn1Encodable entry = certEntry[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                    {
                        continue;
                    }

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'name'
                //if (certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                //
                // make sure we have a local key-id
                //
                if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    AsymmetricKeyParameter pubKey       = certEntry.Certificate.GetPublicKey();
                    SubjectKeyIdentifier   subjectKeyID = CreateSubjectKeyID(pubKey);

                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(subjectKeyID)));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));

                doneCerts.Add(certEntry.Certificate);
            }

            foreach (string certId in certs.Keys)
            {
                X509CertificateEntry cert = (X509CertificateEntry)certs[certId];

                if (keys[certId] != null)
                {
                    continue;
                }

                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(cert.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    // a certificate not immediately linked to a key doesn't require
                    // a localKeyID and will confuse some PKCS12 implementations.
                    //
                    // If we find one, we'll prune it out.
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id))
                    {
                        continue;
                    }

                    Asn1Encodable entry = cert[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                    {
                        continue;
                    }

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'certId'
                //if (cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(certId))));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));

                doneCerts.Add(cert.Certificate);
            }

            foreach (CertId certId in chainCerts.Keys)
            {
                X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId];

                if (doneCerts.Contains(cert.Certificate))
                {
                    continue;
                }

                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(cert.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    // a certificate not immediately linked to a key doesn't require
                    // a localKeyID and will confuse some PKCS12 implementations.
                    //
                    // If we find one, we'll prune it out.
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id))
                    {
                        continue;
                    }

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(cert[oid])));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));
            }

            byte[] certBagsEncoding = new DerSequence(certBags).GetDerEncoded();

            ContentInfo certsInfo;

            if (password == null || certAlgorithm == null)
            {
                certsInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(certBagsEncoding));
            }
            else
            {
                byte[]        certBytes = CryptPbeData(true, cAlgId, password, false, certBagsEncoding);
                EncryptedData cInfo     = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes));
                certsInfo = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object());
            }

            ContentInfo[] info = new ContentInfo[] { keysInfo, certsInfo };

            byte[] data = new AuthenticatedSafe(info).GetEncoded(
                useDerEncoding ? Asn1Encodable.Der : Asn1Encodable.Ber);

            ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(data));

            //
            // create the mac
            //
            MacData macData = null;

            if (password != null)
            {
                byte[] mSalt = new byte[20];
                random.NextBytes(mSalt);

                byte[] mac = CalculatePbeMac(OiwObjectIdentifiers.IdSha1,
                                             mSalt, MinIterations, password, false, data);

                AlgorithmIdentifier algId = new AlgorithmIdentifier(
                    OiwObjectIdentifiers.IdSha1, DerNull.Instance);
                DigestInfo dInfo = new DigestInfo(algId, mac);

                macData = new MacData(dInfo, mSalt, MinIterations);
            }

            //
            // output the Pfx
            //
            Pfx pfx = new Pfx(mainInfo, macData);

            DerOutputStream derOut;

            if (useDerEncoding)
            {
                derOut = new DerOutputStream(stream);
            }
            else
            {
                derOut = new BerOutputStream(stream);
            }

            derOut.WriteObject(pfx);
        }
Exemplo n.º 42
0
 public static new BerSet FromVector(Asn1EncodableVector elementVector)
 {
     return(elementVector.Count < 1 ? Empty : new BerSet(elementVector));
 }
Exemplo n.º 43
0
 internal BerSet(Asn1EncodableVector elementVector, bool needsSorting)
     : base(elementVector, needsSorting)
 {
 }
Exemplo n.º 44
0
 /**
  * create a sequence containing a vector of objects.
  */
 public BerSequence(Asn1EncodableVector elementVector)
     : base(elementVector)
 {
 }
Exemplo n.º 45
0
 internal static new BerSet FromVector(
     Asn1EncodableVector v,
     bool needsSorting)
 {
     return(v.Count < 1 ? Empty : new BerSet(v, needsSorting));
 }
Exemplo n.º 46
0
        private BasicOcspResp GenerateResponse(
            ISignatureFactory signatureCalculator,
            X509Certificate[]               chain,
            DateTime producedAt)
        {
            AlgorithmIdentifier signingAlgID     = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;
            DerObjectIdentifier signingAlgorithm = signingAlgID.Algorithm;

            Asn1EncodableVector responses = new Asn1EncodableVector();

            foreach (ResponseObject respObj in list)
            {
                try
                {
                    responses.Add(respObj.ToResponse());
                }
                catch (Exception e)
                {
                    throw new OcspException("exception creating Request", e);
                }
            }

            ResponseData tbsResp = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(responses), responseExtensions);
            DerBitString bitSig  = null;

            try
            {
                IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();

                byte[] encoded = tbsResp.GetDerEncoded();

                streamCalculator.Stream.Write(encoded, 0, encoded.Length);

                Platform.Dispose(streamCalculator.Stream);

                bitSig = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
            }
            catch (Exception e)
            {
                throw new OcspException("exception processing TBSRequest: " + e, e);
            }

            AlgorithmIdentifier sigAlgId = OcspUtilities.GetSigAlgID(signingAlgorithm);

            DerSequence chainSeq = null;

            if (chain != null && chain.Length > 0)
            {
                Asn1EncodableVector v = new Asn1EncodableVector();
                try
                {
                    for (int i = 0; i != chain.Length; i++)
                    {
                        v.Add(
                            X509CertificateStructure.GetInstance(
                                Asn1Object.FromByteArray(chain[i].GetEncoded())));
                    }
                }
                catch (IOException e)
                {
                    throw new OcspException("error processing certs", e);
                }
                catch (CertificateEncodingException e)
                {
                    throw new OcspException("error encoding certs", e);
                }

                chainSeq = new DerSequence(v);
            }

            return(new BasicOcspResp(new BasicOcspResponse(tbsResp, sigAlgId, bitSig, chainSeq)));
        }
Exemplo n.º 47
0
 internal static new BerSet FromVector(Asn1EncodableVector elementVector, bool needsSorting)
 {
     return(elementVector.Count < 1 ? Empty : new BerSet(elementVector, needsSorting));
 }
Exemplo n.º 48
0
 public BerApplicationSpecific(int tagNo, Asn1EncodableVector vec)
     : base(tagNo, vec)
 {
 }
        /**
         * generate a signed object that for a CMS Signed Data
         * object using the given provider - if encapsulate is true a copy
         * of the message will be included in the signature. The content type
         * is set according to the OID represented by the string signedContentType.
         * @param out stream the CMS object is to be written to.
         * @param signedContentType OID for data to be signed.
         * @param encapsulate true if data should be encapsulated.
         * @param dataOutputStream output stream to copy the data being signed to.
         */
        public Stream Open(
            Stream outStream,
            string signedContentType,
            bool encapsulate,
            Stream dataOutputStream)
        {
            if (outStream == null)
            {
                throw new ArgumentNullException("outStream");
            }
            if (!outStream.CanWrite)
            {
                throw new ArgumentException("Expected writeable stream", "outStream");
            }
            if (dataOutputStream != null && !dataOutputStream.CanWrite)
            {
                throw new ArgumentException("Expected writeable stream", "dataOutputStream");
            }

            _messageDigestsLocked = true;

            //
            // ContentInfo
            //
            BerSequenceGenerator sGen = new BerSequenceGenerator(outStream);

            sGen.AddObject(CmsObjectIdentifiers.SignedData);

            //
            // Signed Data
            //
            BerSequenceGenerator sigGen = new BerSequenceGenerator(
                sGen.GetRawOutputStream(), 0, true);

            sigGen.AddObject(CalculateVersion(signedContentType));

            Asn1EncodableVector digestAlgs = new Asn1EncodableVector();

            foreach (string digestOid in _messageDigestOids)
            {
                digestAlgs.Add(
                    new AlgorithmIdentifier(new DerObjectIdentifier(digestOid), DerNull.Instance));
            }

            {
                byte[] tmp = new DerSet(digestAlgs).GetEncoded();
                sigGen.GetRawOutputStream().Write(tmp, 0, tmp.Length);
            }

            BerSequenceGenerator eiGen = new BerSequenceGenerator(sigGen.GetRawOutputStream());

            eiGen.AddObject(new DerObjectIdentifier(signedContentType));

            Stream digStream;

            if (encapsulate)
            {
                BerOctetStringGenerator octGen = new BerOctetStringGenerator(
                    eiGen.GetRawOutputStream(), 0, true);

                digStream = octGen.GetOctetOutputStream(_bufferSize);

                if (dataOutputStream != null)
                {
                    digStream = new TeeOutputStream(dataOutputStream, digStream);
                }
            }
            else
            {
                if (dataOutputStream != null)
                {
                    digStream = dataOutputStream;
                }
                else
                {
                    digStream = new NullOutputStream();
                }
            }

            foreach (IDigest d in _messageDigests.Values)
            {
                digStream = new DigestStream(digStream, null, d);
            }

            return(new CmsSignedDataOutputStream(this, digStream, signedContentType, sGen, sigGen, eiGen));
        }
Exemplo n.º 50
0
        /**
         * Returns the encoded form of this certification path, using
         * the specified encoding.
         *
         * @param encoding the name of the encoding to use
         * @return the encoded bytes
         * @exception CertificateEncodingException if an encoding error
         * occurs or the encoding requested is not supported
         *
         */
        public virtual byte[] GetEncoded(
            string encoding)
        {
            if (String.Compare(encoding, "PkiPath", true) == 0)
            {
                Asn1EncodableVector v = new Asn1EncodableVector();

                for (int i = certificates.Count - 1; i >= 0; i--)
                {
                    v.Add(ToAsn1Object((X509Certificate)certificates[i]));
                }

                return(ToDerEncoded(new DerSequence(v)));
            }
            else if (String.Compare(encoding, "PKCS7", true) == 0)
            {
                Asn1.Pkcs.ContentInfo encInfo = new Asn1.Pkcs.ContentInfo(
                    PkcsObjectIdentifiers.Data, null);

                Asn1EncodableVector v = new Asn1EncodableVector();
                for (int i = 0; i != certificates.Count; i++)
                {
                    v.Add(ToAsn1Object((X509Certificate)certificates[i]));
                }

                Asn1.Pkcs.SignedData sd = new Asn1.Pkcs.SignedData(
                    new DerInteger(1),
                    new DerSet(),
                    encInfo,
                    new DerSet(v),
                    null,
                    new DerSet());

                return(ToDerEncoded(new Asn1.Pkcs.ContentInfo(PkcsObjectIdentifiers.SignedData, sd)));
            }
            else if (String.Compare(encoding, "PEM", true) == 0)
            {
                MemoryStream bOut = new MemoryStream();
                PemWriter    pWrt = new PemWriter(new StreamWriter(bOut));

                try
                {
                    for (int i = 0; i != certificates.Count; i++)
                    {
                        pWrt.WriteObject(certificates[i]);
                    }

                    pWrt.Writer.Close();
                }
                catch (Exception)
                {
                    throw new CertificateEncodingException("can't encode certificate for PEM encoded path");
                }

                return(bOut.ToArray());
            }
            else
            {
                throw new CertificateEncodingException("unsupported encoding: " + encoding);
            }
        }
Exemplo n.º 51
0
 public Attributes(Asn1EncodableVector v)
 {
     attributes = new BerSet(v);
 }
Exemplo n.º 52
0
        protected Stream Open(
            Stream outStr,
            AlgorithmIdentifier macAlgId,
            ICipherParameters cipherParameters,
            Asn1EncodableVector recipientInfos)
        {
            try
            {
                //
                // ContentInfo
                //
                BerSequenceGenerator cGen = new BerSequenceGenerator(outStr);

                cGen.AddObject(CmsObjectIdentifiers.AuthenticatedData);

                //
                // Authenticated Data
                //
                BerSequenceGenerator authGen = new BerSequenceGenerator(
                    cGen.GetRawOutputStream(), 0, true);

                authGen.AddObject(new DerInteger(AuthenticatedData.CalculateVersion(null)));

                Stream        authRaw  = authGen.GetRawOutputStream();
                Asn1Generator recipGen = _berEncodeRecipientSet
                                        ?       (Asn1Generator) new BerSetGenerator(authRaw)
                                        :       new DerSetGenerator(authRaw);

                foreach (Asn1Encodable ae in recipientInfos)
                {
                    recipGen.AddObject(ae);
                }

                recipGen.Close();

                authGen.AddObject(macAlgId);

                BerSequenceGenerator eiGen = new BerSequenceGenerator(authRaw);
                eiGen.AddObject(CmsObjectIdentifiers.Data);

                Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream(
                    eiGen.GetRawOutputStream(), 0, false, _bufferSize);

                IMac mac = MacUtilities.GetMac(macAlgId.ObjectID);
                // TODO Confirm no ParametersWithRandom needed
                mac.Init(cipherParameters);
                Stream mOut = new TeeOutputStream(octetOutputStream, new MacOutputStream(mac));

                return(new CmsAuthenticatedDataOutputStream(mOut, mac, cGen, authGen, eiGen));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("exception decoding algorithm parameters.", e);
            }
        }
Exemplo n.º 53
0
        /**
         * generate a signed object that for a CMS Signed Data
         * object  - if encapsulate is true a copy
         * of the message will be included in the signature. The content type
         * is set according to the OID represented by the string signedContentType.
         */
        public CmsSignedData Generate(
            string signedContentType,
            // FIXME Avoid accessing more than once to support CmsProcessableInputStream
            CmsProcessable content,
            bool encapsulate)
        {
            Asn1EncodableVector digestAlgs  = new Asn1EncodableVector();
            Asn1EncodableVector signerInfos = new Asn1EncodableVector();

            _digests.Clear();             // clear the current preserved digest state

            //
            // add the precalculated SignerInfo objects.
            //
            foreach (SignerInformation signer in _signers)
            {
                digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID));

                // TODO Verify the content type and calculated digest match the precalculated SignerInfo
                signerInfos.Add(signer.ToSignerInfo());
            }

            //
            // add the SignerInfo objects
            //
            bool isCounterSignature = (signedContentType == null);

            DerObjectIdentifier contentTypeOid = isCounterSignature
                ?   null
                                :       new DerObjectIdentifier(signedContentType);

            foreach (SignerInf signer in signerInfs)
            {
                try
                {
                    digestAlgs.Add(signer.DigestAlgorithmID);
                    signerInfos.Add(signer.ToSignerInfo(contentTypeOid, content, rand));
                }
                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.Count != 0)
            {
                certificates = CmsUtilities.CreateBerSetFromList(_certs);
            }

            Asn1Set certrevlist = null;

            if (_crls.Count != 0)
            {
                certrevlist = CmsUtilities.CreateBerSetFromList(_crls);
            }

            Asn1OctetString octs = null;

            if (encapsulate)
            {
                MemoryStream bOut = new MemoryStream();
                if (content != null)
                {
                    try
                    {
                        content.Write(bOut);
                    }
                    catch (IOException e)
                    {
                        throw new CmsException("encapsulation error.", e);
                    }
                }
                octs = new BerOctetString(bOut.ToArray());
            }

            ContentInfo encInfo = new ContentInfo(contentTypeOid, octs);

            SignedData sd = new SignedData(
                new DerSet(digestAlgs),
                encInfo,
                certificates,
                certrevlist,
                new DerSet(signerInfos));

            ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.SignedData, sd);

            return(new CmsSignedData(content, contentInfo));
        }
Exemplo n.º 54
0
 public BerSet(Asn1EncodableVector v)
     : base(v, needsSorting: false)
 {
 }
Exemplo n.º 55
0
 /**
  * create a set containing a vector of objects.
  */
 public BerSet(Asn1EncodableVector v) : base(v, false)
 {
 }
Exemplo n.º 56
0
        /// <summary>
        /// Generate an enveloped object that contains a CMS Enveloped Data
        /// object using the passed in key generator.
        /// </summary>
        private CmsEnvelopedData Generate(
            CmsProcessable content,
            string encryptionOid,
            CipherKeyGenerator keyGen)
        {
            AlgorithmIdentifier encAlgId = null;
            KeyParameter        encKey;
            Asn1OctetString     encContent;

            try
            {
                byte[] encKeyBytes = keyGen.GenerateKey();
                encKey = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes);

                Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, encKeyBytes);

                ICipherParameters cipherParameters;
                encAlgId = GetAlgorithmIdentifier(
                    encryptionOid, encKey, asn1Params, out cipherParameters);

                IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid);
                cipher.Init(true, new ParametersWithRandom(cipherParameters, rand));

                MemoryStream bOut = new MemoryStream();
                CipherStream cOut = new CipherStream(bOut, null, cipher);

                content.Write(cOut);

                Platform.Dispose(cOut);

                encContent = new BerOctetString(bOut.ToArray());
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("exception decoding algorithm parameters.", e);
            }


            Asn1EncodableVector recipientInfos = new Asn1EncodableVector();

            foreach (RecipientInfoGenerator rig in recipientInfoGenerators)
            {
                try
                {
                    recipientInfos.Add(rig.Generate(encKey, rand));
                }
                catch (InvalidKeyException e)
                {
                    throw new CmsException("key inappropriate for algorithm.", e);
                }
                catch (GeneralSecurityException e)
                {
                    throw new CmsException("error making encrypted content.", e);
                }
            }

            EncryptedContentInfo eci = new EncryptedContentInfo(
                CmsObjectIdentifiers.Data,
                encAlgId,
                encContent);

            Asn1Set unprotectedAttrSet = null;

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

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

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

            return(new CmsEnvelopedData(contentInfo));
        }
Exemplo n.º 57
0
        /**
         * generate a signed object that for a CMS Signed Data
         * object using the given provider - if encapsulate is true a copy
         * of the message will be included in the signature. The content type
         * is set according to the OID represented by the string signedContentType.
         * @param out stream the CMS object is to be written to.
         * @param signedContentType OID for data to be signed.
         * @param encapsulate true if data should be encapsulated.
         * @param dataOutputStream output stream to copy the data being signed to.
         */
        public Stream Open(
            Stream outStream,
            string signedContentType,
            bool encapsulate,
            Stream dataOutputStream)
        {
            if (outStream == null)
            {
                throw new ArgumentNullException("outStream");
            }
            if (!outStream.CanWrite)
            {
                throw new ArgumentException("Expected writeable stream", "outStream");
            }
            if (dataOutputStream != null && !dataOutputStream.CanWrite)
            {
                throw new ArgumentException("Expected writeable stream", "dataOutputStream");
            }

            _messageDigestsLocked = true;

            //
            // ContentInfo
            //
            BerSequenceGenerator sGen = new BerSequenceGenerator(outStream);

            sGen.AddObject(CmsObjectIdentifiers.SignedData);

            //
            // Signed Data
            //
            BerSequenceGenerator sigGen = new BerSequenceGenerator(
                sGen.GetRawOutputStream(), 0, true);

            bool isCounterSignature = (signedContentType == null);

            DerObjectIdentifier contentTypeOid = isCounterSignature
                ? null
                : new DerObjectIdentifier(signedContentType);

            sigGen.AddObject(CalculateVersion(contentTypeOid));

            Asn1EncodableVector digestAlgs = new Asn1EncodableVector();

            foreach (string digestOid in _messageDigestOids)
            {
                digestAlgs.Add(
                    new AlgorithmIdentifier(new DerObjectIdentifier(digestOid), DerNull.Instance));
            }

            {
                byte[] tmp = new DerSet(digestAlgs).GetEncoded();
                sigGen.GetRawOutputStream().Write(tmp, 0, tmp.Length);
            }

            BerSequenceGenerator eiGen = new BerSequenceGenerator(sigGen.GetRawOutputStream());

            eiGen.AddObject(contentTypeOid);

            // If encapsulating, add the data as an octet string in the sequence
            Stream encapStream = encapsulate
                                ?       CmsUtilities.CreateBerOctetOutputStream(eiGen.GetRawOutputStream(), 0, true, _bufferSize)
                                :       null;

            // Also send the data to 'dataOutputStream' if necessary
            Stream teeStream = GetSafeTeeOutputStream(dataOutputStream, encapStream);

            // Let all the digests see the data as it is written
            Stream digStream = AttachDigestsToOutputStream(_messageDigests.Values, teeStream);

            return(new CmsSignedDataOutputStream(this, digStream, signedContentType, sGen, sigGen, eiGen));
        }
Exemplo n.º 58
0
 /**
  * create a sequence containing a vector of objects.
  */
 public BerSequence(
     Asn1EncodableVector v)
     : base(v)
 {
 }
Exemplo n.º 59
0
            private void DoClose()
            {
                Platform.Dispose(_out);

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

                _eiGen.Close();

                outer._digests.Clear();                    // clear the current preserved digest state

                if (outer._certs.Count > 0)
                {
                    Asn1Set certs = CmsUtilities.CreateBerSetFromList(outer._certs);

                    WriteToGenerator(_sigGen, new BerTaggedObject(false, 0, certs));
                }

                if (outer._crls.Count > 0)
                {
                    Asn1Set crls = CmsUtilities.CreateBerSetFromList(outer._crls);

                    WriteToGenerator(_sigGen, new BerTaggedObject(false, 1, crls));
                }

                //
                // Calculate the digest hashes
                //
                foreach (DictionaryEntry de in outer._messageDigests)
                {
                    outer._messageHashes.Add(de.Key, DigestUtilities.DoFinal((IDigest)de.Value));
                }

                // TODO If the digest OIDs for precalculated signers weren't mixed in with
                // the others, we could fill in outer._digests here, instead of SignerInfoGenerator.Generate

                //
                // collect all the SignerInfo objects
                //
                Asn1EncodableVector signerInfos = new Asn1EncodableVector();

                //
                // add the generated SignerInfo objects
                //
                {
                    foreach (DigestAndSignerInfoGeneratorHolder holder in outer._signerInfs)
                    {
                        AlgorithmIdentifier digestAlgorithm = holder.DigestAlgorithm;

                        byte[] calculatedDigest = (byte[])outer._messageHashes[
                            Helper.GetDigestAlgName(holder.digestOID)];
                        outer._digests[holder.digestOID] = calculatedDigest.Clone();

                        signerInfos.Add(holder.signerInf.Generate(_contentOID, digestAlgorithm, calculatedDigest));
                    }
                }

                //
                // add the precalculated SignerInfo objects.
                //
                {
                    foreach (SignerInformation signer in outer._signers)
                    {
                        // TODO Verify the content type and calculated digest match the precalculated SignerInfo
//						if (!signer.ContentType.Equals(_contentOID))
//						{
//							// TODO The precalculated content type did not match - error?
//						}
//
//						byte[] calculatedDigest = (byte[])outer._digests[signer.DigestAlgOid];
//						if (calculatedDigest == null)
//						{
//							// TODO We can't confirm this digest because we didn't calculate it - error?
//						}
//						else
//						{
//							if (!Arrays.AreEqual(signer.GetContentDigest(), calculatedDigest))
//							{
//								// TODO The precalculated digest did not match - error?
//							}
//						}

                        signerInfos.Add(signer.ToSignerInfo());
                    }
                }

                WriteToGenerator(_sigGen, new DerSet(signerInfos));

                _sigGen.Close();
                _sGen.Close();
            }
Exemplo n.º 60
0
        private OcspReq GenerateRequest(
            DerObjectIdentifier signingAlgorithm,
            AsymmetricKeyParameter privateKey,
            X509Certificate[]               chain,
            SecureRandom random)
        {
            Asn1EncodableVector requests = new Asn1EncodableVector();

            foreach (RequestObject reqObj in list)
            {
                try
                {
                    requests.Add(reqObj.ToRequest());
                }
                catch (Exception e)
                {
                    throw new OcspException("exception creating Request", e);
                }
            }

            TbsRequest tbsReq = new TbsRequest(requestorName, new DerSequence(requests), requestExtensions);

            ISigner   sig       = null;
            Signature signature = null;

            if (signingAlgorithm != null)
            {
                if (requestorName == null)
                {
                    throw new OcspException("requestorName must be specified if request is signed.");
                }

                try
                {
                    sig = SignerUtilities.GetSigner(signingAlgorithm.Id);
                    if (random != null)
                    {
                        sig.Init(true, new ParametersWithRandom(privateKey, random));
                    }
                    else
                    {
                        sig.Init(true, privateKey);
                    }
                }
                catch (Exception e)
                {
                    throw new OcspException("exception creating signature: " + e, e);
                }

                DerBitString bitSig = null;

                try
                {
                    byte[] encoded = tbsReq.GetEncoded();
                    sig.BlockUpdate(encoded, 0, encoded.Length);

                    bitSig = new DerBitString(sig.GenerateSignature());
                }
                catch (Exception e)
                {
                    throw new OcspException("exception processing TBSRequest: " + e, e);
                }

                AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(signingAlgorithm, DerNull.Instance);

                if (chain != null && chain.Length > 0)
                {
                    Asn1EncodableVector v = new Asn1EncodableVector();
                    try
                    {
                        for (int i = 0; i != chain.Length; i++)
                        {
                            v.Add(
                                X509CertificateStructure.GetInstance(
                                    Asn1Object.FromByteArray(chain[i].GetEncoded())));
                        }
                    }
                    catch (IOException e)
                    {
                        throw new OcspException("error processing certs", e);
                    }
                    catch (CertificateEncodingException e)
                    {
                        throw new OcspException("error encoding certs", e);
                    }

                    signature = new Signature(sigAlgId, bitSig, new DerSequence(v));
                }
                else
                {
                    signature = new Signature(sigAlgId, bitSig);
                }
            }

            return(new OcspReq(new OcspRequest(tbsReq, signature)));
        }