예제 #1
0
        /// <summary>
        /// 获取一个密钥对,其中私钥是DES加密后的
        /// </summary>
        /// <param name="userPassword"></param>
        /// <returns></returns>
        public static bool CreateRSAKeypair(string pwd, ref KeyPair resultKeypair)
        {
            _error = "";
            try
            {
                resultKeypair = new KeyPair {
                    publicKey = "", privateKey = ""
                };
                //RSA密钥对的构造器
                RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();

                //RSA密钥构造器的参数
                RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                    Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                    new Org.BouncyCastle.Security.SecureRandom(),
                    1024,   //密钥长度
                    25);

                //用参数初始化密钥构造器
                keyGenerator.Init(param);

                //产生密钥对
                AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
                if (((RsaKeyParameters)keyPair.Public).Modulus.BitLength < 1024)
                {
                    _error = "密钥生成失败,长度不足1024字节。";
                    return(false);
                }

                //获取公钥和密钥
                SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
                Asn1Object           asn1ObjectPublic     = subjectPublicKeyInfo.ToAsn1Object();
                byte[] pbkByte = asn1ObjectPublic.GetEncoded();
                resultKeypair.publicKey = Convert.ToBase64String(pbkByte);


                string alg      = "1.2.840.113549.1.12.1.3"; // 3 key triple DES with SHA-1
                byte[] salt     = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
                int    count    = 1000;
                char[] password = pwd.ToCharArray();
                EncryptedPrivateKeyInfo enPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                    alg,
                    password,
                    salt,
                    count,
                    keyPair.Private);

                byte[] prkByte = enPrivateKeyInfo.ToAsn1Object().GetEncoded();
                resultKeypair.privateKey = Convert.ToBase64String(prkByte);

                return(true);
            }
            catch (Exception ex)
            {
                _error = ex.Message;
                return(false);
            }
        }
예제 #2
0
        private static void savetheKey(AsymmetricKeyParameter publicKey, AsymmetricKeyParameter privateKey)
        {
            //保存公钥到文件
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            Asn1Object           aobject       = publicKeyInfo.ToAsn1Object();

            byte[]     pubInfoByte = aobject.GetEncoded();
            FileStream fs          = new FileStream(pubKeyFile, FileMode.Create, FileAccess.Write);

            fs.Write(pubInfoByte, 0, pubInfoByte.Length);
            fs.Close();
            //保存私钥到文件

            /*
             * PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
             * aobject = privateKeyInfo.ToAsn1Object();
             * byte[] priInfoByte = aobject.GetEncoded();
             * fs = new FileStream(@"E:/Desktop/a.pri", FileMode.Create, FileAccess.Write);
             * fs.Write(priInfoByte, 0, priInfoByte.Length);
             * fs.Close();
             */
            string alg = "1.2.840.113549.1.12.1.3"; // 3 key triple DES with SHA-1

            byte[] salt  = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int    count = 1000;

            char[] password = "******".ToCharArray();
            EncryptedPrivateKeyInfo enPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                alg,
                password,
                salt,
                count,
                privateKey);

            byte[] priInfoByte = enPrivateKeyInfo.ToAsn1Object().GetEncoded();
            fs = new FileStream(priKeyFile, FileMode.Create, FileAccess.Write);
            fs.Write(priInfoByte, 0, priInfoByte.Length);
            fs.Close();
            //还原
            //PrivateKeyInfo priInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password, enPrivateKeyInfo);
            //AsymmetricKeyParameter privateKey = PrivateKeyFactory.CreateKey(priInfoByte);
        }
