Add() 공개 메소드

public Add ( ) : void
리턴 void
 public Asn1Object toASN1Primitive()
 {
     Asn1EncodableVector dev = new Asn1EncodableVector();
     dev.Add(this.sigPolicyQualifierId);
     dev.Add(this.sigQualifier);
     return new DerSequence(dev);
 }
예제 #2
0
		public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector();

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

			v.Add(iv);

			return new DerSequence(v);
        }
        private PkiStatusInfo GetPkiStatusInfo()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(
                new DerInteger((int)status));

            if (statusStrings.Count > 0)
            {
                v.Add(new PkiFreeText(new DerSequence(statusStrings)));
            }

            if (failInfo != 0)
            {
                v.Add(new FailInfo(failInfo));
            }

            return new PkiStatusInfo(new DerSequence(v));
        }
예제 #4
0
 public static Asn1Set CreateBerSetFromList(List<Asn1Encodable> derObjects)
 {
     Asn1EncodableVector v = new Asn1EncodableVector();
     foreach (Asn1Encodable d in derObjects)
     {
         v.Add(d);
     }
     return new BerSet(v);
 }
예제 #5
0
        /// <summary>
        /// Write myself to the given stream
        /// </summary>
        public void WriteTo(Stream stream, out string md5FingerPrint, out string sha1FingerPrint)
        {
            X509Certificate[] cert;
            AsymmetricKeyEntry privateKey;
            LoadPfx(out cert, out privateKey);

            var certsVector = new Asn1EncodableVector();
            md5FingerPrint = null;
            sha1FingerPrint = null;
            foreach (var c in cert)
            {
                var certStream = new MemoryStream(c.GetEncoded());
                var certStruct = X509CertificateStructure.GetInstance(new Asn1InputStream(certStream).ReadObject());
                certsVector.Add(certStruct);

                if (md5FingerPrint == null)
                {
                    var certData = certStream.ToArray();
                    md5FingerPrint = CreateFingerprint(new MD5Digest(), certData);
                }

                if (sha1FingerPrint == null)
                {
                    var certData = certStream.ToArray();
                    sha1FingerPrint = CreateFingerprint(new Sha1Digest(), certData);
                }
            }

            var encryptedSignature = GetSignature(signature, privateKey.Key);
            var signerInfo = new SignerInfo(
                new DerInteger(1),
                new IssuerAndSerialNumber(cert[0].IssuerDN, cert[0].SerialNumber),
                new AlgorithmIdentifier(Oids.SHA1, DerNull.Instance),
                null,
                new AlgorithmIdentifier(Oids.RSA, DerNull.Instance),
                new DerOctetString(encryptedSignature),
                null);

            var pkcs7 = new SignedData(
                new DerInteger(1),
                new DerSet(new AlgorithmIdentifier(Oids.SHA1, DerNull.Instance)),
                new ContentInfo(new DerObjectIdentifier(Oids.data), null),
                new DerSet(certsVector),
                null,
                new DerSet(signerInfo));

            //var signedData = new ContentInfo(new DERObjectIdentifier(Oids.signedData), pkcs7);

            var v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(Oids.signedData));
            v.Add(new DerTaggedObject(0, pkcs7));            
            var signedData = new DerSequence(v);

            // Save
            var data = signedData.GetEncoded();
            stream.Write(data, 0, data.Length);
        }
		public static Asn1EncodableVector FromEnumerable(
			IEnumerable e)
		{
			Asn1EncodableVector v = new Asn1EncodableVector();
			foreach (Asn1Encodable obj in e)
			{
				v.Add(obj);
			}
			return v;
		}
예제 #7
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);
		}
예제 #8
0
		public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector seq = new Asn1EncodableVector(qcStatementId);

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

			return new DerSequence(seq);
        }
예제 #9
0
		public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(p, g);

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

			return new DerSequence(v);
        }
예제 #10
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);
        }
예제 #11
0
		/**
         * Produce an object suitable for an Asn1OutputStream.
         * <pre>
         * Request         ::=     Sequence {
         *     reqCert                     CertID,
         *     singleRequestExtensions     [0] EXPLICIT Extensions OPTIONAL }
         * </pre>
         */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(reqCert);

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

			return new DerSequence(v);
        }
예제 #12
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);
        }
예제 #13
0
		public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(
				bagID, new DerTaggedObject(0, bagValue));

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

			return new DerSequence(v);
        }
예제 #14
0
        public static Asn1Set CreateDerSetFromList(
			IList derObjects)
        {
            Asn1EncodableVector v = new Asn1EncodableVector();

            foreach (Asn1Encodable ae in derObjects)
            {
                v.Add(ae);
            }

            return new DerSet(v);
        }
