1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6 using System.Security.Cryptography;
7 using System.IO;
8
9 namespace SecurityDemo
10 {
11 class Program
12 {
13 static CngKey aliceKey;
14 static CngKey bobKey;
15 static byte[] alicePubKeyBlob;
16 static byte[] bobPubKeyBlob;
17
18 static void Main(string[] args)
19 {
20 Console.ForegroundColor = ConsoleColor.Green;
21 CreateKey();
22 byte[] encrytpedData = AliceSendData("123");
23 BobReceiveData(encrytpedData);
24 Console.ReadKey();
25 }
26
27 public static void CreateKey()
28 {
29 aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);
30 bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);
31 alicePubKeyBlob = aliceKey.Export(CngKeyBlobFormat.EccPublicBlob);
32 bobPubKeyBlob = bobKey.Export(CngKeyBlobFormat.EccPublicBlob);
33 }
34
35 private static byte[] AliceSendData(string msg)
36 {
37 Console.WriteLine(string.Format("Alice Send Msg: {0}", msg));
38 byte[] rawdata = Encoding.UTF8.GetBytes(msg);
39 byte[] encryptedData = null;
40 using (var aliceAlgorithm = new ECDiffieHellmanCng(aliceKey))
41 using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob))
42 {
43 byte[] symmkey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey);
44
45 Console.WriteLine(string.Format("Alice Create this symmtric key with {0}", Convert.ToBase64String(symmkey)));
46
47 var aes = new AesCryptoServiceProvider();
48 aes.Key = symmkey;
49 aes.GenerateIV();
50 using (ICryptoTransform encryptor = aes.CreateEncryptor())
51 using (MemoryStream ms = new MemoryStream())
52 {
53 var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
54 ms.Write(aes.IV, 0, aes.IV.Length);
55 cs.Write(rawdata, 0, rawdata.Length);
56 cs.Close();
57 encryptedData = ms.ToArray();
58 }
59 aes.Clear();
60 }
61
62 Console.WriteLine(Convert.ToBase64String(encryptedData));
63 return encryptedData;
64 }
65
66 private static void BobReceiveData(byte[] encryptData)
67 {
68 byte[] rawdata = null;
69 var aes = new AesCryptoServiceProvider();
70 int nBytes = aes.BlockSize >> 3; // bit to Byte, need to devide 8
71 byte[] iv = new byte[nBytes];
72
73 for (int i = 0; i < iv.Length; i++)
74 iv[i] = encryptData[i];
75 using (var bobAlgorithm = new ECDiffieHellmanCng(bobKey))
76 using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob))
77 {
78 byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey);
79 Console.WriteLine(Convert.ToBase64String(symmKey));
80 aes.Key = symmKey;
81 aes.IV = iv;
82 }
83 using (ICryptoTransform decryptor = aes.CreateDecryptor())
84 using (MemoryStream ms = new MemoryStream())
85 {
86 var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write);
87 cs.Write(encryptData, nBytes, encryptData.Length - nBytes);
88 cs.Close();
89 rawdata = ms.ToArray();
90 Console.WriteLine(Encoding.UTF8.GetString(rawdata));
91 }
92 aes.Clear();
93 }
94 }
95
96 }