ektrah / nsec

A modern and easy-to-use cryptographic library for .NET 8+ based on libsodium
https://nsec.rocks
MIT License
374 stars 52 forks source link

Assistance with accessing Private Key. #43

Closed simonpbond closed 3 years ago

simonpbond commented 3 years ago

I am exploring the library and just wanted to confirm, if I generate a keypair using:

private static Key GenerateKeyPair()
        {
            var algorithm = SignatureAlgorithm.Ed25519;
            // Create a new key pair.
            using var key = Key.Create(algorithm, new KeyCreationParameters()
            {
                 ExportPolicy = KeyExportPolicies.AllowPlaintextExport
            });

            return key;

        }

The caller of the method will not be able to export the private key from the returned key object. The only chance to export the private key is within the above method prior to returning the object?

Is this correct? As when I try to peform the following on the returned key object (as the caller):

var privateKey = key.Export(KeyBlobFormat.KeyBlobFormat.RawPrivateKey);

I am told the object is already disposed.

sigaloid commented 3 years ago

It should be returning the entire key, which includes the private key... I don't think I had an issue when I used a method like that where it was generated within a called method, and exporting from outside of it. I'm not certain, but it could be an issue with the way you're generating/exporting it.

ektrah commented 3 years ago

The using keyword disposes the Key instance before the method returns. It should work if you return the instance without using it:

private static Key GenerateKeyPair()
{
    return Key.Create(SignatureAlgorithm.Ed25519, new KeyCreationParameters()
    {
        ExportPolicy = KeyExportPolicies.AllowPlaintextExport
    });
}

Just don't forget to dispose the Key when you're done using it elsewhere:

using (var key = GenerateKeyPair())
{
    var privateKey = key.Export(KeyBlobFormat.RawPrivateKey);
    ...
}
simonpbond commented 3 years ago

@ektrah Thank you so much.