Encryto Message

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;


namespace EncryptionDemo
{
    public class EncryptoKeySenddingDemo
    {
        public EncryptoKeySenddingDemo()
        {
            this.CreateKeys();
        }


        private static CngKey aliceKeySignature;
        private static CngKey bobKeySignature;
        private static byte[] alicePubKeyBlob;
        private static byte[] bobPubKeyBlob;


        /// <summary>
        /// Create public keys.
        /// </summary>
        private void CreateKeys()
        {
            aliceKeySignature = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);
            bobKeySignature = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);
            alicePubKeyBlob = aliceKeySignature.Export(CngKeyBlobFormat.EccPublicBlob);
            bobPubKeyBlob = bobKeySignature.Export(CngKeyBlobFormat.EccPublicBlob);
        }


        /// <summary>
        /// Alice send message to Bob.
        /// </summary>
        /// <param name="message"></param>
        /// <returns>Return encrypted data.</returns>
        public byte[] AliceSendData(string message)
        {
            Console.WriteLine("Alice Send message: " + message);
            //Encodding message to byte data.
            var rawData = Encoding.UTF8.GetBytes(message);
            byte[] encryptoData = null;


            //Create ECDiffidhellman encrypto algorithm.
            ECDiffieHellmanCng aliceKeyAlg = new ECDiffieHellmanCng(aliceKeySignature);
            using (CngKey bobkey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob))
            {
                //Create symmetric key with Bob's public key.
                var symmetricKey = aliceKeyAlg.DeriveKeyMaterial(bobkey);
                Console.WriteLine("Alice create summetric key with Bob's public key info: " + Convert.ToBase64String(symmetricKey));
                
                //Init AES symmetric algorithm.
                AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
                aes.Key = symmetricKey;
                aes.GenerateIV();


                //Write encodded message sent by Alice.
                using (ICryptoTransform encryptor = aes.CreateEncryptor())
                using (MemoryStream ms = new MemoryStream())
                {
                    //Init crypto stream.
                    CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
                    //Send iv without encrypted.
                    ms.Write(aes.IV, 0, aes.IV.Length);
                    //Send message by encrypted stream.
                    cs.Write(rawData, 0, rawData.Length);
                    cs.Close();
                    encryptoData = ms.ToArray();
                }
                //Note: Clear encrypto althorithm.
                aes.Clear();
                Console.WriteLine("Alice's message encrypted: " + Convert.ToBase64String(encryptoData));
            }


            return encryptoData;
        }


        /// <summary>
        /// Bob received data sent by Alice.
        /// </summary>
        /// <param name="encryptedData"></param>
        public void BobReceivesData(byte[] encryptedData)
        {
            Console.WriteLine("Bob receives encryted data: " + Convert.ToBase64String(encryptedData));
            byte[] rawData = null;


            //Get init vector data, its lenght is divisible by 8 with AES block size.
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            var nBytes = aes.BlockSize >> 3;
            var iv = new byte[nBytes];
            for(var i = 0; i < iv.Length; i++)
            {
                iv[i] = encryptedData[i];
            }


            //Create Bob's ECDiffiehellman algorihtm.
            ECDiffieHellmanCng bobKeyAlg = new ECDiffieHellmanCng(bobKeySignature);
            using(CngKey aliceKey = CngKey.Import(alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob))
            {
                //Create symmetric key with Alice's public key blob.
                var symmetirc = bobKeyAlg.DeriveKeyMaterial(aliceKey);
                Console.WriteLine("Bob create symmetric key with Alice's public key blob: " + Convert.ToBase64String(symmetirc));
                aes.Key = symmetirc;
                aes.IV = iv;
                //Decrypt message sent by Alice.
                using(ICryptoTransform decryptor = aes.CreateDecryptor())
                using (MemoryStream ms = new MemoryStream())
                {
                    CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write);
                    cs.Write(encryptedData, nBytes, encryptedData.Length - nBytes);
                    cs.Close();
                    rawData = ms.ToArray();
                    Console.WriteLine("Bob decrypted message: " + Encoding.UTF8.GetString(rawData));
                }
                //Note: Don't forgeet to clear the crypto algorithm.
                bobKeyAlg.Clear();
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值