예제 #15
0
		internal Asn1EncodableVector BuildEncodableVector()
		{
			Asn1EncodableVector v = new Asn1EncodableVector();

			Asn1Object o;
			while ((o = ReadObject()) != null)
			{
				v.Add(o);
			}

			return v;
		}
예제 #16
0
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(
                new DerInteger(3), contentInfo);

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

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

            v.Add(commitmentTypeId);

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

            return new DerSequence(v);
        }
예제 #18
0
        /**
         * Return an ASN1 set from a tagged object. There is a special
         * case here, if an object appears to have been explicitly tagged on
         * reading but we were expecting it to be implicitly tagged in the
         * normal course of events it indicates that we lost the surrounding
         * set - so we need to add it back (this will happen if the tagged
         * object is a sequence that contains other sequences). If you are
         * dealing with implicitly tagged sets you really <b>should</b>
         * be using this method.
         *
         * @param obj the tagged object.
         * @param explicitly true if the object is meant to be explicitly tagged
         *          false otherwise.
         * @exception ArgumentException if the tagged object cannot
         *          be converted.
         */
        public static Asn1Set GetInstance(
            Asn1TaggedObject	obj,
            bool				explicitly)
        {
			Asn1Object inner = obj.GetObject();

			if (explicitly)
            {
                if (!obj.IsExplicit())
                    throw new ArgumentException("object implicit - explicit expected.");

				return (Asn1Set) inner;
            }

			//
            // constructed object which appears to be explicitly tagged
            // and it's really implicit means we have to add the
            // surrounding sequence.
            //
            if (obj.IsExplicit())
            {
                return new DerSet(inner);
            }

			if (inner is Asn1Set)
            {
                return (Asn1Set) inner;
            }

            //
            // in this case the parser returns a sequence, convert it
            // into a set.
            //
			if (inner is Asn1Sequence)
            {
				Asn1EncodableVector v = new Asn1EncodableVector();
				Asn1Sequence s = (Asn1Sequence) inner;

				foreach (Asn1Encodable ae in s)
				{
                    v.Add(ae);
                }

				// TODO Should be able to construct set directly from sequence?
				return new DerSet(v, false);
            }

			throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj");
		}
        public ECPrivateKeyStructure(
            BigInteger		key,
            DerBitString	publicKey,
            Asn1Encodable	parameters)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            Asn1EncodableVector v = new Asn1EncodableVector(
                new DerInteger(1),
                new DerOctetString(key.ToByteArrayUnsigned()));

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

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

            this.seq = new DerSequence(v);
        }
예제 #20
0
        internal Asn1EncodableVector ReadVector()
        {
            IAsn1Convertible obj = ReadObject();

            if (null == obj)
            {
                return(new Asn1EncodableVector(0));
            }

            Asn1EncodableVector v = new Asn1EncodableVector();

            do
            {
                v.Add(obj.ToAsn1Object());
            }while ((obj = ReadObject()) != null);
            return(v);
        }
예제 #21
0
        public static Asn1Set GetInstance(Asn1TaggedObject obj, bool explicitly)
        {
            Asn1Object obj2 = obj.GetObject();

            if (explicitly)
            {
                if (!obj.IsExplicit())
                {
                    throw new ArgumentException("object implicit - explicit expected.");
                }
                return((Asn1Set)obj2);
            }
            if (obj.IsExplicit())
            {
                return(new DerSet(obj2));
            }
            if (obj2 is Asn1Set)
            {
                return((Asn1Set)obj2);
            }
            if (!(obj2 is Asn1Sequence))
            {
                throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj");
            }
            Asn1EncodableVector v          = new Asn1EncodableVector(Array.Empty <Asn1Encodable>());
            IEnumerator         enumerator = ((Asn1Sequence)obj2).GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    Asn1Encodable   current = (Asn1Encodable)enumerator.Current;
                    Asn1Encodable[] objs    = new Asn1Encodable[] { current };
                    v.Add(objs);
                }
            }
            finally
            {
                if (enumerator is IDisposable disposable)
                {
                    IDisposable disposable;
                    disposable.Dispose();
                }
            }
            return(new DerSet(v, false));
        }
예제 #22
0
        internal virtual Asn1EncodableVector ReadVector(DefiniteLengthInputStream dIn)
        {
            if (dIn.Remaining < 1)
            {
                return(new Asn1EncodableVector(0));
            }

            Asn1InputStream     subStream = new Asn1InputStream(dIn);
            Asn1EncodableVector v         = new Asn1EncodableVector();
            Asn1Object          o;

            while ((o = subStream.ReadObject()) != null)
            {
                v.Add(o);
            }

            return(v);
        }
