public SHA256WithRSA(string pkcs12path, string password)
        {
            using (FileStream fs = new FileStream(pkcs12path, FileMode.Open, FileAccess.Read))
            {
                KeyStore = new Pkcs12StoreBuilder().Build();
                KeyStore.Load(fs, password.ToCharArray());

                List <string> keys = new List <string>();

                foreach (string alias in KeyStore.Aliases)
                {
                    if (string.IsNullOrEmpty(alias))
                    {
                        continue;
                    }

                    X509CertificateEntry[] chain = KeyStore.GetCertificateChain(alias);
                    if (chain == null)
                    {
                        continue;
                    }

                    foreach (X509CertificateEntry entry in chain)
                    {
                        X509Certificate cert       = entry.Certificate;
                        byte[]          encoded    = cert.GetEncoded();
                        string          base64cert = Convert.ToBase64String(encoded);
                        keys.Add(base64cert);
                    }

                    Alias          = alias;
                    Base64KeyChain = keys.ToArray();
                }
            }
        }
예제 #2
0
        private void DoTestCertsOnly()
        {
            Pkcs12Store pkcs12 = new Pkcs12StoreBuilder().Build();

            pkcs12.Load(new MemoryStream(certsOnly, false), null);

            IsTrue(pkcs12.ContainsAlias("alias"));

            MemoryStream bOut = new MemoryStream();

            pkcs12.Save(bOut, null, Random);

            pkcs12 = new Pkcs12StoreBuilder().Build();

            pkcs12.Load(new MemoryStream(bOut.ToArray(), false), null);

            IsTrue(pkcs12.ContainsAlias("alias"));

            try
            {
                pkcs12.Load(new MemoryStream(certsOnly, false), "1".ToCharArray());
                Fail("no exception");
            }
            catch (IOException e)
            {
                IsEquals("password supplied for keystore that does not require one", e.Message);
            }

            // TODO Modify environment variables in tests?
            //System.setProperty(Pkcs12Store.IgnoreUselessPasswordProperty, "true");

            //pkcs12.Load(new MemoryStream(certsOnly, false), "1".ToCharArray());

            //System.setProperty(Pkcs12Store.IgnoreUselessPasswordProperty, "false");
        }
예제 #3
0
        public void IssueClientFromCA()
        {
            // get CA
            string caCn = "MyCA CommonName";

            char[] caPass = "******".ToCharArray();

            using (System.IO.Stream caCertFile = System.IO.File.OpenRead(string.Format(@"{0}\{1}", _certificatesDir, "MyCAFile.pfx")))
            {
                Pkcs12Store store = new Pkcs12StoreBuilder().Build();
                store.Load(caCertFile, caPass);
                Org.BouncyCastle.X509.X509Certificate          caCert    = store.GetCertificate(caCn).Certificate;
                Org.BouncyCastle.Crypto.AsymmetricKeyParameter caPrivKey = store.GetKey(caCn).Key;

                byte[] clientCert = GenerateDsaCertificateAsPkcs12(
                    "My Client FriendlyName",
                    "My Client SubjectName",
                    "GT",
                    new System.DateTime(2011, 9, 19),
                    new System.DateTime(2014, 9, 18),
                    "PFXPASS",
                    caCert,
                    caPrivKey);

                string saveAS = string.Format(@"{0}\{1}", _certificatesDir, "clientCertFile.pfx");
                System.IO.File.WriteAllBytes(saveAS, clientCert);
            }
        }
        public StreamDecoder(Stream source, Stream p12, string storePass, string keyPass, bool isBase64)
        {
            Pkcs12Store pkcs12Store = new Pkcs12StoreBuilder().Build();

            pkcs12Store.Load(p12, storePass.ToCharArray());
            string alias = null;

            foreach (string alias2 in pkcs12Store.Aliases)
            {
                if (pkcs12Store.IsKeyEntry(alias2))
                {
                    alias = alias2;
                    break;
                }
            }
            if (isBase64)
            {
                StreamReader streamReader = new StreamReader(source);
                b = new MemoryStream();
                Base64.Decode(streamReader.ReadToEnd(), b);
                b.Position = 0L;
            }
            else
            {
                b = source;
            }
            c = pkcs12Store.GetCertificate(alias);
            d = pkcs12Store.GetKey(alias);
        }
