raju.net raju.net - 2 months ago 27
Java Question

How to get PKCS8 privatekey from byte stream in C#

Trying to get PKCS8 private key using below code, getting null exception error.

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);
}


Getting following error in stack trace

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


If I use
X9ObjectIdentifiers.IdDsa
I get this error

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


Actual working code in JAVA is this. Please check it and help me out in C#

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

Answer

I suggest using the following code, I believe it is equivalent to the Java version:

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