我有以下代碼:有關在.net framework 4.7中執行ECDiffieHellmanCng的祕密協議的問題?
var curve = ECCurve.NamedCurves.nistP256;
var ecdhSender = ECDiffieHellman.Create(curve);
var ecdhReceiver = ECDiffieHellman.Create(curve);
我的理解是,我應該能夠計算祕密協議,無論是從使用ecdhSender對象使用ecdhReceiver.PublicKey或使用與ecdhSender.PublicKey ecdhReceiver對象和兩個祕密協議值應相同。如果這是一個錯誤的假設,請讓我知道。
由於ECDiffieHellman.Create返回ECDiffieHellman類型,我寫了下面的代碼來獲取祕密協議:
string receiverHexString = null;
using (SafeNCryptSecretHandle secretAgreement = (ecdhReceiver as ECDiffieHellmanCng).DeriveSecretAgreementHandle(ecdhSender.PublicKey))
{
byte[] secretAgreementBytes = new byte[32];
IntPtr pointer = secretAgreement.DangerousGetHandle();
Marshal.Copy(pointer, secretAgreementBytes, 0, secretAgreementBytes.Length);
receiverHexString = BitConverter.ToString(secretAgreementBytes).Replace("-", string.Empty).ToLower();
Console.WriteLine($"receiver secretAgreement: 0x{receiverHexString}");
}
string senderHexString = null;
using (SafeNCryptSecretHandle secretAgreement = (ecdhSender as ECDiffieHellmanCng).DeriveSecretAgreementHandle(ecdhReceiver.PublicKey))
{
byte[] secretAgreementBytes = new byte[32];
IntPtr pointer = secretAgreement.DangerousGetHandle();
Marshal.Copy(pointer, secretAgreementBytes, 0, secretAgreementBytes.Length);
senderHexString = BitConverter.ToString(secretAgreementBytes).Replace("-", string.Empty).ToLower();
Console.WriteLine($"sender secretAgreement: 0x{senderHexString}");
}
Assert.AreEqual(receiverHexString, senderHexString);
我斷言失敗。顯然我做錯了一些事情(如果祕密協議應該是相同的)。
難道我是如何提取字節的句柄嗎?或者是其他東西?
你想完成什麼? NCRYPT_SECRET_HANDLE結構是不透明的,你不應該讀它的內存。 – bartonjs
嘗試使用詳細步驟驗證來自合作伙伴的結果。如果在我的問題的第一部分中,我的假設是正確的還是錯誤的,請您評論一下嗎? – Raghu