예제 #5
0
        public static X509Certificate2 CreateSelfSignedClientCertificate(string commonNameValue, RavenServer.CertificateHolder certificateHolder, out byte[] certBytes)
        {
            var serverCertBytes = certificateHolder.Certificate.Export(X509ContentType.Cert);
            var readCertificate = new X509CertificateParser().ReadCertificate(serverCertBytes);

            CreateSelfSignedCertificateBasedOnPrivateKey(
                commonNameValue,
                readCertificate.SubjectDN,
                (certificateHolder.PrivateKey.Key, readCertificate.GetPublicKey()),
                true,
                false,
                5,
                out certBytes);


            ValidateNoPrivateKeyInServerCert(serverCertBytes);

            Pkcs12Store store      = new Pkcs12StoreBuilder().Build();
            var         serverCert = DotNetUtilities.FromX509Certificate(certificateHolder.Certificate);

            store.Load(new MemoryStream(certBytes), Array.Empty <char>());
            store.SetCertificateEntry(serverCert.SubjectDN.ToString(), new X509CertificateEntry(serverCert));

            var memoryStream = new MemoryStream();

            store.Save(memoryStream, Array.Empty <char>(), GetSeededSecureRandom());
            certBytes = memoryStream.ToArray();

            var cert = new X509Certificate2(certBytes, (string)null, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);

            return(cert);
        }
        private static Pkcs12Store CreateTemporaryStore(X509Certificate2 signerCertificate)
        {
            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            var    random          = new SecureRandom();
            string sessionPassword = Convert.ToBase64String(SecureRandom.GetNextBytes(random, 32));

            using (var stream = new MemoryStream(signerCertificate.Export(X509ContentType.Pfx, sessionPassword)))
            {
                store.Load(stream, sessionPassword.ToCharArray());
            }

            return(store);
        }
예제 #7
0
        public static Org.BouncyCastle.X509.X509Certificate LoadBouncyCertFromPKCS12Store(string Filename)
        {
            Pkcs12Store Store = new Pkcs12StoreBuilder().Build();

            Store.Load(File.OpenRead(Filename), new char[0]);

            foreach (string Alias in Store.Aliases)
            {
                if (Store.IsCertificateEntry(Alias))
                {
                    return(Store.GetCertificate(Alias).Certificate);
                }
            }

            return(null);
        }
예제 #8
0
        public static RSACryptoServiceProvider LoadKeyPairFromPKCS12Store(string Filename)
        {
            Pkcs12Store Store = new Pkcs12StoreBuilder().Build();

            Store.Load(File.OpenRead(Filename), new char[0]);

            foreach (string Alias in Store.Aliases)
            {
                if (Store.IsKeyEntry(Alias))
                {
                    Console.WriteLine("Key with alias {0} is {1}", Alias, Store.GetKey(Alias).Key);
                    return(ConvertBouncyKeyPairToNET(Store.GetKey(Alias).Key as RsaPrivateCrtKeyParameters));
                }
            }

            return(null);
        }
