如何从 C# 中的字节流中获取 PKCS8 私钥

How to get PKCS8 privatekey from byte stream in C#

当使用下面的代码检索 PKCS8 私钥时,我得到一个 NullReferenceException

public ECPrivateKeyParameters GetMerchantPrivateKey(byte[] privateKeyBite)
{
    Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(privateKeyBite);
    ECPrivateKeyStructure pKey = ECPrivateKeyStructure.GetInstance(seq);
    AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters());

    PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object());

    return (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privInfo);
}

[Fact]
public void GetMerchantPrivateKey__ShouldReturnPrivateKey__WhenPassPrivateKeyBytes()
{
    ApplePay applePay = new ApplePay(new MOBSHOPApplePayRequest());
    byte[] privateKey = Base64.Decode("MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgjyo3fzxT7j+CFxC7I4B5iVee2FUyn2vfOSjcgp2/g6qhRANCAARdoBFEtnuapXFKw4DYWsW0yV4bavpdWKszkefi19AhlIRE3WSNWSn25W5tZNFjMWtLISBmqANyufx2xP19oRvy");
    applePay.GetMerchantPrivateKey(privateKey);
}

堆栈跟踪

Object reference not set to an instance of an object.
BouncyCastle.Crypto
at Org.BouncyCastle.Security.PrivateKeyFactory.CreateKey(PrivateKeyInfo keyInfo)

如果我使用 X9ObjectIdentifiers.IdDsa 我会得到这个错误

Unable to cast object of type 'Org.BouncyCastle.Asn1.DerSequence' to type 'Org.BouncyCastle.Asn1.DerInteger'.

这个 Java 示例确实有效:

private PrivateKey inflatePrivateKey() throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance( "EC" );
        return keyFactory.generatePrivate( new PKCS8EncodedKeySpec( _dataProvider.getPrivateKeyBytes() ) );
    }

请检查并在 C# 中帮助我

我建议使用下面的代码,我相信它等同于 Java 版本:

public static ECPrivateKeyParameters GetMerchantPrivateKey(byte[] privateKeyBite)
{
    var akp = PrivateKeyFactory.CreateKey(privateKeyBite);
    return (ECPrivateKeyParameters)akp;
}