#ECDiffieHellmanCngの動作サンプル
C#でEC-DH鍵交換を試すためのアプリケーションです。
- フォームにTextBox3つとボタン2つが必要です。
- 一方の当事者だけを実現するアプリケーションですので、同じマシンでも別のマシンでもいいですがアプリケーションを2つ起動してください。
- button1をクリックすると、自分側のキーがtextBox1に入ります
- 相手から受け取ったキーをtextBox2に入れてbutton2をクリックすると、textBox3に共有キーが入ります。
- もう一方でも同じ操作をすれば共有キーは一致するはずです。
using System;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public static byte[] publicKey;
ECDiffieHellmanCng ecdh = new ECDiffieHellmanCng();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ecdh.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
ecdh.HashAlgorithm = CngAlgorithm.Sha256;
publicKey = ecdh.PublicKey.ToByteArray();
textBox1.Text = BitConverter.ToString(publicKey);
Clipboard.SetText(textBox1.Text);
}
private void button2_Click(object sender, EventArgs e)
{
String[] arr = textBox2.Lines[0].Split('-');
byte[] array = new byte[arr.Length];
for (int i = 0; i < arr.Length; i++) array[i] = Convert.ToByte(arr[i], 16);
CngKey.Import(array, CngKeyBlobFormat.EccPublicBlob);
byte[] key = ecdh.DeriveKeyMaterial(CngKey.Import(array, CngKeyBlobFormat.EccPublicBlob));
textBox3.Text = BitConverter.ToString(key);
}
}
}