65.9K
CodeProject 正在变化。 阅读更多。
Home

Diffie-Hellman 密钥交换示例

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.81/5 (30投票s)

2004年1月9日

CPOL

2分钟阅读

viewsIcon

298392

downloadIcon

9636

这是一个示例,展示了两个用户如何使用 Diffie-Hellman 密钥交换方法共享加密密钥。

引言

在两个参与方之间加密消息以进行安全通信通常是必需的。那里有很多用于加密的算法,它们非常安全,但它们的弱点在于传输加密密钥。Diffie-Hellman 密钥交换协议允许人们以窃听者无法快速计算密钥的方式交换密钥。

这段代码演示了这种密钥交换的使用。

如何使用演示项目

要演示密钥交换的使用,请运行两个演示应用程序的副本。将其中一个设置为发送者,另一个设置为接收者。

发送者应生成公钥和发送者的中间密钥。将这些值粘贴到接收者应用程序的相应文本框中。接收者应然后单击以生成他/她的中间密钥,并将此密钥复制到发送者应用程序上的“接收者的中间密钥”文本框中。然后,两个应用程序应该能够通过单击“生成密钥”来生成相同的密钥。

使用源代码

DiffieHellman 类使用起来很简单,应该以以下方式集成

创建类的实例 - (例如 CDiffieHellman *DH = new CDiffieHellman;)

发送者应用程序然后执行以下操作

__int64 n = 0;
__int64 g = 0;
__int64 SInterim = 0;
__int64 RInterim = 0;
__int64 key = 0; 

DH->CreateKeys(g,n);
DH->CreateSenderInterKey(SInterim);

//The sender now sends (n, g, and SInterim) to the receiving application
//This can be done unencrypted because they are public keys
//Now we wait until the reciever send us their interim key lets say RInterim

DH->CreateSenderEncryptionKey(key,RInterim);
//The shared encryption key is now the value of 'key'

接收者应用程序执行以下操作

__int64 n = 0;
__int64 g = 0;
__int64 SInterim = 0;
__int64 RInterim = 0;
__int64 key = 0;

//Wait for the values of (n,g, and SInterim) to be sent here

DH->CreateRecipientInterKey(RInterim);

//Now send the RInterim key to the sender application

DH->CreateRecipientEncryptionKey(key,SInterim);
//The shared encryption key is now the value of 'key'

附加函数

CDiffieHellman 类有一些私有成员函数,您可能会觉得有用,请随时使用它们。

  • GeneratePrime() 函数生成一个大质数。
  • MillerRabinIsItPrime 函数可以结合使用来测试质数。
  • XtoYmodN 是一个函数,用于以模 n 的形式将 x 提升到 y 的幂。虽然听起来计算机无法计算,例如 1.5 亿的 1.5 亿次幂,但可以通过使用幂链方法以模 n 的形式完成。

进一步帮助

如果您需要任何其他帮助,请随时与我联系。我很乐意听取您的评论、建议和任何问题。

© . All rights reserved.