예제 #23
0
        internal Asn1EncodableVector ReadVector()
        {
            Asn1EncodableVector v = new Asn1EncodableVector();
            try
            {
                IAsn1Convertible obj;
                while ((obj = ReadObject()) != null)
                {
                    v.Add(obj.ToAsn1Object());
                }
            }
            catch (IOException e)
            {
                throw new InvalidOperationException(e.Message, e);
            }

            return v;
        }
        internal Asn1EncodableVector ReadVector()
        {
            Asn1EncodableVector v = new Asn1EncodableVector();

            try
            {
                IAsn1Convertible obj;
                while ((obj = ReadObject()) != null)
                {
                    v.Add(obj.ToAsn1Object());
                }
            }
            catch (IOException e)
            {
                throw new InvalidOperationException(e.Message, e);
            }

            return(v);
        }
예제 #25
0
        private void Parse()
        {
            lock (this)
            {
                if (null != encoded)
                {
                    Asn1EncodableVector v = new Asn1EncodableVector();
                    Asn1InputStream     e = new LazyAsn1InputStream(encoded);

                    Asn1Object o;
                    while ((o = e.ReadObject()) != null)
                    {
                        v.Add(o);
                    }

                    this.elements = v.TakeElements();
                    this.encoded  = null;
                }
            }
        }
예제 #26
0
        public static Asn1Set GetInstance(Asn1TaggedObject obj, bool explicitly)
        {
            Asn1Object @object = obj.GetObject();

            if (explicitly)
            {
                if (!obj.IsExplicit())
                {
                    throw new ArgumentException("object implicit - explicit expected.");
                }
                return((Asn1Set)@object);
            }
            else
            {
                if (obj.IsExplicit())
                {
                    return(new DerSet(@object));
                }
                if (@object is Asn1Set)
                {
                    return((Asn1Set)@object);
                }
                if (@object is Asn1Sequence)
                {
                    Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(new Asn1Encodable[0]);
                    Asn1Sequence        asn1Sequence        = (Asn1Sequence)@object;
                    foreach (Asn1Encodable asn1Encodable in asn1Sequence)
                    {
                        asn1EncodableVector.Add(new Asn1Encodable[]
                        {
                            asn1Encodable
                        });
                    }
                    return(new DerSet(asn1EncodableVector, false));
                }
                throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj");
            }
        }
예제 #27
0
        public static Asn1EncodableVector FromEnumerable(global::System.Collections.IEnumerable e)
        {
            Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();

            global::System.Collections.IEnumerator enumerator = e.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    Asn1Encodable asn1Encodable = (Asn1Encodable)enumerator.get_Current();
                    asn1EncodableVector.Add(asn1Encodable);
                }
                return(asn1EncodableVector);
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }
예제 #28
0
        public static Asn1EncodableVector FromEnumerable(IEnumerable e)
        {
            Asn1EncodableVector vector     = new Asn1EncodableVector(Array.Empty <Asn1Encodable>());
            IEnumerator         enumerator = e.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    Asn1Encodable   current = (Asn1Encodable)enumerator.Current;
                    Asn1Encodable[] objs    = new Asn1Encodable[] { current };
                    vector.Add(objs);
                }
            }
            finally
            {
                if (enumerator is IDisposable disposable)
                {
                    IDisposable disposable;
                    disposable.Dispose();
                }
            }
            return(vector);
        }