예제 #3
0
        public void RsaKeysGenerate(string PrivateKeyFilename, string PublicKeyFilename, string passw)
        {
            RsaKeyPairGenerator        keyGenerator = new RsaKeyPairGenerator();
            RsaKeyGenerationParameters param        = new RsaKeyGenerationParameters(BigInteger.ValueOf(3L), new SecureRandom(), 1024, 25);

            keyGenerator.Init(param);
            AsymmetricCipherKeyPair keyPair       = keyGenerator.GenerateKeyPair();
            AsymmetricKeyParameter  publicKey     = keyPair.Public;
            AsymmetricKeyParameter  privateKey    = keyPair.Private;
            SubjectPublicKeyInfo    publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            Asn1Object aobject = publicKeyInfo.ToAsn1Object();

            byte[] pubInfoByte      = aobject.GetEncoded();
            System.IO.FileStream fs = new System.IO.FileStream(PublicKeyFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            fs.Write(pubInfoByte, 0, pubInfoByte.Length);
            fs.Close();
            string alg = "1.2.840.113549.1.12.1.3";

            byte[] salt = new byte[]
            {
                1,
                2,
                3,
                4,
                5,
                6,
                7,
                8,
                9,
                10
            };
            int count = 1000;

            char[] password = passw.ToCharArray();
            EncryptedPrivateKeyInfo enPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(alg, password, salt, count, privateKey);

            byte[] priInfoByte = enPrivateKeyInfo.ToAsn1Object().GetEncoded();
            fs = new System.IO.FileStream(PrivateKeyFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            fs.Write(priInfoByte, 0, priInfoByte.Length);
            fs.Close();
        }
예제 #4
0
        public static string SavePrivateKey(AsymmetricKeyParameter privateKey)
        {
            //保存公钥到文件
            string alg = "1.2.840.113549.1.12.1.3"; // 3 key triple DES with SHA-1

            byte[] salt  = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int    count = 1000;

            char[] password = "******".ToCharArray();
            EncryptedPrivateKeyInfo enPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                alg,
                password,
                salt,
                count,
                privateKey);

            byte[] priInfoByte = enPrivateKeyInfo.ToAsn1Object().GetEncoded();
            return(Convert.ToBase64String(priInfoByte));

            ////还原
            //PrivateKeyInfo priInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password, enPrivateKeyInfo);
            //AsymmetricKeyParameter privateKey = PrivateKeyFactory.CreateKey(priInfoByte);
        }
예제 #5
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);
                    IAsymmetricKeyParameter 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)
                {
                    IAsymmetricKeyParameter 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);
        }
        public override void PerformTest()
        {
            Pfx                 bag   = Pfx.GetInstance(pkcs12);
            ContentInfo         info  = bag.AuthSafe;
            MacData             mData = bag.MacData;
            DigestInfo          dInfo = mData.Mac;
            AlgorithmIdentifier algId = dInfo.AlgorithmID;

            byte[] salt    = mData.GetSalt();
            int    itCount = mData.IterationCount.IntValue;

            Asn1OctetString   content  = Asn1OctetString.GetInstance(info.Content);
            AuthenticatedSafe authSafe = AuthenticatedSafe.GetInstance(content.GetOctets());

            ContentInfo[] c = authSafe.GetContentInfo();

            //
            // private key section
            //
            if (!c[0].ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                Fail("Failed comparison data test");
            }

            Asn1OctetString authSafeContent = Asn1OctetString.GetInstance(c[0].Content);
            Asn1Sequence    seq             = Asn1Sequence.GetInstance(authSafeContent.GetOctets());

            SafeBag b = SafeBag.GetInstance(seq[0]);

            if (!b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
            {
                Fail("Failed comparison shroudedKeyBag test");
            }

            EncryptedPrivateKeyInfo encInfo = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);

            encInfo = new EncryptedPrivateKeyInfo(encInfo.EncryptionAlgorithm, encInfo.GetEncryptedData());

            b = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, encInfo.ToAsn1Object(), b.BagAttributes);

            byte[] contentOctets = new DerSequence(b).GetEncoded();

            c[0] = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(contentOctets));

            //
            // certificates
            //
            if (!c[1].ContentType.Equals(PkcsObjectIdentifiers.EncryptedData))
            {
                Fail("Failed comparison encryptedData test");
            }

            EncryptedData eData = EncryptedData.GetInstance(c[1].Content);

            c[1] = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, eData);

            //
            // create an octet stream to represent the BER encoding of authSafe
            //
            authSafe = new AuthenticatedSafe(c);

            contentOctets = authSafe.GetEncoded();

            info = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(contentOctets));

            mData = new MacData(new DigestInfo(algId, dInfo.GetDigest()), salt, itCount);

            bag = new Pfx(info, mData);

            //
            // comparison test
            //
            byte[] pfxEncoding = bag.GetEncoded();
            if (!Arrays.AreEqual(pfxEncoding, pkcs12))
            {
                Fail("Failed comparison test");
            }
        }
예제 #7
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();

            MacData mData = null;

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

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

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

            BerOutputStream berOut = new BerOutputStream(stream);

            berOut.WriteObject(pfx);
        }