首页 > 解决方案 > 如何从 p12 文件中读取 SecretKey?

问题描述

我正在尝试从 p12 文件中读取 SecretKey,但它不是在 Bouncy Castle 中创建的。需要注意的一件有趣的事情是该文件没有任何证书,并且 System.Security.Cryptography.X509Certificates 类无法读取任何内容。

  public void Pkcs12Pfx2()
    {
        Pfx bag = Pfx.GetInstance(File.ReadAllBytes(path));
        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();

        foreach (ContentInfo ci in c)
        {
            DerObjectIdentifier oid = ci.ContentType;

            byte[] octetsCi = null;
            if (oid.Equals(PkcsObjectIdentifiers.Data))
            {
                octetsCi = Asn1OctetString.GetInstance(ci.Content).GetOctets();
            }

            if (octetsCi != null)
            {
                Asn1Sequence seqCi = Asn1Sequence.GetInstance(octetsCi);

                foreach (Asn1Sequence subSeq in seqCi)
                {
                    SafeBag bagCi = SafeBag.GetInstance(subSeq);

                    foreach (var item in Asn1Sequence.GetInstance(bagCi.BagValue))
                    {
                        if (item.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                        {

                        }
                        else
                        {
                            PrivateKeyInfo pki = new PrivateKeyInfo(algId, (Asn1Encodable)item);
                            var epki = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo("PBEWITHSHA1AND3-KEYTRIPLEDES-CBC", password.ToCharArray(), salt, itCount, pki);

                            var aa = epki.ToAsn1Object();
                        }
                    }
                }
            }
        }

对象 epki 包含 SecretKey 的信息,但它仍然被加密或编码。我怎样才能解码这些信息?

标签: c#bouncycastlepkcs#12

解决方案


Pkcs12Store如果您只是想打开文件并获取密钥,则使用该类要简单得多。您提供文件和文件密码以打开它。然后,一旦您创建了对象,您就有一个属性Aliases将列出文件中所有条目的别名。然后,您只需使用别名调用“GetKey”方法即可获取条目的密钥。

这是如何读取第一个条目的密钥的示例。

 Pkcs12Store pkcs12Store = new Pkcs12Store(new FileStream("test.p12", FileMode.Open), "password".ToCharArray());
 AsymmetricKeyEntry key = pkcs12Store.GetKey(pkcs12Store.Aliases.Cast<string>().First());
 RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)key.Key; // here you should check what kind of key it is to then access the specific key parameters

推荐阅读