예제 #29
0
		/**
         * Produce an object suitable for an Asn1OutputStream.
         * <pre>
         * PasswordRecipientInfo ::= Sequence {
         *   version CMSVersion,   -- Always set to 0
         *   keyDerivationAlgorithm [0] KeyDerivationAlgorithmIdentifier
         *                             OPTIONAL,
         *  keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
         *  encryptedKey EncryptedKey }
         * </pre>
         */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(version);

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

			v.Add(keyEncryptionAlgorithm, encryptedKey);

			return new DerSequence(v);
        }
		/**
		* If the complete CRL includes an issuing distribution point (IDP) CRL
		* extension check the following:
		* <p>
		* (i) If the distribution point name is present in the IDP CRL extension
		* and the distribution field is present in the DP, then verify that one of
		* the names in the IDP matches one of the names in the DP. If the
		* distribution point name is present in the IDP CRL extension and the
		* distribution field is omitted from the DP, then verify that one of the
		* names in the IDP matches one of the names in the cRLIssuer field of the
		* DP.
		* </p>
		* <p>
		* (ii) If the onlyContainsUserCerts boolean is asserted in the IDP CRL
		* extension, verify that the certificate does not include the basic
		* constraints extension with the cA boolean asserted.
		* </p>
		* <p>
		* (iii) If the onlyContainsCACerts boolean is asserted in the IDP CRL
		* extension, verify that the certificate includes the basic constraints
		* extension with the cA boolean asserted.
		* </p>
		* <p>
		* (iv) Verify that the onlyContainsAttributeCerts boolean is not asserted.
		* </p>
		*
		* @param dp   The distribution point.
		* @param cert The certificate.
		* @param crl  The CRL.
		* @throws AnnotatedException if one of the conditions is not met or an error occurs.
		*/
		internal static void ProcessCrlB2(
			DistributionPoint	dp,
			object				cert,
			X509Crl				crl)
		{
			IssuingDistributionPoint idp = null;
			try
			{
				idp = IssuingDistributionPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.IssuingDistributionPoint));
			}
			catch (Exception e)
			{
				throw new Exception("0 Issuing distribution point extension could not be decoded.", e);
			}
			// (b) (2) (i)
			// distribution point name is present
			if (idp != null)
			{
				if (idp.DistributionPoint != null)
				{
					// make list of names
					DistributionPointName dpName = IssuingDistributionPoint.GetInstance(idp).DistributionPoint;
					IList names = Platform.CreateArrayList();

					if (dpName.PointType == DistributionPointName.FullName)
					{
						GeneralName[] genNames = GeneralNames.GetInstance(dpName.Name).GetNames();
						for (int j = 0; j < genNames.Length; j++)
						{
							names.Add(genNames[j]);
						}
					}
					if (dpName.PointType == DistributionPointName.NameRelativeToCrlIssuer)
					{
						Asn1EncodableVector vec = new Asn1EncodableVector();
						try
						{
							IEnumerator e = Asn1Sequence.GetInstance(
								Asn1Sequence.FromByteArray(crl.IssuerDN.GetEncoded())).GetEnumerator();
							while (e.MoveNext())
							{
								vec.Add((Asn1Encodable)e.Current);
							}
						}
						catch (IOException e)
						{
							throw new Exception("Could not read CRL issuer.", e);
						}
						vec.Add(dpName.Name);
						names.Add(new GeneralName(X509Name.GetInstance(new DerSequence(vec))));
					}
					bool matches = false;
					// verify that one of the names in the IDP matches one
					// of the names in the DP.
					if (dp.DistributionPointName != null)
					{
						dpName = dp.DistributionPointName;
						GeneralName[] genNames = null;
						if (dpName.PointType == DistributionPointName.FullName)
						{
							genNames = GeneralNames.GetInstance(dpName.Name).GetNames();
						}
						if (dpName.PointType == DistributionPointName.NameRelativeToCrlIssuer)
						{
							if (dp.CrlIssuer != null)
							{
								genNames = dp.CrlIssuer.GetNames();
							}
							else
							{
								genNames = new GeneralName[1];
								try
								{
									genNames[0] = new GeneralName(
										PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert));
								}
								catch (IOException e)
								{
									throw new Exception("Could not read certificate issuer.", e);
								}
							}
							for (int j = 0; j < genNames.Length; j++)
							{
								IEnumerator e = Asn1Sequence.GetInstance(genNames[j].Name.ToAsn1Object()).GetEnumerator();
								Asn1EncodableVector vec = new Asn1EncodableVector();
								while (e.MoveNext())
								{
									vec.Add((Asn1Encodable)e.Current);
								}
								vec.Add(dpName.Name);
								genNames[j] = new GeneralName(X509Name.GetInstance(new DerSequence(vec)));
							}
						}
						if (genNames != null)
						{
							for (int j = 0; j < genNames.Length; j++)
							{
								if (names.Contains(genNames[j]))
								{
									matches = true;
									break;
								}
							}
						}
						if (!matches)
						{
							throw new Exception(
								"No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point.");
						}
					}
						// verify that one of the names in
						// the IDP matches one of the names in the cRLIssuer field of
						// the DP
					else
					{
						if (dp.CrlIssuer == null)
						{
							throw new Exception("Either the cRLIssuer or the distributionPoint field must "
								+ "be contained in DistributionPoint.");
						}
						GeneralName[] genNames = dp.CrlIssuer.GetNames();
						for (int j = 0; j < genNames.Length; j++)
						{
							if (names.Contains(genNames[j]))
							{
								matches = true;
								break;
							}
						}
						if (!matches)
						{
							throw new Exception(
								"No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point.");
						}
					}
				}
				BasicConstraints bc = null;
				try
				{
					bc = BasicConstraints.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(
						(IX509Extension)cert, X509Extensions.BasicConstraints));
				}
				catch (Exception e)
				{
					throw new Exception("Basic constraints extension could not be decoded.", e);
				}

				//if (cert is X509Certificate)
				{
					// (b) (2) (ii)
					if (idp.OnlyContainsUserCerts && ((bc != null) && bc.IsCA()))
					{
						throw new Exception("CA Cert CRL only contains user certificates.");
					}

					// (b) (2) (iii)
					if (idp.OnlyContainsCACerts && (bc == null || !bc.IsCA()))
					{
						throw new Exception("End CRL only contains CA certificates.");
					}
				}

				// (b) (2) (iv)
				if (idp.OnlyContainsAttributeCerts)
				{
					throw new Exception("onlyContainsAttributeCerts boolean is asserted.");
				}
			}
		}
		/**
		* generate an enveloped object that contains an CMS Enveloped Data
		* object using the given provider and the passed in key generator.
		* @throws java.io.IOException
		*/
		private Stream Open(
			Stream				outStr,
			string				macOid,
			CipherKeyGenerator	keyGen)
		{
			// FIXME Will this work for macs?
			byte[] encKeyBytes = keyGen.GenerateKey();
			KeyParameter encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes);

			Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes);

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

			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);
				}
			}

			// FIXME Only passing key at the moment