예제 #9
0
        private void testNoExtraLocalKeyID(byte[] store1data)
        {
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");

            kpg.Init(new RsaKeyGenerationParameters(
                         BigInteger.ValueOf(0x10001), new SecureRandom(), 512, 25));

            AsymmetricCipherKeyPair newPair = kpg.GenerateKeyPair();

            Pkcs12Store store1 = new Pkcs12StoreBuilder().Build();

            store1.Load(new MemoryStream(store1data, false), passwd);

            Pkcs12Store store2 = new Pkcs12StoreBuilder().Build();

            AsymmetricKeyEntry k1 = store1.GetKey("privatekey");

            X509CertificateEntry[] chain1 = store1.GetCertificateChain("privatekey");

            X509CertificateEntry[] chain2 = new X509CertificateEntry[chain1.Length + 1];

            Array.Copy(chain1, 0, chain2, 1, chain1.Length);

            chain2[0] = CreateCert(newPair.Public, k1.Key, "*****@*****.**", "*****@*****.**");

            if (chain1[0][PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
            {
                Fail("localKeyID not found initially");
            }

            store2.SetKeyEntry("new", new AsymmetricKeyEntry(newPair.Private), chain2);

            MemoryStream bOut = new MemoryStream();

            store2.Save(bOut, passwd, new SecureRandom());

            store2.Load(new MemoryStream(bOut.ToArray(), false), passwd);

            chain2 = store2.GetCertificateChain("new");

            if (chain2[1][PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] != null)
            {
                Fail("localKeyID found after save");
            }
        }
예제 #10
0
        /// <summary>
        /// stores SubjectPublicKeyInfo Data Type from certificate's public key, asymmetric algorithm and digest
        /// </summary>
        /// <param name="path">string .ps12, pfx or .jks (PKCS12 fromat) certificate path</param>
        /// <param name="password">string certificate's password, required if PKCS12</param>
        /// <returns>boolean true if loaded correctly</returns>
        private bool loadPublicKeyFromPKCS12File(string path, string password)
        {
            bool flag = false;

            if (password == null)
            {
                this.error.setError("CE012", "Alias and password are required for PKCS12 certificates");
                return(false);
            }

            Pkcs12Store pkcs12 = null;

            try
            {
                pkcs12 = new Pkcs12StoreBuilder().Build();
                pkcs12.Load(new FileStream(path, FileMode.Open, FileAccess.Read), password.ToCharArray());
            }

            catch
            {
                this.error.setError("CE013", path + "not found.");
                // throw new FileLoadException(path + "not found.");
            }

            if (pkcs12 != null)
            {
                string pName = null;
                foreach (string n in pkcs12.Aliases)
                {
                    if (pkcs12.IsKeyEntry(n))
                    {
                        pName = n;


                        Org.BouncyCastle.X509.X509Certificate cert = pkcs12.GetCertificate(pName).Certificate;
                        castCertificate(cert);
                        return(true);
                    }
                }
            }
            this.error.setError("CE014", path + "not found.");
            return(flag);
        }
예제 #11
0
        /// <summary>
        /// Stores PrivateKeyInfo Data Type from certificate's private key, algorithm and digest
        /// </summary>
        /// <param name="path">string .ps12, pfx or .jks (PKCS12 fromat) certificate path</param>
        /// <param name="password">string certificate's password, required if PKCS12</param>
        /// <returns></returns>
        private bool loadPrivateKeyFromPKCS12File(string path, string password)
        {
            bool flag = false;

            if (password == null)
            {
                this.error.setError("PK004", "Alias and Password are required for PKCS12 keys");
                return(false);
            }
            Pkcs12Store pkcs12 = null;

            try
            {
                pkcs12 = new Pkcs12StoreBuilder().Build();
                pkcs12.Load(new FileStream(path, FileMode.Open, FileAccess.Read), password.ToCharArray());
            }

            catch
            {
                this.error.setError("PK005", path + "not found or wrong password.");
                //throw new FileLoadException(path + "not found or wrong password.");
            }

            if (pkcs12 != null)
            {
                string pName = null;
                foreach (string n in pkcs12.Aliases)
                {
                    if (pkcs12.IsKeyEntry(n) && pkcs12.GetKey(n).Key.IsPrivate)
                    {
                        pName = n;

                        this.privateKeyInfo      = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pkcs12.GetKey(n).Key);
                        this.privateKeyAlgorithm = this.privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Id;
                        this.hasPrivateKey       = true;
                        return(true);
                    }
                }
            }
            this.error.setError("PK006", path + " not found");
            return(flag);
        }
        public static AsymmetricKeyParameter getPrivateKey(Stream certStream, string password)
        {
            Pkcs12Store pkcs12Store = new Pkcs12StoreBuilder().Build();

            pkcs12Store.Load(certStream, password.ToCharArray());
            AsymmetricKeyParameter asymmetricKeyParameter = null;

            foreach (string alias in pkcs12Store.Aliases)
            {
                if (pkcs12Store.IsKeyEntry(alias))
                {
                    asymmetricKeyParameter = pkcs12Store.GetKey(alias).Key;
                    if (asymmetricKeyParameter.IsPrivate)
                    {
                        return(asymmetricKeyParameter);
                    }
                }
            }
            return(asymmetricKeyParameter);
        }
예제 #13
0
        /// <exception cref="Sharpen.KeyStoreException"></exception>
        public IList <IDssPrivateKeyEntry> GetKeys()
        {
            if (keys != null)
            {
                return(keys);
            }

            IList <IDssPrivateKeyEntry> list = new List <IDssPrivateKeyEntry>();
            Pkcs12Store     keyStore         = new Pkcs12StoreBuilder().Build();
            FileInputStream input            = new FileInputStream(pkcs12File);

            keyStore.Load(input, password.ToCharArray());
            input.Close();

            foreach (string alias in keyStore.Aliases)
            {
                bool[] keyUsage;
                if (!(keyStore.IsKeyEntry(alias) &&
                      keyStore.GetKey(alias).Key.IsPrivate &&
                      ((keyUsage = keyStore.GetCertificate(alias).Certificate.GetKeyUsage()) == null ||
                       keyUsage[0])))
                {
                    continue;
                }

                X509CertificateEntry[] x     = keyStore.GetCertificateChain(alias);
                X509Certificate[]      chain = new X509Certificate[x.Length];

                for (int k = 0; k < x.Length; ++k)
                {
                    chain[k] = x[k].Certificate;
                }

                AsymmetricKeyParameter privateKey = keyStore.GetKey(alias).Key;

                list.Add(new KSPrivateKeyEntry(chain[0], chain, privateKey));
            }
            this.keys = list;

            return(list);
        }
예제 #14
0
        public RSAStreamDecoder(Stream source, Stream p12, string storePass, string keyPass, bool isBase64)
        {
            Pkcs12Store pkcs12Store = new Pkcs12StoreBuilder().Build();

            pkcs12Store.Load(p12, storePass.ToCharArray());
            string alias = null;

            foreach (string alias3 in pkcs12Store.Aliases)
            {
                if (pkcs12Store.IsKeyEntry(alias3))
                {
                    alias = alias3;
                    break;
                }
            }
            if (isBase64)
            {
                StreamReader streamReader = new StreamReader(source);
                b = new MemoryStream();
                Base64.Decode(streamReader.ReadToEnd(), b);
                b.Position = 0L;
            }
            else
            {
                b = source;
            }
            c = pkcs12Store.GetCertificate(alias);
            d = pkcs12Store.GetKey(alias);
            foreach (string alias4 in pkcs12Store.Aliases)
            {
                if (pkcs12Store.IsKeyEntry(alias4))
                {
                    AsymmetricKeyEntry key = pkcs12Store.GetKey(alias4);
                    if (key.Key.IsPrivate)
                    {
                        e = (key.Key as RsaPrivateCrtKeyParameters);
                    }
                }
            }
        }
예제 #15
0
        /*
         *
         * ==================读取私钥==========================
         * path   证书路径
         *
         * pwd  证书密码
         *
         */
        public static AsymmetricKeyParameter getPrivateKeyFromFile(string path, string pwd)
        {
            FileStream fs = File.OpenRead(path);      //path路径下证书

            char[] passwd = pwd.ToCharArray();

            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            store.Load(fs, passwd); //加载证书
            string alias = null;

            foreach (string str in store.Aliases)
            {
                if (store.IsKeyEntry(str))
                {
                    alias = str;
                }
            }
            AsymmetricKeyEntry keyEntry = store.GetKey(alias);

            return(keyEntry.Key);
        }
예제 #16
0
        /// <exception cref="Sharpen.KeyStoreException"></exception>
        public override IList <IDssPrivateKeyEntry> GetKeys()
        {
            if (keys != null)
            {
                return(keys);
            }

            IList <IDssPrivateKeyEntry> list = new AList <IDssPrivateKeyEntry>();

            try
            {
                Pkcs12Store     keyStore = new Pkcs12StoreBuilder().Build();
                FileInputStream input    = new FileInputStream(pkcs12File);
                keyStore.Load(input, password);
                input.Close();

                foreach (string alias in keyStore.Aliases)
                {
                    if (keyStore.IsKeyEntry(alias) &&
                        keyStore.GetKey(alias).Key.IsPrivate &&
                        keyStore.GetCertificate(alias).Certificate.GetKeyUsage()[0]    //0: DigitalSignature
                        )
                    {
                        X509CertificateEntry[] x     = keyStore.GetCertificateChain(alias);
                        X509Certificate[]      chain = new X509Certificate[x.Length];

                        for (int k = 0; k < x.Length; ++k)
                        {
                            chain[k] = x[k].Certificate;
                        }

                        AsymmetricKeyParameter privateKey = keyStore.GetKey(alias).Key;

                        list.AddItem(new KSPrivateKeyEntry(chain[0], chain, privateKey));
                    }
                }
            }
            catch (IOException iox)
            {
                if (iox.Message.Contains("password") || iox.Message.Contains("corrupted"))
                {
                    //"PKCS12 key store MAC invalid - wrong  or corrupted file."
                    throw new IOException("La contraseña es incorrecta, o el archivo está corrompido.", iox);
                }

                throw;
            }
            catch (NoSuchAlgorithmException e)
            {
                //throw new KeyStoreException("Can't initialize Sun PKCS#12 security " + "provider. Reason: "
                //     + e.InnerException.Message, e);
                throw;
            }
            catch (CertificateException e)
            {
                //throw new KeyStoreException("Can't initialize Sun PKCS#12 security " + "provider. Reason: "
                //     + e.InnerException.Message, e);
                throw;
            }

            /*catch (UnrecoverableEntryException e)
             * {
             *  throw new KeyStoreException("Can't initialize Sun PKCS#12 security " + "provider. Reason: "
             + e.InnerException.Message, e);
             + }*/

            this.keys = list;

            return(list);
        }
예제 #17
0
        private void basicStoreTest(AsymmetricKeyEntry privKey, X509CertificateEntry[] chain,
                                    DerObjectIdentifier keyAlgorithm, DerObjectIdentifier certAlgorithm)
        {
            Pkcs12Store store = new Pkcs12StoreBuilder()
                                .SetKeyAlgorithm(keyAlgorithm)
                                .SetCertAlgorithm(certAlgorithm)
                                .Build();

            store.SetKeyEntry("key", privKey, chain);

            MemoryStream bOut = new MemoryStream();

            store.Save(bOut, passwd, new SecureRandom());

            store.Load(new MemoryStream(bOut.ToArray(), false), passwd);

            AsymmetricKeyEntry k = store.GetKey("key");

            if (!k.Equals(privKey))
            {
                Fail("private key didn't match");
            }

            X509CertificateEntry[] c = store.GetCertificateChain("key");

            if (c.Length != chain.Length || !c[0].Equals(chain[0]))
            {
                Fail("certificates didn't match");
            }

            // check attributes
            Pkcs12Entry b1 = k;
            Pkcs12Entry b2 = chain[0];

            if (b1[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] != null)
            {
                DerBmpString name = (DerBmpString)b1[PkcsObjectIdentifiers.Pkcs9AtFriendlyName];

                if (!name.Equals(new DerBmpString("key")))
                {
                    Fail("friendly name wrong");
                }
            }
            else
            {
                Fail("no friendly name found on key");
            }

            if (b1[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] != null)
            {
                Asn1OctetString id = (Asn1OctetString)b1[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID];

                if (!id.Equals(b2[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID]))
                {
                    Fail("local key id mismatch");
                }
            }
            else
            {
                Fail("no local key id found");
            }

            //
            // check algorithm types.
            //
            Asn1InputStream aIn = new Asn1InputStream(bOut.ToArray());

            Pfx pfx = new Pfx((Asn1Sequence)aIn.ReadObject());

            ContentInfo cInfo = pfx.AuthSafe;

            Asn1OctetString auth = (Asn1OctetString)cInfo.Content;

            aIn = new Asn1InputStream(auth.GetOctets());
            Asn1Sequence s1 = (Asn1Sequence)aIn.ReadObject();

            ContentInfo c1 = ContentInfo.GetInstance(s1[0]);
            ContentInfo c2 = ContentInfo.GetInstance(s1[1]);

            aIn = new Asn1InputStream(((Asn1OctetString)c1.Content).GetOctets());

            SafeBag sb = new SafeBag((Asn1Sequence)(((Asn1Sequence)aIn.ReadObject())[0]));

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

            // check the key encryption
            if (!encInfo.EncryptionAlgorithm.Algorithm.Equals(keyAlgorithm))
            {
                Fail("key encryption algorithm wrong");
            }

            // check the certificate encryption
            EncryptedData cb = EncryptedData.GetInstance(c2.Content);

            if (!cb.EncryptionAlgorithm.Algorithm.Equals(certAlgorithm))
            {
                Fail("cert encryption algorithm wrong");
            }
        }
예제 #18
0
        public void doTestPkcs12Store()
        {
            BigInteger mod = new BigInteger("bb1be8074e4787a8d77967f1575ef72dd7582f9b3347724413c021beafad8f32dba5168e280cbf284df722283dad2fd4abc750e3d6487c2942064e2d8d80641aa5866d1f6f1f83eec26b9b46fecb3b1c9856a303148a5cc899c642fb16f3d9d72f52526c751dc81622c420c82e2cfda70fe8d13f16cc7d6a613a5b2a2b5894d1", 16);

            MemoryStream stream = new MemoryStream(pkcs12, false);
            Pkcs12Store  store  = new Pkcs12StoreBuilder().Build();

            store.Load(stream, passwd);

            string pName = null;

            foreach (string n in store.Aliases)
            {
                if (store.IsKeyEntry(n))
                {
                    pName = n;
                    //break;
                }
            }

            AsymmetricKeyEntry key = store.GetKey(pName);

            if (!((RsaKeyParameters)key.Key).Modulus.Equals(mod))
            {
                Fail("Modulus doesn't match.");
            }

            X509CertificateEntry[] ch = store.GetCertificateChain(pName);

            if (ch.Length != 3)
            {
                Fail("chain was wrong length");
            }

            if (!ch[0].Certificate.SerialNumber.Equals(new BigInteger("96153094170511488342715101755496684211")))
            {
                Fail("chain[0] wrong certificate.");
            }

            if (!ch[1].Certificate.SerialNumber.Equals(new BigInteger("279751514312356623147411505294772931957")))
            {
                Fail("chain[1] wrong certificate.");
            }

            if (!ch[2].Certificate.SerialNumber.Equals(new BigInteger("11341398017")))
            {
                Fail("chain[2] wrong certificate.");
            }

            //
            // save test
            //
            MemoryStream bOut = new MemoryStream();

            store.Save(bOut, passwd, new SecureRandom());

            stream = new MemoryStream(bOut.ToArray(), false);
            store.Load(stream, passwd);

            key = store.GetKey(pName);

            if (!((RsaKeyParameters)key.Key).Modulus.Equals(mod))
            {
                Fail("Modulus doesn't match.");
            }

            store.DeleteEntry(pName);

            if (store.GetKey(pName) != null)
            {
                Fail("Failed deletion test.");
            }

            //
            // cert chain test
            //
            store.SetCertificateEntry("testCert", ch[2]);

            if (store.GetCertificateChain("testCert") != null)
            {
                Fail("Failed null chain test.");
            }

            //
            // UTF 8 single cert test
            //
            stream = new MemoryStream(certUTF, false);
            store.Load(stream, "user".ToCharArray());

            if (store.GetCertificate("37") == null)
            {
                Fail("Failed to find UTF cert.");
            }

            //
            // try for a self generated certificate
            //
            RsaKeyParameters pubKey = new RsaKeyParameters(
                false,
                new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
                new BigInteger("11", 16));

            RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters(
                new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
                new BigInteger("11", 16),
                new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16),
                new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16),
                new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16),
                new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16),
                new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16),
                new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16));

            X509CertificateEntry[] chain = new X509CertificateEntry[] {
                CreateCert(pubKey, privKey, "*****@*****.**", "*****@*****.**")
            };

            store = new Pkcs12StoreBuilder().Build();

            store.SetKeyEntry("privateKey", new AsymmetricKeyEntry(privKey), chain);

            if (!store.ContainsAlias("privateKey") || !store.ContainsAlias("PRIVATEKEY"))
            {
                Fail("couldn't find alias privateKey");
            }

            if (store.IsCertificateEntry("privateKey"))
            {
                Fail("key identified as certificate entry");
            }

            if (!store.IsKeyEntry("privateKey") || !store.IsKeyEntry("PRIVATEKEY"))
            {
                Fail("key not identified as key entry");
            }

            if (!"privateKey".Equals(store.GetCertificateAlias(chain[0].Certificate)))
            {
                Fail("Did not return alias for key certificate privateKey");
            }

            MemoryStream store1Stream = new MemoryStream();

            store.Save(store1Stream, passwd, new SecureRandom());
            testNoExtraLocalKeyID(store1Stream.ToArray());

            //
            // no friendly name test
            //
            stream = new MemoryStream(pkcs12noFriendly, false);
            store.Load(stream, noFriendlyPassword);

            pName = null;

            foreach (string n in store.Aliases)
            {
                if (store.IsKeyEntry(n))
                {
                    pName = n;
                    //break;
                }
            }

            ch = store.GetCertificateChain(pName);

            //for (int i = 0; i != ch.Length; i++)
            //{
            //	Console.WriteLine(ch[i]);
            //}

            if (ch.Length != 1)
            {
                Fail("no cert found in pkcs12noFriendly");
            }

            //
            // failure tests
            //
            ch = store.GetCertificateChain("dummy");

            store.GetCertificateChain("DUMMY");

            store.GetCertificate("dummy");

            store.GetCertificate("DUMMY");

            //
            // storage test
            //
            stream = new MemoryStream(pkcs12StorageIssue, false);
            store.Load(stream, storagePassword);

            pName = null;

            foreach (string n in store.Aliases)
            {
                if (store.IsKeyEntry(n))
                {
                    pName = n;
                    //break;
                }
            }

            ch = store.GetCertificateChain(pName);
            if (ch.Length != 2)
            {
                Fail("Certificate chain wrong length");
            }

            store.Save(new MemoryStream(), storagePassword, new SecureRandom());

            //
            // basic certificate check
            //
            store.SetCertificateEntry("cert", ch[1]);

            if (!store.ContainsAlias("cert") || !store.ContainsAlias("CERT"))
            {
                Fail("couldn't find alias cert");
            }

            if (!store.IsCertificateEntry("cert") || !store.IsCertificateEntry("CERT"))
            {
                Fail("cert not identified as certificate entry");
            }

            if (store.IsKeyEntry("cert") || store.IsKeyEntry("CERT"))
            {
                Fail("cert identified as key entry");
            }

            if (!store.IsEntryOfType("cert", typeof(X509CertificateEntry)))
            {
                Fail("cert not identified as X509CertificateEntry");
            }

            if (!store.IsEntryOfType("CERT", typeof(X509CertificateEntry)))
            {
                Fail("CERT not identified as X509CertificateEntry");
            }

            if (store.IsEntryOfType("cert", typeof(AsymmetricKeyEntry)))
            {
                Fail("cert identified as key entry via AsymmetricKeyEntry");
            }

            if (!"cert".Equals(store.GetCertificateAlias(ch[1].Certificate)))
            {
                Fail("Did not return alias for certificate entry");
            }

            //
            // test restoring of a certificate with private key originally as a ca certificate
            //
            store = new Pkcs12StoreBuilder().Build();

            store.SetCertificateEntry("cert", ch[0]);

            if (!store.ContainsAlias("cert") || !store.ContainsAlias("CERT"))
            {
                Fail("restore: couldn't find alias cert");
            }

            if (!store.IsCertificateEntry("cert") || !store.IsCertificateEntry("CERT"))
            {
                Fail("restore: cert not identified as certificate entry");
            }

            if (store.IsKeyEntry("cert") || store.IsKeyEntry("CERT"))
            {
                Fail("restore: cert identified as key entry");
            }

            if (store.IsEntryOfType("cert", typeof(AsymmetricKeyEntry)))
            {
                Fail("restore: cert identified as key entry via AsymmetricKeyEntry");
            }

            if (store.IsEntryOfType("CERT", typeof(AsymmetricKeyEntry)))
            {
                Fail("restore: cert identified as key entry via AsymmetricKeyEntry");
            }

            if (!store.IsEntryOfType("cert", typeof(X509CertificateEntry)))
            {
                Fail("restore: cert not identified as X509CertificateEntry");
            }

            //
            // test of reading incorrect zero-length encoding
            //
            stream = new MemoryStream(pkcs12nopass, false);
            store.Load(stream, "".ToCharArray());
        }