Inheritance: DerOctetString, IEnumerable
        /**
        * Generate an object that contains an CMS Compressed Data
        */
        public CmsCompressedData Generate(
            CmsProcessable	content,
            string			compressionOid)
        {
            AlgorithmIdentifier comAlgId;
            Asn1OctetString comOcts;

            try
            {
                MemoryStream bOut = new MemoryStream();
                ZOutputStream zOut = new ZOutputStream(bOut, JZlib.Z_DEFAULT_COMPRESSION);

                content.Write(zOut);

                zOut.Dispose();

                comAlgId = new AlgorithmIdentifier(new DerObjectIdentifier(compressionOid));
                comOcts = new BerOctetString(bOut.ToArray());
            }
            catch (IOException e)
            {
                throw new CmsException("exception encoding data.", e);
            }

            ContentInfo comContent = new ContentInfo(CmsObjectIdentifiers.Data, comOcts);
            ContentInfo contentInfo = new ContentInfo(
                CmsObjectIdentifiers.CompressedData,
                new CompressedData(comAlgId, comContent));

            return new CmsCompressedData(contentInfo);
        }
        internal override void Encode(
            DerOutputStream derOut)
        {
            if (derOut is Asn1OutputStream || derOut is BerOutputStream)
            {
                derOut.WriteTag((byte)(Asn1Tags.Constructed | Asn1Tags.Tagged), tagNo);
                derOut.WriteByte(0x80);

                if (!IsEmpty())
                {
                    if (!explicitly)
                    {
                        IEnumerable eObj;
                        if (obj is Asn1OctetString)
                        {
                            if (obj is BerOctetString)
                            {
                                eObj = (BerOctetString)obj;
                            }
                            else
                            {
                                Asn1OctetString octs = (Asn1OctetString)obj;
                                eObj = new BerOctetString(octs.GetOctets());
                            }
                        }
                        else if (obj is Asn1Sequence)
                        {
                            eObj = (Asn1Sequence)obj;
                        }
                        else if (obj is Asn1Set)
                        {
                            eObj = (Asn1Set)obj;
                        }
                        else
                        {
                            throw Platform.CreateNotImplementedException(obj.GetType().Name);
                        }

                        foreach (Asn1Encodable o in eObj)
                        {
                            derOut.WriteObject(o);
                        }
                    }
                    else
                    {
                        derOut.WriteObject(obj);
                    }
                }

                derOut.WriteByte(0x00);
                derOut.WriteByte(0x00);
            }
            else
            {
                base.Encode(derOut);
            }
        }
Ejemplo n.º 3
0
		internal override void Encode(
			DerOutputStream derOut)
		{
			if (derOut is Asn1OutputStream || derOut is BerOutputStream)
			{
				derOut.WriteTag((byte)(Asn1Tags.Constructed | Asn1Tags.Tagged), tagNo);
				derOut.WriteByte(0x80);

				if (!IsEmpty())
				{
					if (!explicitly)
					{
						IEnumerable eObj;
						if (obj is Asn1OctetString)
						{
							if (obj is BerOctetString)
							{
								eObj = (BerOctetString) obj;
							}
							else
							{
								Asn1OctetString octs = (Asn1OctetString)obj;
								eObj = new BerOctetString(octs.GetOctets());
							}
						}
						else if (obj is Asn1Sequence)
						{
							eObj = (Asn1Sequence) obj;
						}
						else if (obj is Asn1Set)
						{
							eObj = (Asn1Set) obj;
						}
						else
						{
							throw Platform.CreateNotImplementedException(obj.GetType().Name);
						}

						foreach (Asn1Encodable o in eObj)
						{
							derOut.WriteObject(o);
						}
					}
					else
					{
						derOut.WriteObject(obj);
					}
				}

				derOut.WriteByte(0x00);
				derOut.WriteByte(0x00);
			}
			else
			{
				base.Encode(derOut);
			}
		}
Ejemplo n.º 4
0
        public static Asn1OctetString GetInstance(Asn1TaggedObject obj, bool isExplicit)
        {
            Asn1Object @object = obj.GetObject();

            if (isExplicit || @object is Asn1OctetString)
            {
                return(GetInstance(@object));
            }
            return(BerOctetString.FromSequence(Asn1Sequence.GetInstance(@object)));
        }
Ejemplo n.º 5
0
        public static Asn1OctetString GetInstance(Asn1TaggedObject obj, bool isExplicit)
        {
            Asn1Object obj2 = obj.GetObject();

            if (!isExplicit && !(obj2 is Asn1OctetString))
            {
                return(BerOctetString.FromSequence(Asn1Sequence.GetInstance(obj2)));
            }
            return(GetInstance(obj2));
        }
