I'm trying to read ES512 private key to create JWT token in .NET Framework 4.7.2 but it throws validation exception when I'm creating ECDsa object.
System.Security.Cryptography.CryptographicException: 'The specified key parameters are not valid. Q.X and Q.Y are required fields. Q.X, Q.Y must be the same length. If D is specified it must be the same length as Q.X and Q.Y for named curves or the same length as Order for explicit curves.'
What is wrong here? I checked internet and couldn't find any solution. In NET Core 3 it is working with ImportECPrivateKey method but I don't know how to do this in .NET Framework which I need.
class Program
{
static string privateKey = @"MIHcAgEBBEIBiyAa7aRHFDCh2qga9sTUGINE5jHAFnmM8xWeT/uni5I4tNqhV5Xx0pDrmCV9mbroFtfEa0XVfKuMAxxfZ6LM/yKgBwYFK4EEACOhgYkDgYYABAGBzgdnP798FsLuWYTDDQA7c0r3BVk8NnRUSexpQUsRilPNv3SchO0lRw9Ru86x1khnVDx+duq4BiDFcvlSAcyjLACJvjvoyTLJiA+TQFdmrearjMiZNE25pT2yWP1NUndJxPcvVtfBW48kPOmvkY4WlqP5bAwCXwbsKrCgk6xbsp12ew==";
static void Main(string[] args)
{
var derArray = Convert.FromBase64String(privateKey);
LoadPrivateKey(derArray);
}
private static ECDsa LoadPrivateKey(byte[] key)
{
var privKeyInt = new Org.BouncyCastle.Math.BigInteger(+1, key);
var parameters = SecNamedCurves.GetByName("secp521r1");
var ecPoint = parameters.G.Multiply(privKeyInt);
var privKeyX = ecPoint.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned();
var privKeyY = ecPoint.Normalize().YCoord.ToBigInteger().ToByteArrayUnsigned();
return ECDsa.Create(new ECParameters
{
Curve = ECCurve.NamedCurves.nistP521,
D = privKeyInt.ToByteArrayUnsigned(),
Q = new ECPoint
{
X = privKeyX,
Y = privKeyY
}
});
}
}