예제 #1
0
        public static void Save(this Pkcs12Store store,
                                Stream stream,
                                string encryptionPassword,
                                string integrityPassword,
                                SecureRandom random)
        {
            const int saltSize      = 20;
            const int minIterations = 1024;

            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            //if (null != encryptionPassword && encryptionPassword == integrityPassword)
            //{
            //    store.Save(stream, encryptionPassword.ToArray(), random);
            //    return;
            //}
            if (random == null)
            {
                throw new ArgumentNullException("random");
            }

            var T = store.GetType();
            Func <AsymmetricKeyParameter, SubjectKeyIdentifier> CreateSubjectKeyID = (pubKey_) =>
            {
                var method = T.GetMethod("CreateSubjectKeyID", BindingFlags.NonPublic | BindingFlags.Static);
                return((SubjectKeyIdentifier)method.Invoke(store, new object[] { pubKey_ }));
            };

            Func <DerObjectIdentifier> keyAlgorithm = () =>
            {
                var property = T.GetField("keyAlgorithm", BindingFlags.NonPublic | BindingFlags.Instance);
                return((DerObjectIdentifier)property.GetValue(store));
            };


            Func <DerObjectIdentifier> certAlgorithm = () =>
            {
                var property = T.GetField("certAlgorithm", BindingFlags.NonPublic | BindingFlags.Instance);
                return((DerObjectIdentifier)property.GetValue(store));
            };
            //
            // handle the key
            //
            Asn1EncodableVector keyS = new Asn1EncodableVector();
            var keys = store.Aliases.OfType <string>().ToDictionary(alias => alias, store.GetKey);

            foreach (string name in store.Aliases.OfType <string>())
            {
                byte[] kSalt = new byte[saltSize];
                random.NextBytes(kSalt);

                AsymmetricKeyEntry privKey = keys[name];
                Asn1Encodable      kInfo   = null;
                if (!string.IsNullOrEmpty(encryptionPassword))
                {
                    kInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(keyAlgorithm(), encryptionPassword.ToArray(), kSalt, minIterations, privKey.Key);
                }
                else
                {
                    kInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(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           = store.GetCertificate(name);
                    AsymmetricKeyParameter pubKey       = ct.Certificate.GetPublicKey();
                    SubjectKeyIdentifier   subjectKeyID = CreateSubjectKeyID(pubKey);

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

                SafeBag kBag = null;
                if (!string.IsNullOrEmpty(encryptionPassword))
                {
                    kBag = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, kInfo.ToAsn1Object(), new DerSet(kName));
                }
                else
                {
                    kBag = new SafeBag(PkcsObjectIdentifiers.KeyBag, 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 = store.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);
            }

            var certs = store.Aliases.OfType <string>().Select(store.GetCertificate);

            foreach (var cert in certs)
            {
                //X509CertificateEntry cert = (X509CertificateEntry)certs[certId];

                //if (keys[certId] != null)
                //    continue;
                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;
                    }

                    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))));
                    fName.Add(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtFriendlyName, new DerSet(new DerBmpString(CreateSubjectKeyID(cert.Certificate.GetPublicKey()).GetKeyIdentifier()))));
                }

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

                certSeq.Add(sBag);

                doneCerts.Add(cert.Certificate);
            }

            var chainCerts = store.Aliases.OfType <string>().Select(store.GetCertificateChain).Aggregate <IEnumerable <X509CertificateEntry>, IEnumerable <X509CertificateEntry> >(new List <X509CertificateEntry>(), (list, entries) => list.Union(entries));

            foreach (var cert in chainCerts)
            {
                //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();

            Func <bool, AlgorithmIdentifier, char[], bool, byte[], byte[]> CryptPbeData = (forEncryption_, algId_, password_, wrongPkcs12Zero_, data_) =>
            {
                var method = T.GetMethod("CryptPbeData", BindingFlags.NonPublic | BindingFlags.Static);
                return((byte[])method.Invoke(store, new object[] { forEncryption_, algId_, password_, wrongPkcs12Zero_, data_ }));
            };

            ContentInfo[] info = null;
            if (null != encryptionPassword)
            {
                byte[] certBytes = CryptPbeData(true, cAlgId, encryptionPassword.ToArray(), false, derEncodedBytes);

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

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

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

            byte[] data = new AuthenticatedSafe(info).GetEncoded(Asn1Encodable.Der);

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

            //
            // create the mac
            //
            byte[] mSalt = new byte[saltSize];
            random.NextBytes(mSalt);

            Func <DerObjectIdentifier, byte[], int, char[], bool, byte[], byte[]> CalculatePbeMac = (oid_, salt_, itCount_, password_, wrongPkcs12Zero_, data_) =>
            {
                var method = T.GetMethod("CalculatePbeMac", BindingFlags.NonPublic | BindingFlags.Static);
                return((byte[])method.Invoke(store, new object[] { oid_, salt_, itCount_, password_, wrongPkcs12Zero_, data_ }));
            };


            MacData mData = null;

            if (null != integrityPassword)
            {
                //byte[] mac = CalculatePbeMac(OiwObjectIdentifiers.IdSha1, mSalt, minIterations, integrityPassword.ToArray(), false, data);
                byte[] mac = CalculatePbeMac(PbeUtilities.GetObjectIdentifier("PBEwithHmacSHA-256"), mSalt, minIterations, integrityPassword.ToArray(), false, data);

                //AlgorithmIdentifier algId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance);
                AlgorithmIdentifier algId = new AlgorithmIdentifier(PbeUtilities.GetObjectIdentifier("PBEwithHmacSHA-256"), DerNull.Instance);

                DigestInfo dInfo = new DigestInfo(algId, mac);

                mData = new MacData(dInfo, mSalt, minIterations);
            }

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

            DerOutputStream derOut = new DerOutputStream(stream);

            derOut.WriteObject(pfx);
        }