//			return Open(outStr, macAlgId, cipherParameters, recipientInfos);
			return Open(outStr, macAlgId, encKey, recipientInfos);
		}
예제 #32
0
 private static byte[] BuildOCSPResponse(byte[] BasicOCSPResponse) {
     DerOctetString doctet = new DerOctetString(BasicOCSPResponse);
     Asn1EncodableVector v2 = new Asn1EncodableVector();
     v2.Add(OcspObjectIdentifiers.PkixOcspBasic);
     v2.Add(doctet);
     DerEnumerated den = new DerEnumerated(0);
     Asn1EncodableVector v3 = new Asn1EncodableVector();
     v3.Add(den);
     v3.Add(new DerTaggedObject(true, 0, new DerSequence(v2)));            
     DerSequence seq = new DerSequence(v3);
     return seq.GetEncoded();
 }
예제 #33
0
 private DerSet GetAuthenticatedAttributeSet(byte[] secondDigest, DateTime signingTime, byte[] ocsp) {
     Asn1EncodableVector attribute = new Asn1EncodableVector();
     Asn1EncodableVector v = new Asn1EncodableVector();
     v.Add(new DerObjectIdentifier(ID_CONTENT_TYPE));
     v.Add(new DerSet(new DerObjectIdentifier(ID_PKCS7_DATA)));
     attribute.Add(new DerSequence(v));
     v = new Asn1EncodableVector();
     v.Add(new DerObjectIdentifier(ID_SIGNING_TIME));
     v.Add(new DerSet(new DerUtcTime(signingTime)));
     attribute.Add(new DerSequence(v));
     v = new Asn1EncodableVector();
     v.Add(new DerObjectIdentifier(ID_MESSAGE_DIGEST));
     v.Add(new DerSet(new DerOctetString(secondDigest)));
     attribute.Add(new DerSequence(v));
     if (ocsp != null) {
         v = new Asn1EncodableVector();
         v.Add(new DerObjectIdentifier(ID_ADBE_REVOCATION));
         DerOctetString doctet = new DerOctetString(ocsp);
         Asn1EncodableVector vo1 = new Asn1EncodableVector();
         Asn1EncodableVector v2 = new Asn1EncodableVector();
         v2.Add(OcspObjectIdentifiers.PkixOcspBasic);
         v2.Add(doctet);
         DerEnumerated den = new DerEnumerated(0);
         Asn1EncodableVector v3 = new Asn1EncodableVector();
         v3.Add(den);
         v3.Add(new DerTaggedObject(true, 0, new DerSequence(v2)));
         vo1.Add(new DerSequence(v3));
         v.Add(new DerSet(new DerSequence(new DerTaggedObject(true, 1, new DerSequence(vo1)))));
         attribute.Add(new DerSequence(v));
     }
     return new DerSet(attribute);
 }
