.NET ECDiffieHellmanCng与BouncyCastle Core兼容协议

.NET ECDiffieHellmanCng and BouncyCastle Core compatible agreement

我必须与以 .NET ECDiffieHellmanCng XmlString 格式传送 public 密钥的第三方达成 Diffie Hellman 协议。我无法更改他们的代码。 他们发送的内容如下所示:

<ECDHKeyValue xmlns="http://www.w3.org/2001/04/xmldsig-more#">
  <DomainParameters>
    <NamedCurve URN="urn:oid:1.3.132.0.35" />
  </DomainParameters>
  <PublicKey>
    <X Value="11" xsi:type="PrimeFieldElemType" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
    <Y Value="17" xsi:type="PrimeFieldElemType" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
  </PublicKey>
</ECDHKeyValue>

他们使用典型的 .NET Framework 代码生成该代码,如下所示:

using (ECDiffieHellmanCng dhKey = new ECDiffieHellmanCng())
{
    dhKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
    dhKey.HashAlgorithm = CngAlgorithm.Sha256;

    Console.WriteLine(dhKey.PublicKey.ToXmlString());
}

他们希望以相同的格式收到我的 public 密钥。 他们这样使用我的 public 密钥:

ECDiffieHellmanCngPublicKey pbkey = ECDiffieHellmanCngPublicKey.FromXmlString(xmlHere);

我在 .NET Core 2.1 工作。不幸的是,ECDiffieHellmanCng 类 等目前未在 .NET 核心中实现。 我想我可以为此使用 BouncyCastle for .NET Core 包:https://www.nuget.org/packages/BouncyCastle.NetCore/ 我假设它们都执行相同的标准并且它们是兼容的。

我知道如何与充气城堡完全达成协议,但我不清楚如何从 .NET ECDiffieHellmanCng 中的 xml 中的 X 和 Y 值开始以及如何确保我使用兼容的参数。 我也不清楚我是如何从我生成的充气城堡 public 密钥中获取 X 和 Y 值并发回给他们的。 .net api 的充气城堡与 java api 的充气城堡不完全相同,而且文档有限,这无济于事。

更新 1: 阅读下面的一些评论后,ECDiffieHellmanCng 似乎确实在 .NET Core 中部分实现了。大多数逻辑都有效,但只有 ToXmlString 和 FromXmlString 无效。没关系,我可以解决这个问题。 但是,我现在 运行 遇到了另一个问题。对方使用的曲线是oid:1.3.132.0.35。 然而,当我尝试在 .NET 核心中使用它时,即使是像这样的基本示例:

    using (ECDiffieHellman dhBob = ECDiffieHellman.Create(ECCurve.CreateFromValue("1.3.132.0.35")))
    {
        using (ECDiffieHellman dhAlice = ECDiffieHellman.Create(ECCurve.CreateFromValue("1.3.132.0.35")))
        {
            byte[] b = dhAlice.DeriveKeyMaterial(dhBob.PublicKey);

            byte[] b2 = dhBob.DeriveKeyMaterial(dhAlice.PublicKey);

            Console.WriteLine(b.SequenceEqual(b2));
        }
    }

然后我得到这个错误:

Unhandled Exception: System.PlatformNotSupportedException: The specified curve 'ECDSA_P521' or its parameters are not valid for this platform. ---> Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: The parameter is incorrect
   at System.Security.Cryptography.CngKeyLite.SetProperty(SafeNCryptHandle ncryptHandle, String propertyName, Byte[] value)
   at System.Security.Cryptography.CngKeyLite.SetCurveName(SafeNCryptHandle keyHandle, String curveName)
   at System.Security.Cryptography.CngKeyLite.GenerateNewExportableKey(String algorithm, String curveName)
   at System.Security.Cryptography.ECCngKey.GenerateKey(ECCurve curve)
   --- End of inner exception stack trace ---
   at System.Security.Cryptography.ECCngKey.GenerateKey(ECCurve curve)
   at System.Security.Cryptography.ECDiffieHellman.Create(ECCurve curve)
   at TestCore.Program.Main(String[] args) 

我不清楚错误信息。真的不支持那条曲线吗?或者参数有问题,但究竟是什么? 如果不支持该曲线,我会感到惊讶,因为支持 nistP521 曲线,并且根据我在网上找到的这篇 IBM 文档,它们是相同的:https://www.ibm.com/support/knowledgecenter/en/linuxonibm/com.ibm.linux.z.wskc.doc/wskc_r_ecckt.html

看起来在使用 ECDH 处理这些 OID 时存在等效性问题(它将其转换为 Windows ECDSA 名称而不是 Windows ECDH 名称)。你可以用

之类的东西解决它
private static ECCurve GetCurveByOid(string oidValue)
{
    switch (oidValue)
    {
        case "1.2.840.10045.3.1.7":
            return ECCurve.NamedCurves.nistP256;
        case "1.3.132.0.34":
            return ECCurve.NamedCurves.nistP384;
        case "1.3.132.0.35":
            return ECCurve.NamedCurves.nistP521;
    }

    return ECCurve.CreateFromValue(oidValue);
}

感谢大家的帮助。最终我写了这段代码,它适用于 .Net Core 2.1 并且与 .Net Framework To/FromXmlString:

兼容
        using (ECDiffieHellmanCng dhBob = new ECDiffieHellmanCng())
        {
            dhBob.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            dhBob.HashAlgorithm = CngAlgorithm.Sha256;
            string xmlBob = ToXmlString(dhBob.PublicKey);
            //Console.WriteLine(xmlBob);

            using (ECDiffieHellmanCng dhAlice = new ECDiffieHellmanCng())
            {
                dhAlice.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
                dhAlice.HashAlgorithm = CngAlgorithm.Sha256;
                ECDiffieHellmanPublicKey keyBob = FromXmlString(xmlBob, dhAlice.KeySize);
                byte[] b = dhAlice.DeriveKeyMaterial(keyBob);


                string xmlAlice = ToXmlString(dhAlice.PublicKey);
                ECDiffieHellmanPublicKey keyAlice = FromXmlString(xmlAlice, dhBob.KeySize);
                byte[] b2 = dhBob.DeriveKeyMaterial(keyAlice);

                Console.WriteLine(b.SequenceEqual(b2));
            }
        }

public static string ToXmlString(ECDiffieHellmanPublicKey key)
{
    // the regular ToXmlString from ECDiffieHellmanPublicKey throws PlatformNotSupportedException on .net core 2.1
    ECParameters parameters = key.ExportParameters();
    return string.Format("<ECDHKeyValue xmlns='http://www.w3.org/2001/04/xmldsig-more#'><DomainParameters><NamedCurve URN='urn:oid:{0}' />" +
                         "</DomainParameters><PublicKey><X Value='{1}' xsi:type='PrimeFieldElemType' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' />" +
                         "<Y Value='{2}' xsi:type='PrimeFieldElemType' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' /></PublicKey></ECDHKeyValue>",
        GetOid(parameters.Curve),
        new BigInteger(parameters.Q.X.Reverse().ToArray().Concat(new byte[] { 0 }).ToArray()).ToString(System.Globalization.CultureInfo.InvariantCulture), // watch out for big endian - little endian
        new BigInteger(parameters.Q.Y.Reverse().ToArray().Concat(new byte[] { 0 }).ToArray()).ToString(System.Globalization.CultureInfo.InvariantCulture));
}

public static ECDiffieHellmanPublicKey FromXmlString(string xml, int keySize)
{
    // the regular FromXmlString from ECDiffieHellmanPublicKey throws PlatformNotSupportedException on .net core 2.1
    XDocument doc = XDocument.Parse(xml);
    XNamespace nsSys = "http://www.w3.org/2001/04/xmldsig-more#";
    string xString = doc.Element(nsSys + "ECDHKeyValue").Element(nsSys + "PublicKey").Element(nsSys + "X").Attribute("Value").Value;
    string yString = doc.Element(nsSys + "ECDHKeyValue").Element(nsSys + "PublicKey").Element(nsSys + "Y").Attribute("Value").Value;
    string curve = doc.Element(nsSys + "ECDHKeyValue").Element(nsSys + "DomainParameters").Element(nsSys + "NamedCurve").Attribute("URN").Value;
    curve = curve.Replace("urn:", "").Replace("oid:", "");

    byte[] arrayX = BigInteger.Parse(xString, System.Globalization.CultureInfo.InvariantCulture).ToByteArray(false, true); // watch out for big endian - little endian
    byte[] arrayY = BigInteger.Parse(yString, System.Globalization.CultureInfo.InvariantCulture).ToByteArray(false, true);

    // make sure each part has the correct and same size
    int partSize = (int) Math.Ceiling(keySize / 8.0);
    ResizeRight(ref arrayX, partSize);
    ResizeRight(ref arrayY, partSize);

    ECParameters parameters = new ECParameters() { Q = new ECPoint() { X = arrayX, Y = arrayY }, Curve = GetCurveByOid(curve) };
    ECDiffieHellman dh = ECDiffieHellman.Create(parameters);
    return dh.PublicKey;
}

/// <summary>
/// Resize but pad zeroes to the left instead of to the right like Array.Resize
/// </summary>
public static void ResizeRight(ref byte[] b, int length)
{
    if (b.Length == length)
        return;
    if (b.Length > length)
        throw new NotSupportedException();

    byte[] newB = new byte[length];
    Array.Copy(b, 0, newB, length - b.Length, b.Length);
    b = newB;
}

private static ECCurve GetCurveByOid(string oidValue)
{
    // there are strange bugs in .net core 2.1 where the createfromvalue doesn't work for the named curves
    switch (oidValue)
    {
        case "1.2.840.10045.3.1.7":
            return ECCurve.NamedCurves.nistP256;
        case "1.3.132.0.34":
            return ECCurve.NamedCurves.nistP384;
        case "1.3.132.0.35":
            return ECCurve.NamedCurves.nistP521;
        default:
            return ECCurve.CreateFromValue(oidValue);
    }
}

private static string GetOid(ECCurve curve)
{
    // there are strange bugs in .net core 2.1 where the value of the oid of the named curves is empty
    if (curve.Oid.FriendlyName == ECCurve.NamedCurves.nistP256.Oid.FriendlyName)
        return "1.2.840.10045.3.1.7";
    else if (curve.Oid.FriendlyName == ECCurve.NamedCurves.nistP384.Oid.FriendlyName)
        return "1.3.132.0.34";
    else if (curve.Oid.FriendlyName == ECCurve.NamedCurves.nistP521.Oid.FriendlyName)
        return "1.3.132.0.35";
    else
        return curve.Oid.Value;
}