0 votes
by (120 points)

I am using bouncy castle for generating ECKey pair but i am not able to create sshprivatekey from it. How can i accomplish this task?

1 Answer

0 votes
by (147k points)

To create an SshPrivateKey from a BouncyCastle EC key pair, you have to encode the key pair into a DER-encoded PKCS #8 format - this results i na byte array (or a file) that can be loaded into SshPrivateKey.

With the C# version of BouncyCastle, this can be achieved by the following code:

public static byte[] BouncyPrivateKeyParametersToPkcs8(Org.BouncyCastle.Crypto.Parameters.ECPrivateKeyParameters parameters)
{
    if (parameters == null)
    {
        throw new ArgumentNullException("parameters");
    }

    if (parameters.AlgorithmName != "ECDSA")
    {
        throw new CryptographicException("Not an ECDSA key.");
    }

    if (parameters.PublicKeyParamSet == null)
    {
        throw new CryptographicException("Not a named curve keypair.");
    }

    var bcPrivateKeyInfo = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(parameters);
    return bcPrivateKeyInfo.GetDerEncoded();
}

Then, just load the resulting byte array into SshPrivateKey:

byte[] pkcs8 = BouncyPrivateKeyParametersToPkcs8(bcPrivateKey);
var sshPrivateKey = new SshPrivateKey(pkcs8);
by (120 points)
I am getting "{"Object reference not set to an instance of an object."}" execption.

I am using below code to generate byte array in der format

        public static byte[] BouncyPrivateKeyParametersToPkcs8()
        {
            SecureRandom secureRandom = new SecureRandom();
            var keygenParam = new KeyGenerationParameters(secureRandom, 521);
            var keyGenerator = new ECKeyPairGenerator();
            keyGenerator.Init(keygenParam);
            AsymmetricKeyParameter key = keyGenerator.GenerateKeyPair().Private;

            var bcPrivateKeyInfo = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(key);
            byte[] stream = bcPrivateKeyInfo.GetDerEncoded();
            return stream;
        }
by (147k points)
Which versions of Rebex and BouncyCastle do you use? With current versions of both, your code seems to work fine. Please download my test project from https://www.rebex.net/getfile/81541e8057b5480c96506fc5e529ee5a/BouncyToRebex.zip and give it a try. Does this work or does it fail as well?
by (120 points)
edited by
I have executed the exact code you have shared but it is still giving me same exception. I am using trial version of Rebex and  BouncyCastle version 1.0.0.0
by (147k points)
My test project above references specific versions of Rebex and BouncyCastle from NuGet.org: Rebex.Common/Rebex.Networking 5.0.7027.0 and BouncyCastle 1.8.5. Could you please try using these versions instead of BouncyCastle 1.0.0.0?
by (120 points)
This worked. Thanks.
by (147k points)
Thanks for letting us know!
...