예제 #34
0
        /**
        * Added by Aiken Sam, 2006-11-15, modifed by Martin Brunecky 07/12/2007
        * to start with the timeStampToken (signedData 1.2.840.113549.1.7.2).
        * Token is the TSA response without response status, which is usually
        * handled by the (vendor supplied) TSA request/response interface).
        * @param timeStampToken byte[] - time stamp token, DER encoded signedData
        * @return ASN1EncodableVector
        * @throws IOException
        */
        private Asn1EncodableVector BuildUnauthenticatedAttributes(byte[] timeStampToken) {
            if (timeStampToken == null)
                return null;

            // @todo: move this together with the rest of the defintions
            String ID_TIME_STAMP_TOKEN = "1.2.840.113549.1.9.16.2.14"; // RFC 3161 id-aa-timeStampToken

            Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(timeStampToken));
            Asn1EncodableVector unauthAttributes = new Asn1EncodableVector();

            Asn1EncodableVector v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(ID_TIME_STAMP_TOKEN)); // id-aa-timeStampToken
            Asn1Sequence seq = (Asn1Sequence) tempstream.ReadObject();
            v.Add(new DerSet(seq));

            unauthAttributes.Add(new DerSequence(v));
            return unauthAttributes;
        }
예제 #35
0
        /**
        * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
        * in the signerInfo can also be set, OR a time-stamp-authority client
        * may be provided.
        * @param secondDigest the digest in the authenticatedAttributes
        * @param signingTime the signing time in the authenticatedAttributes
        * @param tsaClient TSAClient - null or an optional time stamp authority client
        * @return byte[] the bytes for the PKCS7SignedData object
        * @since   2.1.6
        */
        public byte[] GetEncodedPKCS7(byte[] secondDigest, DateTime signingTime, ITSAClient tsaClient, byte[] ocsp) {
            if (externalDigest != null) {
                digest = externalDigest;
                if (RSAdata != null)
                    RSAdata = externalRSAdata;
            }
            else if (externalRSAdata != null && RSAdata != null) {
                RSAdata = externalRSAdata;
                sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                digest = sig.GenerateSignature();
            }
            else {
                if (RSAdata != null) {
                    RSAdata = new byte[messageDigest.GetDigestSize()];
                    messageDigest.DoFinal(RSAdata, 0);
                    sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                }
                digest = sig.GenerateSignature();
            }
            
            // Create the set of Hash algorithms
            Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector();
            foreach (string dal in digestalgos.Keys) {
                Asn1EncodableVector algos = new Asn1EncodableVector();
                algos.Add(new DerObjectIdentifier(dal));
                algos.Add(DerNull.Instance);
                digestAlgorithms.Add(new DerSequence(algos));
            }
            
            // Create the contentInfo.
            Asn1EncodableVector v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(ID_PKCS7_DATA));
            if (RSAdata != null)
                v.Add(new DerTaggedObject(0, new DerOctetString(RSAdata)));
            DerSequence contentinfo = new DerSequence(v);
            
            // Get all the certificates
            //
            v = new Asn1EncodableVector();
            foreach (X509Certificate xcert in certs) {
                Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(xcert.GetEncoded()));
                v.Add(tempstream.ReadObject());
            }
            
            DerSet dercertificates = new DerSet(v);
            
            // Create signerinfo structure.
            //
            Asn1EncodableVector signerinfo = new Asn1EncodableVector();
            
            // Add the signerInfo version
            //
            signerinfo.Add(new DerInteger(signerversion));
            
            v = new Asn1EncodableVector();
            v.Add(GetIssuer(signCert.GetTbsCertificate()));
            v.Add(new DerInteger(signCert.SerialNumber));
            signerinfo.Add(new DerSequence(v));
            
            // Add the digestAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestAlgorithm));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));
            
            // add the authenticated attribute if present
            if (secondDigest != null /*&& signingTime != null*/) {
                signerinfo.Add(new DerTaggedObject(false, 0, GetAuthenticatedAttributeSet(secondDigest, signingTime, ocsp)));
            }
            // Add the digestEncryptionAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestEncryptionAlgorithm));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));
            
            // Add the digest
            signerinfo.Add(new DerOctetString(digest));
            
            // When requested, go get and add the timestamp. May throw an exception.
            // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15
            // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest
            if (tsaClient != null) {
                byte[] tsImprint = new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(digest);
                byte[] tsToken = tsaClient.GetTimeStampToken(this, tsImprint);
                if (tsToken != null) {
                    Asn1EncodableVector unauthAttributes = BuildUnauthenticatedAttributes(tsToken);
                    if (unauthAttributes != null) {
                        signerinfo.Add(new DerTaggedObject(false, 1, new DerSet(unauthAttributes)));
                    }
                }
            }
            
            // Finally build the body out of all the components above
            Asn1EncodableVector body = new Asn1EncodableVector();
            body.Add(new DerInteger(version));
            body.Add(new DerSet(digestAlgorithms));
            body.Add(contentinfo);
            body.Add(new DerTaggedObject(false, 0, dercertificates));
            
