use*_*698 5 .net c# bouncycastle diffie-hellman .net-core
我必须与第三方签订 Diffie Hellman 协议,该第三方以 .NET ECDiffieHellmanCng XmlString 格式传输公钥。我无法更改他们的代码。他们发送的内容如下所示:
<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>
Run Code Online (Sandbox Code Playgroud)
他们使用典型的 .NET Framework 代码生成它,如下所示:
using (ECDiffieHellmanCng dhKey = new ECDiffieHellmanCng())
{
dhKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
dhKey.HashAlgorithm = CngAlgorithm.Sha256;
Console.WriteLine(dhKey.PublicKey.ToXmlString());
}
Run Code Online (Sandbox Code Playgroud)
他们希望以相同的格式接收我的公钥。他们像这样使用我的公钥:
ECDiffieHellmanCngPublicKey pbkey = ECDiffieHellmanCngPublicKey.FromXmlString(xmlHere);
Run Code Online (Sandbox Code Playgroud)
我在 .NET 核心 2.1 中工作。不幸的是,ECDiffieHellmanCng 类等目前尚未在 .NET 核心中实现。我想我可以为此使用 BouncyCastle for .NET Core 包:https ://www.nuget.org/packages/BouncyCastle.NetCore/ 我假设它们都实现了相同的标准并且它们将兼容。
我知道如何与充气城堡完全达成一致,但是我不清楚如何从 .NET ECDiffieHellmanCng 中的 xml 中的 X 和 Y 值开始,以及如何确保我使用兼容的参数. 我也不清楚如何从我生成的充气城堡公钥中获取 X 和 Y 值以发送回给他们。.net api 的充气城堡与 java api 不完全相同并且文档有限,这无济于事。
更新 1:阅读下面的一些评论后,ECDiffieHellmanCng 似乎确实在 .NET Core 中部分实现。大多数逻辑有效,但只有 ToXmlString 和 FromXmlString 无效。没关系,我可以解决这个问题。但是我现在遇到了一个不同的问题。对方使用的曲线是oid:1.3.132.0.35。但是,当我尝试在 .NET core 中使用它时,即使是这样的基本示例:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
然后我收到这个错误:
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)
Run Code Online (Sandbox Code Playgroud)
我不清楚错误消息。那条曲线真的不支持吗?或者参数有问题,但究竟是什么?如果不支持曲线,我会感到惊讶,因为支持 nistP521 曲线,根据我在网上找到的这个 IBM 文档,它们是相同的:https ://www.ibm.com/support/knowledgecenter/en/linuxonibm/com.ibm .linux.z.wskc.doc/wskc_r_eckt.html
感谢你的帮助。最终我编写了这段代码,该代码适用于 .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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1145 次 |
| 最近记录: |