Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

ECDiffieHellmanCngのサンプル

More than 5 years have passed since last update.

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);
        }
    }
}
suzukis
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away