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

Making use of the library if having the private key pre-generated as a byte array? #35

Closed ASagaidak closed 3 years ago

ASagaidak commented 3 years ago

Hello, I have a program that already signs with Ed25519. Currently I am using a different library for that which allows providing a byte array as a private key to sign data. I consider transitioning to this library instead but would like to keep using the old private key. Should I be able to create a "Key" object with my own private key as a byte array?

ektrah commented 3 years ago

Yes, you can create a Key instance from a byte array using the Key.Import method. For that, you need to know the format of the byte array. Without knowing where you got the old private key from, I guess it's 32 raw private key bytes. In that case, it would look like this:

using var key = Key.Import(SignatureAlgorithm.Ed25519, theByteArray, KeyBlobFormat.RawPrivateKey);

Since key import is relatively expensive, try to avoid importing the byte array for every single signing operation. Instead, pass around the Key instance in your application and only export/import it when really necessary.

(Also, if possible, try to avoid the RawPrivateKey format. Instead, I'd recommend the PkixPrivateKeyText (ASCII text) or PkixPrivateKey (binary) format. These also include the information that it's an Ed25519 key, so you don't accidentally import something that has 32 bytes but isn't an Ed25519 key.)