//                if (crls.Count > 0) {
//                    v = new Asn1EncodableVector();
//                    for (Iterator i = crls.Iterator();i.HasNext();) {
//                        Asn1InputStream t = new Asn1InputStream(new ByteArrayInputStream((((X509CRL)i.Next()).GetEncoded())));
//                        v.Add(t.ReadObject());
//                    }
//                    DERSet dercrls = new DERSet(v);
//                    body.Add(new DERTaggedObject(false, 1, dercrls));
//                }
            
            // Only allow one signerInfo
            body.Add(new DerSet(new DerSequence(signerinfo)));
            
            // Now we have the body, wrap it in it's PKCS7Signed shell
            // and return it
            //
            Asn1EncodableVector whole = new Asn1EncodableVector();
            whole.Add(new DerObjectIdentifier(ID_PKCS7_SIGNED_DATA));
            whole.Add(new DerTaggedObject(0, new DerSequence(body)));
            
            MemoryStream bOut = new MemoryStream();
            
            Asn1OutputStream dout = new Asn1OutputStream(bOut);
            dout.WriteObject(new DerSequence(whole));
            dout.Close();
            
            return bOut.ToArray();
        }
			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 IOException("encoding error." + e);
                    }
                    catch (SignatureException e)
                    {
                        throw new IOException("error creating signature." + e);
                    }
                    catch (CertificateEncodingException e)
                    {
                        throw new IOException("error creating sid." + e);
                    }
                }

				WriteToGenerator(_sigGen, new DerSet(signerInfos));

				_sigGen.Close();
                _sGen.Close();
				base.Close();
			}
예제 #37
0
        /**
         * Produce an object suitable for an Asn1OutputStream.
         * <pre>
         *  SignerInfo ::= Sequence {
         *      version Version,
         *      SignerIdentifier sid,
         *      digestAlgorithm DigestAlgorithmIdentifier,
         *      authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,
         *      digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
         *      encryptedDigest EncryptedDigest,
         *      unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL
         *  }
         *
         *  EncryptedDigest ::= OCTET STRING
         *
         *  DigestAlgorithmIdentifier ::= AlgorithmIdentifier
         *
         *  DigestEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
         * </pre>
         */
        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(
                version, sid, digAlgorithm);

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

            v.Add(digEncryptionAlgorithm, encryptedDigest);

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

            return new DerSequence(v);
        }