Ejemplo n.º 6
0
        internal override void Encode(DerOutputStream derOut)
        {
            if (derOut is Asn1OutputStream || derOut is BerOutputStream)
            {
                derOut.WriteTag(160, this.tagNo);
                derOut.WriteByte(128);
                if (!base.IsEmpty())
                {
                    if (!this.explicitly)
                    {
                        IEnumerable enumerable;
                        if (this.obj is Asn1OctetString)
                        {
                            if (this.obj is BerOctetString)
                            {
                                enumerable = (BerOctetString)this.obj;
                            }
                            else
                            {
                                Asn1OctetString asn1OctetString = (Asn1OctetString)this.obj;
                                enumerable = new BerOctetString(asn1OctetString.GetOctets());
                            }
                        }
                        else if (this.obj is Asn1Sequence)
                        {
                            enumerable = (Asn1Sequence)this.obj;
                        }
                        else
                        {
                            if (!(this.obj is Asn1Set))
                            {
                                throw Platform.CreateNotImplementedException(this.obj.GetType().Name);
                            }
                            enumerable = (Asn1Set)this.obj;
                        }
                        using (IEnumerator enumerator = enumerable.GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                Asn1Encodable obj = (Asn1Encodable)enumerator.Current;
                                derOut.WriteObject(obj);
                            }
                            goto IL_119;
                        }
                    }
                    derOut.WriteObject(this.obj);
                }
IL_119:
                derOut.WriteByte(0);
                derOut.WriteByte(0);
                return;
            }
            base.Encode(derOut);
        }
