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

时间:2016-10-01 17:39:55

标签: c# bouncycastle crypt

使用以下代码检索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#中帮助我

1 个答案:

答案 0 :(得分:0)

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

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