예제 #38
0
        public Asn1Object ReadObject()
        {
            int tag = ReadByte();

            if (tag == -1)
            {
                if (eofFound)
                {
                    throw new EndOfStreamException("attempt to read past end of file.");
                }

                eofFound = true;

                return(null);
            }

            int tagNo = 0;

            if ((tag & Asn1Tags.Tagged) != 0 || (tag & Asn1Tags.Application) != 0)
            {
                tagNo = ReadTagNumber(tag);
            }

            int length = ReadLength();

            if (length < 0)                // indefinite length method
            {
                switch (tag)
                {
                case Asn1Tags.Null:
                    return(BerNull.Instance);

                case Asn1Tags.Sequence | Asn1Tags.Constructed:
                {
                    Asn1EncodableVector v = BuildEncodableVector(EndOfStream);
                    return(new BerSequence(v));
                }

                case Asn1Tags.Set | Asn1Tags.Constructed:
                {
                    Asn1EncodableVector v = BuildEncodableVector(EndOfStream);
                    return(new BerSet(v, false));
                }

                case Asn1Tags.OctetString | Asn1Tags.Constructed:
                    return(BuildConstructedOctetString(EndOfStream));

                default:
                {
                    //
                    // with tagged object tag number is bottom 5 bits
                    //
                    if ((tag & (int)Asn1Tags.Tagged) != 0)
                    {
                        //
                        // simple type - implicit... return an octet string
                        //
                        if ((tag & (int)Asn1Tags.Constructed) == 0)
                        {
                            byte[] bytes = ReadIndefiniteLengthFully();

                            return(new BerTaggedObject(false, tagNo, new DerOctetString(bytes)));
                        }

                        //
                        // either constructed or explicitly tagged
                        //
                        Asn1Object dObj = ReadObject();

                        if (dObj == EndOfStream)                                     // empty tag!
                        {
                            return(new DerTaggedObject(tagNo));
                        }

                        Asn1Object next = ReadObject();

                        //
                        // explicitly tagged (probably!) - if it isn't we'd have to
                        // tell from the context
                        //
                        if (next == EndOfStream)
                        {
                            return(new BerTaggedObject(tagNo, dObj));
                        }

                        //
                        // another implicit object, we'll create a sequence...
                        //
                        Asn1EncodableVector v = new Asn1EncodableVector(dObj);

                        do
                        {
                            v.Add(next);
                            next = ReadObject();
                        }while (next != EndOfStream);

                        return(new BerTaggedObject(false, tagNo, new BerSequence(v)));
                    }

                    throw new IOException("unknown Ber object encountered");
                }
                }
            }
            else
            {
                if (tag == 0 && length == 0)    // end of contents marker.
                {
                    return(EndOfStream);
                }

                byte[] bytes = new byte[length];

                ReadFully(bytes);

                return(BuildObject(tag, tagNo, bytes));
            }
        }
        /**
        * 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);
        }
예제 #40
0
        /**
         * build an object given its tag and a byte stream to construct it
         * from.
         */
        internal Asn1Object BuildObject(
            int tag,
            int tagNo,
            byte[]      bytes)
        {
            if ((tag & Asn1Tags.Application) != 0)
            {
                return(new DerApplicationSpecific(tagNo, bytes));
            }

            switch (tag)
            {
            case Asn1Tags.Null:
                return(DerNull.Instance);

            case Asn1Tags.Sequence | Asn1Tags.Constructed:
            {
                Asn1EncodableVector v = BuildDerEncodableVector(bytes);
                return(new DerSequence(v));
            }

            case Asn1Tags.Set | Asn1Tags.Constructed:
            {
                Asn1EncodableVector v = BuildDerEncodableVector(bytes);
                return(new DerSet(v, false));
            }

            case Asn1Tags.Boolean:
                return(new DerBoolean(bytes));

            case Asn1Tags.Integer:
                return(new DerInteger(bytes));

            case Asn1Tags.Enumerated:
                return(new DerEnumerated(bytes));

            case Asn1Tags.ObjectIdentifier:
                return(new DerObjectIdentifier(bytes));

            case Asn1Tags.BitString:
            {
                int    padBits = bytes[0];
                byte[] data    = new byte[bytes.Length - 1];
                Array.Copy(bytes, 1, data, 0, bytes.Length - 1);
                return(new DerBitString(data, padBits));
            }

            case Asn1Tags.NumericString:
                return(new DerNumericString(bytes));

            case Asn1Tags.Utf8String:
                return(new DerUtf8String(bytes));

            case Asn1Tags.PrintableString:
                return(new DerPrintableString(bytes));

            case Asn1Tags.IA5String:
                return(new DerIA5String(bytes));

            case Asn1Tags.T61String:
                return(new DerT61String(bytes));

            case Asn1Tags.VisibleString:
                return(new DerVisibleString(bytes));

            case Asn1Tags.GeneralString:
                return(new DerGeneralString(bytes));

            case Asn1Tags.UniversalString:
                return(new DerUniversalString(bytes));

            case Asn1Tags.BmpString:
                return(new DerBmpString(bytes));

            case Asn1Tags.OctetString:
                return(new DerOctetString(bytes));

            case Asn1Tags.OctetString | Asn1Tags.Constructed:
                return(BuildDerConstructedOctetString(bytes));

            case Asn1Tags.UtcTime:
                return(new DerUtcTime(bytes));

            case Asn1Tags.GeneralizedTime:
                return(new DerGeneralizedTime(bytes));

            default:
            {
                //
                // with tagged object tag number is bottom 5 bits
                //
                if ((tag & (int)Asn1Tags.Tagged) != 0)
                {
                    bool isImplicit = ((tag & (int)Asn1Tags.Constructed) == 0);

                    if (bytes.Length == 0)                                    // empty tag!
                    {
                        Asn1Encodable ae = isImplicit
                                                                ?       (Asn1Encodable)DerNull.Instance
                                                                :       new DerSequence();

                        return(new DerTaggedObject(false, tagNo, ae));
                    }

                    //
                    // simple type - implicit... return an octet string
                    //
                    if (isImplicit)
                    {
                        return(new DerTaggedObject(false, tagNo, new DerOctetString(bytes)));
                    }

                    Asn1InputStream aIn  = new Asn1InputStream(bytes);
                    Asn1Encodable   dObj = aIn.ReadObject();


                    // explicitly tagged (probably!) - if it isn't we'd have to
                    // tell from the context

                    //if (aIn.available() == 0)
                    if (aIn.Position == bytes.Length)                             //FIXME?
                    {
                        return(new DerTaggedObject(tagNo, dObj));
                    }

                    //
                    // another implicit object, we'll create a sequence...
                    //
                    Asn1EncodableVector v = new Asn1EncodableVector();

                    while (dObj != null)
                    {
                        v.Add(dObj);
                        dObj = aIn.ReadObject();
                    }

                    return(new DerTaggedObject(false, tagNo, new DerSequence(v)));
                }

                return(new DerUnknownTag(tag, bytes));
            }
            }
        }