将JAVA代码KeyStore.getInstance转换为c#

时间:2016-10-07 02:26:22

标签: java c# pkcs#12

我正在尝试将此JAVA代码转换为C#以获取ECPrivateKey

private static ECPrivateKey loadPrivateKey(String pkcs12Filename) throws KeyStoreException, NoSuchProviderException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
    KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
    keystore.load(new FileInputStream(pkcs12Filename), "".toCharArray());
    assert keystore.size() == 1 : "wrong number of entries in keychain";
    Enumeration<String> aliases = keystore.aliases();
    String alias = null;
    while (aliases.hasMoreElements()) {
      alias = aliases.nextElement();
    }
    return (ECPrivateKey) keystore.getKey(alias, null);
}

1 个答案:

答案 0 :(得分:0)

这是代码,我得到了输出。

private void GetPrivateKeyFromP12(string path, string passWord)
        {
            //this.mKeyStoreEntities = PKCSUtils.extractEntities(privateKeyFilePath, privateKeyPassword);
            /**
             * Java has a minimum requirement for keystore password lengths.  Utilities like KeyChain will
             * allow you to specify less but then you will receive an obscure java error when trying to
             * load the keystore.  Check for it here and throw a meaningful error
             */

            //X509Certificate certificate;
            //ECPrivateKey privateKey;

            using (StreamReader reader = new StreamReader(path))
            {
                var fs = reader.BaseStream;
                GetMerchantIdentifierField(fs);

                fs.Position = 0;
                GetPrivateKey(fs, passWord);
            }
        }

        private void GetPrivateKey(Stream fs, string passWord)
        {
            Pkcs12Store store = new Pkcs12Store(fs, passWord.ToCharArray());

            foreach (string n in store.Aliases)
            {
                if (store.IsKeyEntry(n))
                {
                    AsymmetricKeyEntry asymmetricKey = store.GetKey(n);

                    if (asymmetricKey.Key.IsPrivate)
                    {
                        this.merchantPrivateKey = asymmetricKey.Key as ECPrivateKeyParameters;
                    }
                }
            }
        }