Ejemplo n.º 7
0
 internal override void Encode(DerOutputStream derOut)
 {
     if (derOut is Asn1OutputStream || derOut is BerOutputStream)
     {
         derOut.WriteTag(160, tagNo);
         derOut.WriteByte(128);
         if (!IsEmpty())
         {
             if (!explicitly)
             {
                 IEnumerable enumerable;
                 if (base.obj is Asn1OctetString)
                 {
                     if (base.obj is BerOctetString)
                     {
                         enumerable = (BerOctetString)base.obj;
                     }
                     else
                     {
                         Asn1OctetString asn1OctetString = (Asn1OctetString)base.obj;
                         enumerable = new BerOctetString(asn1OctetString.GetOctets());
                     }
                 }
                 else if (base.obj is Asn1Sequence)
                 {
                     enumerable = (Asn1Sequence)base.obj;
                 }
                 else
                 {
                     if (!(base.obj is Asn1Set))
                     {
                         throw Platform.CreateNotImplementedException(base.obj.GetType().Name);
                     }
                     enumerable = (Asn1Set)base.obj;
                 }
                 foreach (Asn1Encodable item in enumerable)
                 {
                     derOut.WriteObject(item);
                 }
             }
             else
             {
                 derOut.WriteObject(obj);
             }
         }
         derOut.WriteByte(0);
         derOut.WriteByte(0);
     }
     else
     {
         base.Encode(derOut);
     }
 }
        public Asn1Object ToAsn1Object()
        {
            Asn1Object result;

            try
            {
                result = new BerOctetString(Streams.ReadAll(this.GetOctetStream()));
            }
            catch (IOException ex)
            {
                throw new Asn1ParsingException("IOException converting stream to byte array: " + ex.Message, ex);
            }
            return(result);
        }
	    /**
	     * 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();
				Stream mOut = new TeeOutputStream(bOut, new MacOutputStream(mac));

				content.Write(mOut);

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

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

				byte[] macOctets = MacUtilities.DoFinal(mac);
				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);
		}
Ejemplo n.º 10
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,
            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));
				signerInfos.Add(signer.ToSignerInfo());
            }

			//
            // add the SignerInfo objects
            //
			DerObjectIdentifier contentTypeOID;
			bool isCounterSignature;

			if (signedContentType != null)
			{
				contentTypeOID = new DerObjectIdentifier(signedContentType);
				isCounterSignature = false;
			}
			else
			{
				contentTypeOID = CmsObjectIdentifiers.Data;
				isCounterSignature = true;
			}

			foreach (SignerInf signer in signerInfs)
            {
				try
                {
					digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID));
					signerInfos.Add(signer.ToSignerInfo(contentTypeOID, content, rand, isCounterSignature));
				}
                catch (IOException e)
                {
                    throw new CmsException("encoding error.", e);
                }
                catch (InvalidKeyException e)
                {
                    throw new CmsException("key inappropriate for signature.", e);
                }
                catch (SignatureException e)
                {
                    throw new CmsException("error creating signature.", e);
                }
                catch (CertificateEncodingException e)
                {
                    throw new CmsException("error creating sid.", e);
                }
            }

			Asn1Set certificates = null;

			if (_certs.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();
                try
                {
                    content.Write(bOut);
                }
                catch (IOException e)
                {
                    throw new CmsException("encapsulation error.", e);
                }

				octs = new BerOctetString(bOut.ToArray());
            }

			Asn1.Cms.ContentInfo encInfo = new Asn1.Cms.ContentInfo(contentTypeOID, octs);

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

            Asn1.Cms.ContentInfo contentInfo = new Asn1.Cms.ContentInfo(
                PkcsObjectIdentifiers.SignedData, sd);

            return new CmsSignedData(content, contentInfo);
        }
Ejemplo n.º 11
0
        public void Save(
        	Stream			stream,
        	char[]			password,
        	SecureRandom	random)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");
            if (password == null)
                throw new ArgumentNullException("password");
            if (random == null)
                throw new ArgumentNullException("random");

            ContentInfo[] c = new ContentInfo[2];

            //
            // handle the key
            //
            Asn1EncodableVector keyS = new Asn1EncodableVector();
            foreach (string name in keys.Keys)
            {
                byte[] kSalt = new byte[saltSize];
                random.NextBytes(kSalt);

                AsymmetricKeyEntry privKey = (AsymmetricKeyEntry) keys[name];
                EncryptedPrivateKeyInfo kInfo =
                    EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                        keyAlgorithm, password, kSalt, minIterations, privKey.Key);

                Asn1EncodableVector kName = new Asn1EncodableVector();

                foreach (string oid in privKey.BagAttributeKeys)
                {
                    kName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(privKey[oid])));
                }

                //
                // make sure we have a local key-id
                //
                if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    X509CertificateEntry ct = GetCertificate(name);

                    SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
                        ct.Certificate.GetPublicKey());

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

                //
                // make sure we are using the local alias on store
                //
                DerBmpString nm = (DerBmpString) privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName];
                if (nm == null || !nm.GetString().Equals(name))
                {
                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                SafeBag kBag = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, kInfo.ToAsn1Object(), new DerSet(kName));
                keyS.Add(kBag);
            }

            byte[] derEncodedBytes = new DerSequence(keyS).GetDerEncoded();

            BerOctetString keyString = new BerOctetString(derEncodedBytes);

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

            random.NextBytes(cSalt);

            Asn1EncodableVector	certSeq = new Asn1EncodableVector();
            Pkcs12PbeParams		cParams = new Pkcs12PbeParams(cSalt, minIterations);
            AlgorithmIdentifier	cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object());
            Hashtable			doneCerts = new Hashtable();

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

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in certEntry.BagAttributeKeys)
                {
                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(certEntry[oid])));
                }

                //
                // make sure we are using the local alias on store
                //
                DerBmpString nm = (DerBmpString)certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName];
                if (nm == null || !nm.GetString().Equals(name))
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                //
                // make sure we have a local key-id
                //
                if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
                        certEntry.Certificate.GetPublicKey());

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

                SafeBag sBag = new SafeBag(
                    PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName));

                certSeq.Add(sBag);

                doneCerts.Add(certEntry.Certificate, certEntry.Certificate);
            }

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

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

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

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(cert[oid])));
                }

                //
                // make sure we are using the local alias on store
                //
                DerBmpString nm = (DerBmpString) cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName];
                if (nm == null || !nm.GetString().Equals(certId))
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(certId))));
                }

                SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag,
                    cBag.ToAsn1Object(), new DerSet(fName));

                certSeq.Add(sBag);

                doneCerts.Add(cert, cert);
            }

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

                if (doneCerts[cert] != null)
                {
                    continue;
                }

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

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    fName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(cert[oid])));
                }

                SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName));

                certSeq.Add(sBag);
            }

            derEncodedBytes = new DerSequence(certSeq).GetDerEncoded();

            byte[] certBytes = EncryptData(new AlgorithmIdentifier(certAlgorithm, cParams), derEncodedBytes, password);
            EncryptedData cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes));

            c[0] = new ContentInfo(PkcsObjectIdentifiers.Data, keyString);
            c[1] = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object());

            AuthenticatedSafe auth = new AuthenticatedSafe(c);

            byte[] pkg = auth.GetEncoded();

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

            //
            // create the mac
            //
            byte[] mSalt = new byte[20];
            int itCount = minIterations;

            random.NextBytes(mSalt);

            byte[] data = ((Asn1OctetString)mainInfo.Content).GetOctets();

            Asn1Encodable parameters = PbeUtilities.GenerateAlgorithmParameters(OiwObjectIdentifiers.IdSha1, mSalt, itCount);
            ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters(
                OiwObjectIdentifiers.IdSha1, password, parameters);
            IMac mac = (IMac)PbeUtilities.CreateEngine(OiwObjectIdentifiers.IdSha1);

            mac.Init(keyParameters);

            mac.BlockUpdate(data, 0, data.Length);

            byte[] res = new byte[mac.GetMacSize()];

            mac.DoFinal(res, 0);

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

            MacData mData = new MacData(dInfo, mSalt, itCount);

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

            BerOutputStream berOut = new BerOutputStream(stream);

            berOut.WriteObject(pfx);
        }
Ejemplo n.º 12
0
        public void Save(
            Stream			stream,
            char[]			password,
            SecureRandom	random)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");
            if (password == null)
                throw new ArgumentNullException("password");
            if (random == null)
                throw new ArgumentNullException("random");

            //
            // handle the key
            //
            Asn1EncodableVector keyS = new Asn1EncodableVector();
            foreach (string name in keys.Keys)
            {
                byte[] kSalt = new byte[SaltSize];
                random.NextBytes(kSalt);

                AsymmetricKeyEntry privKey = (AsymmetricKeyEntry) keys[name];
                EncryptedPrivateKeyInfo kInfo =
                    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)));
                }

                SafeBag kBag = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, kInfo.ToAsn1Object(), new DerSet(kName));
                keyS.Add(kBag);
            }

            byte[] derEncodedBytes = new DerSequence(keyS).GetDerEncoded();

            BerOctetString keyString = new BerOctetString(derEncodedBytes);

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

            random.NextBytes(cSalt);

            Asn1EncodableVector	certSeq = 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)));
                }

                SafeBag sBag = new SafeBag(
                    PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName));

                certSeq.Add(sBag);

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

                SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag,
                    cBag.ToAsn1Object(), new DerSet(fName));

                certSeq.Add(sBag);

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

                SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName));

                certSeq.Add(sBag);
            }

            derEncodedBytes = new DerSequence(certSeq).GetDerEncoded();

            byte[] certBytes = CryptPbeData(true, cAlgId, password, false, derEncodedBytes);

            EncryptedData cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes));

            ContentInfo[] info = new ContentInfo[]
            {
                new ContentInfo(PkcsObjectIdentifiers.Data, keyString),
                new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object())
            };

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

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

            //
            // create the mac
            //
            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 mData = new MacData(dInfo, mSalt, MinIterations);

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

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

            derOut.WriteObject(pfx);
        }
Ejemplo n.º 13
0
 internal override void Encode(DerOutputStream derOut)
 {
     if (derOut is Asn1OutputStream || derOut is BerOutputStream)
     {
         derOut.WriteTag(160, tagNo);
         ((Stream)derOut).WriteByte((byte)128);
         if (!IsEmpty())
         {
             if (!explicitly)
             {
                 global::System.Collections.IEnumerable enumerable;
                 if (obj is Asn1OctetString)
                 {
                     if (obj is BerOctetString)
                     {
                         enumerable = (BerOctetString)obj;
                     }
                     else
                     {
                         Asn1OctetString asn1OctetString = (Asn1OctetString)obj;
                         enumerable = new BerOctetString(asn1OctetString.GetOctets());
                     }
                 }
                 else if (obj is Asn1Sequence)
                 {
                     enumerable = (Asn1Sequence)obj;
                 }
                 else
                 {
                     if (!(obj is Asn1Set))
                     {
                         throw Platform.CreateNotImplementedException(Platform.GetTypeName(obj));
                     }
                     enumerable = (Asn1Set)obj;
                 }
                 {
                     global::System.Collections.IEnumerator enumerator = enumerable.GetEnumerator();
                     try
                     {
                         while (enumerator.MoveNext())
                         {
                             Asn1Encodable asn1Encodable = (Asn1Encodable)enumerator.get_Current();
                             derOut.WriteObject(asn1Encodable);
                         }
                     }
                     finally
                     {
                         global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                         if (disposable != null)
                         {
                             disposable.Dispose();
                         }
                     }
                 }
             }
             else
             {
                 derOut.WriteObject(obj);
             }
         }
         ((Stream)derOut).WriteByte((byte)0);
         ((Stream)derOut).WriteByte((byte)0);
     }
     else
     {
         base.Encode(derOut);
     }
 }
        /// <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
            {
                IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid);

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

                Asn1Encodable asn1Params = null;

                try
                {
                    if (encryptionOid.Equals(RC2Cbc))
                    {
                        // mix in a bit extra...
                        rand.SetSeed(DateTime.Now.Ticks);

                        byte[] iv = rand.GenerateSeed(8);

                        // TODO Is this detailed repeat of Java version really necessary?
                        int effKeyBits = encKeyBytes.Length * 8;
                        int parameterVersion;

                        if (effKeyBits < 256)
                        {
                            parameterVersion = rc2Table[effKeyBits];
                        }
                        else
                        {
                            parameterVersion = effKeyBits;
                        }

                        asn1Params = new RC2CbcParameter(parameterVersion, iv);
                    }
                    else
                    {
                        asn1Params = ParameterUtilities.GenerateParameters(encryptionOid, rand);
                    }
                }
                catch (SecurityUtilityException)
                {
                    // No problem... no parameters generated
                }

                Asn1Object asn1Object;
                ICipherParameters cipherParameters;

                if (asn1Params != null)
                {
                    asn1Object = asn1Params.ToAsn1Object();
                    cipherParameters = ParameterUtilities.GetCipherParameters(
                        encryptionOid, encKey, asn1Object);
                }
                else
                {
                    asn1Object = DerNull.Instance;
                    cipherParameters = encKey;
                }

                encAlgId = new AlgorithmIdentifier(
                    new DerObjectIdentifier(encryptionOid),
                    asn1Object);

                cipher.Init(true, cipherParameters);

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

                content.Write(cOut);

                cOut.Close();

                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 (RecipientInf recipient in recipientInfs)
            {
                try
                {
                    recipientInfos.Add(recipient.ToRecipientInfo(encKey));
                }
                catch (IOException e)
                {
                    throw new CmsException("encoding error.", e);
                }
                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(
                PkcsObjectIdentifiers.Data,
                encAlgId,
                encContent);

            Asn1.Cms.ContentInfo contentInfo = new Asn1.Cms.ContentInfo(
                PkcsObjectIdentifiers.EnvelopedData,
                new EnvelopedData(null, new DerSet(recipientInfos), eci, null));

            return new CmsEnvelopedData(contentInfo);
        }
        /// <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);

                cOut.Dispose();

                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)
            {
                Asn1.Cms.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);
        }
Ejemplo n.º 16
0
 public BerOctetString(IEnumerable octets) : base(BerOctetString.ToBytes(octets))
 {
     this.octs = octets;
 }
        /**
        * 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);
        }
Ejemplo n.º 18
0
 internal override void Encode(DerOutputStream derOut)
 {
     if ((derOut is Asn1OutputStream) || (derOut is BerOutputStream))
     {
         derOut.WriteTag(160, base.tagNo);
         derOut.WriteByte(0x80);
         if (!base.IsEmpty())
         {
             if (!base.explicitly)
             {
                 IEnumerable enumerable;
                 if (base.obj is Asn1OctetString)
                 {
                     if (base.obj is BerOctetString)
                     {
                         enumerable = (BerOctetString)base.obj;
                     }
                     else
                     {
                         Asn1OctetString str = (Asn1OctetString)base.obj;
                         enumerable = new BerOctetString(str.GetOctets());
                     }
                 }
                 else if (base.obj is Asn1Sequence)
                 {
                     enumerable = (Asn1Sequence)base.obj;
                 }
                 else
                 {
                     if (!(base.obj is Asn1Set))
                     {
                         throw Platform.CreateNotImplementedException(Platform.GetTypeName(base.obj));
                     }
                     enumerable = (Asn1Set)base.obj;
                 }
                 IEnumerator enumerator = enumerable.GetEnumerator();
                 try
                 {
                     while (enumerator.MoveNext())
                     {
                         Asn1Encodable current = (Asn1Encodable)enumerator.Current;
                         derOut.WriteObject(current);
                     }
                 }
                 finally
                 {
                     if (enumerator is IDisposable disposable)
                     {
                         IDisposable disposable;
                         disposable.Dispose();
                     }
                 }
             }
             else
             {
                 derOut.WriteObject(base.obj);
             }
         }
         derOut.WriteByte(0);
         derOut.WriteByte(0);
     }
     else
     {
         base.Encode(derOut);
     }
 }