从 private 获取 X、Y 坐标,从 AsymmetricKeyParameter 获取 public

Get X, Y coords from private and public from AsymmetricKeyParameter

public class EccGenerator
{
    public AsymmetricCipherKeyPair GenerateKeyPairs(int keySize)
    {
        ECKeyPairGenerator gen = new ECKeyPairGenerator("ECDSA");
        KeyGenerationParameters keyGenParam = new KeyGenerationParameters(new SecureRandom(), keySize);
        gen.Init(keyGenParam);
        AsymmetricCipherKeyPair keyPair = gen.GenerateKeyPair();
        return keyPair;
    }

    public static void  PrintPublicX_Y(AsymmetricKeyParameter publicKey)
    {
        ECPublicKeyParameters key = (ECPublicKeyParameters)publicKey;
        string X = Encoding.ASCII.GetString(UrlBase64.Encode(key.Q.XCoord.ToBigInteger().ToByteArrayUnsigned()));
        string Y = Encoding.ASCII.GetString(UrlBase64.Encode(key.Q.YCoord.ToBigInteger().ToByteArrayUnsigned()));
        Console.WriteLine(X + "--" + Y);
    }

    public static void PrintPrivateX_Y(AsymmetricKeyParameter privateKey)
    {
        ECPrivateKeyParameters key = (ECPrivateKeyParameters)privateKey;
        string D = Encoding.ASCII.GetString(UrlBase64.Encode(key.D.ToByteArrayUnsigned()));
        string X = Encoding.ASCII.GetString(UrlBase64.Encode(key.Parameters.G.XCoord.ToBigInteger().ToByteArrayUnsigned()));
        string Y = Encoding.ASCII.GetString(UrlBase64.Encode(key.Parameters.G.YCoord.ToBigInteger().ToByteArrayUnsigned()));
        Console.WriteLine(X + "--" + Y);
    }

    public static void Main(string[] args)
    {
        EccGenerator ecc = new EccGenerator();
        AsymmetricCipherKeyPair pair = ecc.GenerateKeyPairs(256);
        PrintPublicX_Y(pair.Public);
        PrintPrivateX_Y(pair.Private);
    }
}

这里的问题是 public 中的 X 和 private 不一样,Y 也一样,我怎样才能得到 private

的正确的 x 和 y 和 D

我正在使用 Bouncy Castle C#

public密钥是基点G乘以私钥D得到的,结果一般要归一化(后者负责投影坐标的变换,用于性能原因,进入仿射坐标,详情见here).

因此,在 PrintPrivateX_Y() 中,表达式 key.Parameters.G 必须替换为 key.Parameters.G.Multiply(key.D).Normalize()

以下替代代码:

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using System;
...
AsymmetricCipherKeyPair pair = GenerateKeyPairs(256);

ECPublicKeyParameters publicKeyParams = (ECPublicKeyParameters)pair.Public;
ECPoint publicKey = publicKeyParams.Q;
PrintKey(publicKey);

ECPrivateKeyParameters privateKeyParams = (ECPrivateKeyParameters)pair.Private;
ECPoint publicKeyViaPrivate = privateKeyParams.Parameters.G.Multiply(privateKeyParams.D).Normalize();
PrintKey(publicKeyViaPrivate);

public static void PrintKey(ECPoint ecPoint)
{
    string X = Hex.ToHexString(ecPoint.XCoord.ToBigInteger().ToByteArrayUnsigned());
    string Y = Hex.ToHexString(ecPoint.YCoord.ToBigInteger().ToByteArrayUnsigned());
    Console.WriteLine(X + " -- " + Y);
}

并且问题中发布的(静态)GenerateKeyPairs(int keySize) 使用十六进制表示显示两个 public 键与预期相同。