public static Int32 Main(string[] args) { Console.CancelKeyPress += new ConsoleCancelEventHandler(MainClass.ConsoleShutdown); Server myServer = new Server(); try { myServer.Start(); do { myServer.Update(); Thread.Sleep(10); if (MainClass.doShutDown == true) break; } while (true); myServer.Stop(); return 0; } catch (Exception e) { Console.ForegroundColor = ConsoleColor.DarkRed; Console.BackgroundColor = ConsoleColor.Gray; Console.WriteLine(e); Console.ReadKey(); return -1; } using (var ec = new ECDiffieHellmanCng(eccKey)) { var message = "Hello World!"; Console.WriteLine("Real Message: "); Console.WriteLine(message); } }
public static byte[] DeriveKey(CngKey externalPubKey, CngKey privateKey, int keyBitLength, byte[] algorithmId, byte[] partyVInfo, byte[] partyUInfo, byte[] suppPubInfo) { using (var cng = new ECDiffieHellmanCng(privateKey)) { using (SafeNCryptSecretHandle hSecretAgreement = cng.DeriveSecretAgreementHandle(externalPubKey)) { using (var algIdBuffer = new NCrypt.NCryptBuffer(NCrypt.KDF_ALGORITHMID, algorithmId)) using (var pviBuffer = new NCrypt.NCryptBuffer(NCrypt.KDF_PARTYVINFO, partyVInfo)) using (var pvuBuffer = new NCrypt.NCryptBuffer(NCrypt.KDF_PARTYUINFO, partyUInfo)) using (var spiBuffer = new NCrypt.NCryptBuffer(NCrypt.KDF_SUPPPUBINFO, suppPubInfo)) { using (var parameters = new NCrypt.NCryptBufferDesc(algIdBuffer, pviBuffer, pvuBuffer, spiBuffer)) { uint derivedSecretByteSize; uint status = NCrypt.NCryptDeriveKey(hSecretAgreement, "SP800_56A_CONCAT", parameters, null, 0, out derivedSecretByteSize, 0); if (status != BCrypt.ERROR_SUCCESS) throw new CryptographicException(string.Format("NCrypt.NCryptDeriveKey() failed with status code:{0}", status)); var secretKey = new byte[derivedSecretByteSize]; status = NCrypt.NCryptDeriveKey(hSecretAgreement, "SP800_56A_CONCAT", parameters, secretKey, derivedSecretByteSize, out derivedSecretByteSize, 0); if (status != BCrypt.ERROR_SUCCESS) throw new CryptographicException(string.Format("NCrypt.NCryptDeriveKey() failed with status code:{0}", status)); return Arrays.LeftmostBits(secretKey, keyBitLength); } } } } }
public string Decription(byte[] encryptedData, byte[] alicePubKeyBlob) { byte[] rawData = null; var aes = new AesCryptoServiceProvider(); int nBytes = aes.BlockSize >> 3; byte[] iv = new byte[nBytes]; for (int i = 0; i < iv.Length; i++) iv[i] = encryptedData[i]; using (var bobAlgorithm = new ECDiffieHellmanCng(privKey)) using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey); aes.Key = symmKey; aes.IV = iv; using (ICryptoTransform decryptor = aes.CreateDecryptor()) using (MemoryStream ms = new MemoryStream()) { var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write); cs.Write(encryptedData, nBytes, encryptedData.Length - nBytes); cs.Close(); rawData = ms.ToArray(); } aes.Clear(); } return Encoding.UTF8.GetString(rawData); }
public static void Main(string[] args) { ECDiffieHellmanCng alice = new ECDiffieHellmanCng(); //alice.DeriveKeyMaterial( //CngKey.Import( // create a new DH instance DiffieHellman dh1 = new DiffieHellmanManaged(); // export the public parameters of the first DH instance DHParameters dhp = dh1.ExportParameters(false); // create a second DH instance and initialize it with the public parameters of the first instance DiffieHellman dh2 = new DiffieHellmanManaged(dhp.P, dhp.G, 160); // generate the public key of the first DH instance byte[] ke1 = dh1.CreateKeyExchange(); // generate the public key of the second DH instance byte[] ke2 = dh2.CreateKeyExchange(); // let the first DH instance compute the shared secret using the second DH public key byte[] dh1k = dh1.DecryptKeyExchange(ke2); // let the second DH instance compute the shared secret using the first DH public key byte[] dh2k = dh2.DecryptKeyExchange(ke1); // print both shared secrets to verify they are the same Console.WriteLine("Computed secret of instance 1:"); PrintBytes(dh1k); Console.WriteLine("\r\nComputed secret of instance 2:"); PrintBytes(dh2k); Console.WriteLine("\r\nPress ENTER to continue..."); Console.ReadLine(); }
public byte[] Encription(string message, byte[] bobPubKeyBlob) { byte[] rawData = Encoding.UTF8.GetBytes(message); byte[] encryptedData = null; using (var aliceAlgorithm = new ECDiffieHellmanCng(privKey)) using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey); using (var aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (MemoryStream ms = new MemoryStream()) { // create CryptoStream and encrypt data to send var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); // write initialization vector not encrypted ms.Write(aes.IV, 0, aes.IV.Length); cs.Write(rawData, 0, rawData.Length); cs.Close(); encryptedData = ms.ToArray(); } aes.Clear(); } } return encryptedData; }
private static byte[] AliceSendData(string msg) { Console.WriteLine(string.Format("Alice Send Msg: {0}", msg)); byte[] rawdata = Encoding.UTF8.GetBytes(msg); byte[] encryptedData = null; using (var aliceAlgorithm = new ECDiffieHellmanCng(aliceKey)) using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmkey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey); Console.WriteLine(string.Format("Alice Create this symmtric key with {0}", Convert.ToBase64String(symmkey))); var aes = new AesCryptoServiceProvider(); aes.Key = symmkey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (MemoryStream ms = new MemoryStream()) { var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); ms.Write(aes.IV, 0, aes.IV.Length); cs.Write(rawdata, 0, rawdata.Length); cs.Close(); encryptedData = ms.ToArray(); } aes.Clear(); } Console.WriteLine(Convert.ToBase64String(encryptedData)); return encryptedData; }
private static Aes CreateAesForServer(ProgramOptions options, BinaryReader reader, BinaryWriter writer) { if (!options.Encrypt) return null; using (var ke = new ECDiffieHellmanCng()) { // expecting client's public key var len = reader.ReadInt32(); byte[] key; using (var remotePubKey = CngKey.Import(reader.ReadBytes(len), CngKeyBlobFormat.EccPublicBlob)) key = ke.DeriveKeyMaterial(remotePubKey); var aes = new AesCryptoServiceProvider(); using (var kdf = new Rfc2898DeriveBytes(key, Salt.ToArray(), KdfIterations)) aes.Key = kdf.GetBytes(aes.KeySize / 8); // send pub key and IV to client var localPubKey = ke.PublicKey.ToByteArray(); writer.Write(localPubKey.Length); writer.Write(localPubKey); writer.Write(aes.IV.Length); writer.Write(aes.IV); return aes; } }
private static void BobReceiveData(byte[] encryptData) { byte[] rawdata = null; var aes = new AesCryptoServiceProvider(); int nBytes = aes.BlockSize >> 3; // bit to Byte, need to devide 8 byte[] iv = new byte[nBytes]; for (int i = 0; i < iv.Length; i++) iv[i] = encryptData[i]; using (var bobAlgorithm = new ECDiffieHellmanCng(bobKey)) using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey); Console.WriteLine(Convert.ToBase64String(symmKey)); aes.Key = symmKey; aes.IV = iv; } using (ICryptoTransform decryptor = aes.CreateDecryptor()) using (MemoryStream ms = new MemoryStream()) { var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write); cs.Write(encryptData, nBytes, encryptData.Length - nBytes); cs.Close(); rawdata = ms.ToArray(); Console.WriteLine(Encoding.UTF8.GetString(rawdata)); } aes.Clear(); }
private async static Task<byte[]> AliceSendsData(string message) { Console.WriteLine("Alice send message {0}", message); byte[] rawData = Encoding.UTF8.GetBytes(message); byte[] encryptedData = null; using(var aliceAlgo = new ECDiffieHellmanCng(aliceKey)) { using(CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.GenericPublicBlob)) { byte[] symmKey = aliceAlgo.DeriveKeyMaterial(bobPubKey); Console.WriteLine("Alice create this symm key with Bobs public key information : {0}", Convert.ToBase64String(symmKey)); using(var aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using(ICryptoTransform encryptor = aes.CreateEncryptor()) { using(MemoryStream ms = new MemoryStream()) { var cs = new CryptoStream(ms, encryptor,CryptoStreamMode.Write); await ms.WriteAsync(aes.IV, 0, aes.IV.Length); cs.Write(rawData, 0, rawData.Length); cs.Close(); encryptedData = ms.ToArray(); } } aes.Clear(); } } } Console.WriteLine("Alice message is encrypted : {0}", Convert.ToBase64String(encryptedData)); return encryptedData; }
/// <summary> /// Decrypts a ProcessedPacket. /// </summary> /// <param name="InitializationVector">Initialization vec to be used by AES.</param> /// <param name="PrivateKey">Private key to be used.</param> /// <param name="PubKeyBlob">Public key blob to be used.</param> /// <param name="StreamToDecrypt">The stream to decrypt.</param> /// <returns>A decrypted stream.</returns> public static byte[] DecryptData(byte[] InitializationVector, CngKey PrivateKey, byte[] PubKeyBlob, byte[] DataToDecrypt) { using (var Algorithm = new ECDiffieHellmanCng(PrivateKey)) { using (CngKey PubKey = CngKey.Import(PubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] SymmetricKey = Algorithm.DeriveKeyMaterial(PubKey); Console.WriteLine("DecryptedStream: Created symmetric key with " + "public key information: {0}", Convert.ToBase64String(SymmetricKey)); AesCryptoServiceProvider AES = new AesCryptoServiceProvider(); AES.Key = SymmetricKey; AES.IV = InitializationVector; int NBytes = AES.BlockSize >> 3; //No idea... using (ICryptoTransform Decryptor = AES.CreateDecryptor()) { using (MemoryStream DecryptedStream = new MemoryStream()) { var cs = new CryptoStream(DecryptedStream, Decryptor, CryptoStreamMode.Write); cs.Write(DataToDecrypt, NBytes, DataToDecrypt.Length - NBytes); cs.FlushFinalBlock(); return DecryptedStream.ToArray(); } } } } }
public void TestEcdhKeys() { // To make sure keys are exportable: // http://stackoverflow.com/questions/20505325/how-to-export-private-key-for-ecdiffiehellmancng/20505976#20505976 var ecdhKeyParams = new CngKeyCreationParameters { KeyUsage = CngKeyUsages.AllUsages, ExportPolicy = CngExportPolicies.AllowPlaintextExport }; var ecdhKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256, null, ecdhKeyParams); var ecdh = new ECDiffieHellmanCng(ecdhKey); ecdh.KeySize = 256; //Export the keys var privateKey = ecdh.Key.Export(CngKeyBlobFormat.EccPrivateBlob); // This returns: // [ { MinSize = 256; MaxSize = 384; SkipSize = 128 } // { MinSize = 521; MaxSize = 521; SkipSize = 0 } ] var keySizes = ecdh.LegalKeySizes; // Example of this: // <ECDHKeyValue xmlns="http://www.w3.org/2001/04/xmldsig-more#"> // <DomainParameters> // <NamedCurve URN="urn:oid:1.3.132.0.35" /> // </DomainParameters> // <PublicKey> // <X Value="6338036285454860977775086861655185721418051140960904673987863656163882965225521398319125216217757952736756437624751684728661860413862054254572205453827782795" xsi:type="PrimeFieldElemType" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" /> // <Y Value="2429739115523607678822648112222739155064474393176967830414279652115290771735466025346855521196073509912224542851147234378090051353981358078708633637907317343" xsi:type="PrimeFieldElemType" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" /> // </PublicKey> // </ECDHKeyValue> var pubKeyXml = ecdh.PublicKey.ToXmlString(); }
/// <summary> /// Creates an encrypted message /// </summary> /// <param name="recipientsEcPublicKey">The public portion of the message recpient's EC key.</param> /// <param name="plaintextMessageAsByteArray">The message to encrypt.</param> public EcEncryptedMessageAesCbcHmacSha256(ECDiffieHellmanPublicKey recipientsEcPublicKey, byte[] plaintextMessageAsByteArray) { ECDiffieHellmanCng oneTimeEcKey = new ECDiffieHellmanCng(CngKey.Create(CngAlgorithm.ECDiffieHellmanP256, null, new CngKeyCreationParameters())); PublicOneTimeEcKey = oneTimeEcKey.PublicKey.ToByteArray(); byte[] sessionKey = oneTimeEcKey.DeriveKeyMaterial(recipientsEcPublicKey); EncryptedMessage = Encryption.EncryptAesCbc(plaintextMessageAsByteArray, sessionKey, addHmac: true); }
public byte[] GetPublicKey() { if (dh == null) { dh = new ECDiffieHellmanCng() { KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash, HashAlgorithm = CngAlgorithm.Sha256 }; } return dh.PublicKey.ToByteArray(); }
/// <summary> /// Decrypts the provided data. /// </summary> /// <param name="privateKey">The private key used for decryption.</param> /// <param name="publicKey">The public key used for decryption.</param> /// <param name="nonce">The nonce used for decryption.</param> /// <param name="encryptedData">The data to decrypt.</param> /// <returns>The decrypted data.</returns> public static byte[] Decrypt(ECDiffieHellmanCng privateKey, ECDiffieHellmanPublicKey publicKey, byte[] nonce, byte[] encryptedData) { try { Aes aes = DeriveKeyAndIv(privateKey, publicKey, nonce); return aes.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length); } catch (Exception E) { throw new DecryptionException(E.ToString()); } }
public Bob() { using (ECDiffieHellmanCng bob = new ECDiffieHellmanCng()) { bob.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; bob.HashAlgorithm = CngAlgorithm.Sha256; bobPublicKey = bob.PublicKey.ToByteArray(); bobKey = bob.DeriveKeyMaterial(CngKey.Import(Alice.alicePublicKey, CngKeyBlobFormat.EccPublicBlob)); } }
public static byte[] DeriveKeyMaterial(byte[] privateKey, byte[] otherPublicKey, CngAlgorithm hashAlgorithm) { #if Mono throw new NotSupportedException(); #else using (CngKey ck = CngKey.Import(privateKey, CngKeyBlobFormat.Pkcs8PrivateBlob)) using (ECDiffieHellmanCng ecdh = new ECDiffieHellmanCng(ck)) { ecdh.HashAlgorithm = hashAlgorithm; return ecdh.DeriveKeyMaterial(ECDiffieHellmanCngPublicKey.FromXmlString(Encoding.ASCII.GetString(otherPublicKey))); } #endif }
/// <summary> /// Creates an encrypted message /// </summary> /// <param name="recipientsEcPublicKey">The public portion of the message recpient's EC key.</param> /// <param name="plaintextMessageAsByteArray">The message to encrypt.</param> public EcEncryptedMessageAesCbcHmacSha256(ECDiffieHellmanPublicKey recipientsEcPublicKey, byte[] plaintextMessageAsByteArray) { byte[] sessionKey; using (CngKey oneTimeEcCngKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256)) { using (ECDiffieHellmanCng oneTimeEcKey = new ECDiffieHellmanCng(oneTimeEcCngKey)) { PublicOneTimeEcKey = oneTimeEcKey.PublicKey.ToByteArray(); sessionKey = oneTimeEcKey.DeriveKeyMaterial(recipientsEcPublicKey); } } EncryptedMessage = Encryption.EncryptAesCbc(plaintextMessageAsByteArray, sessionKey, addHmac: true); }
public override byte[] GetServerKeys(ProtocolVersion version) { _ecdhCng = new ECDiffieHellmanCng(256); UInt16 namedCurve = KeySizeToNamedCurve(256); byte[] ecPoint = Blob2Point(_ecdhCng.PublicKey.ToByteArray()); byte[] ret = new byte[4+ecPoint.Length]; ret[0] = 3; // ECCurveType.named_curve ret[1] = (byte) (namedCurve >> 8); ret[2] = (byte) (namedCurve); ret[3] = (byte) (ecPoint.Length); Buffer.BlockCopy(ecPoint, 0, ret, 4, ecPoint.Length); return ret; }
private static byte[] Generate256BitKey(CngKey ourPvtEcCngKey, X509Certificate2 theirCert) { if (ourPvtEcCngKey == null) throw new ArgumentNullException("ourPvtEcCngKey"); var ourEcDh = new ECDiffieHellmanCng(ourPvtEcCngKey) { KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash, HashAlgorithm = CngAlgorithm.Sha256 }; ECDiffieHellmanCngPublicKey theirEcDh = GetECDiffieHellmanCngPublicKey(theirCert); byte[] symKey = ourEcDh.DeriveKeyMaterial(theirEcDh); return symKey; }
/// <summary> /// Decrypt the message by providing the recipient's private EC key. /// </summary> /// <param name="recipientsPrivateEcKey">The private EC key matching the public key provided for encryption.</param> /// <returns>The decrypted message as a byte array</returns> public byte[] Decrypt(ECDiffieHellmanCng recipientsPrivateEcKey) { byte[] sessionKey; try { sessionKey = recipientsPrivateEcKey.DeriveKeyMaterial(CngKey.Import(PublicOneTimeEcKey, CngKeyBlobFormat.EccPublicBlob)); } catch (CryptographicException e) { throw new Exception("Failed to Decrypt log entry", e); } return Encryption.DecryptAescbc(EncryptedMessage, sessionKey, checkAndRemoveHmac: true); }
public Server(string ip, int port, string nickname, string username, string password) { Ip = ip; Port = port; Password = password; Username = username; Nickname = nickname; _status = 0; WinStatus = "Disconnected"; exch = new ECDiffieHellmanCng(256); exch.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; exch.HashAlgorithm = CngAlgorithm.Sha256; publicKey = exch.PublicKey.ToByteArray(); }
public MyServer(int port, string username, string password, MainWindow w) { try { exch = new ECDiffieHellmanCng(256); exch.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; exch.HashAlgorithm = CngAlgorithm.Sha256; publicKey = exch.PublicKey.ToByteArray(); this.username = username; this.password = password; this.Window = w; input = new Input(); mcb = new MyClipBoard(); localpt = new IPEndPoint(IPAddress.Any, port); /* Initializes the Listener */ myList = new TcpListener(localpt); uclient = new UdpClient(); uclient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); uclient.DontFragment = true; uclient.Client.Bind(localpt); /* Start Listening at the specified port */ myList.Start(); Console.WriteLine("The server is running at port 8001..."); Console.WriteLine("The local End point is :" + myList.LocalEndpoint); Console.WriteLine("Waiting for a connection....."); Thread t3 = new Thread(InputProcessing); t3.Start(); Thread t = new Thread(ClipBoardProcessing); //LOGIN AND CLIPBOARD PROCESSING t.SetApartmentState(ApartmentState.STA); t.Start(); } catch (SocketException se) { if (se.ErrorCode == 10048) { throw se; } Console.WriteLine(se.Message + " " + se.ErrorCode); } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary> /// 公開鍵と秘密鍵を作成して返す /// </summary> /// <param name="publicKey">作成された公開鍵</param> /// <param name="privateKey">作成された秘密鍵</param> public static void CreateKeys(out byte[] publicKey, out byte[] privateKey) { #if Mono throw new NotSupportedException(); #else CngKeyCreationParameters ckcp = new CngKeyCreationParameters(); ckcp.ExportPolicy = CngExportPolicies.AllowPlaintextExport; ckcp.KeyUsage = CngKeyUsages.KeyAgreement; using (CngKey ck = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521, null, ckcp)) using (ECDiffieHellmanCng ecdh = new ECDiffieHellmanCng(ck)) { publicKey = Encoding.ASCII.GetBytes(ecdh.ToXmlString(ECKeyXmlFormat.Rfc4050)); privateKey = ecdh.Key.Export(CngKeyBlobFormat.Pkcs8PrivateBlob); } #endif }
private static Aes DeriveKeyAndIv(ECDiffieHellmanCng privateKey, ECDiffieHellmanPublicKey publicKey, byte[] nonce) { privateKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; privateKey.HashAlgorithm = CngAlgorithm.Sha256; privateKey.SecretAppend = nonce; byte[] keyAndIv = privateKey.DeriveKeyMaterial(publicKey); byte[] key = new byte[16]; Array.Copy(keyAndIv, 0, key, 0, 16); byte[] iv = new byte[16]; Array.Copy(keyAndIv, 16, iv, 0, 16); Aes aes = new AesManaged(); aes.Key = key; aes.IV = iv; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; return aes; }
public static void Main(string[] args) { using (ECDiffieHellmanCng alice = new ECDiffieHellmanCng()) { //Establish DH shared secret alice.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; alice.HashAlgorithm = CngAlgorithm.Sha256; alicePublicKey = alice.PublicKey.ToByteArray(); Bob bob = new Bob(); CngKey k = CngKey.Import(bob.bobPublicKey, CngKeyBlobFormat.EccPublicBlob); byte[] aliceKey = alice.DeriveKeyMaterial(k); //share public key info byte[] encryptedMessage = null; byte[] iv = null; Send(aliceKey, "RSA Public key", out encryptedMessage, out iv); bob.Receive(encryptedMessage, iv); } }
private async Task<byte[]> AliceSendsDataAsync(string message) { WriteLine($"Alice sends message: {message}"); byte[] rawData = Encoding.UTF8.GetBytes(message); byte[] encryptedData = null; using (var aliceAlgorithm = new ECDiffieHellmanCng(_aliceKey)) using (CngKey bobPubKey = CngKey.Import(_bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey); WriteLine("Alice creates this symmetric key with " + $"Bobs public key information: { Convert.ToBase64String(symmKey)}"); using (var aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (var ms = new MemoryStream()) { // create CryptoStream and encrypt data to send using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { // write initialization vector not encrypted await ms.WriteAsync(aes.IV, 0, aes.IV.Length); await cs.WriteAsync(rawData, 0, rawData.Length); } encryptedData = ms.ToArray(); } aes.Clear(); } } WriteLine($"Alice: message is encrypted: {Convert.ToBase64String(encryptedData)}"); ; WriteLine(); return encryptedData; }
private void Encrypt() { if (string.IsNullOrEmpty(DataTextBox.Text)) { EncryptedDataTextBox.Text = ""; return; } EncryptedDataTextBox.Text = "Encrypting..."; try { // Import parameters from BLOB. var keyBlob = System.Convert.FromBase64String(PrivateKeyTextBox.Text); var privateKey = CngKey.Import(keyBlob, CngKeyBlobFormat.EccPrivateBlob); var ecdh = new System.Security.Cryptography.ECDiffieHellmanCng(privateKey); // Encrypt the passed byte array. var otherPartyKeyBlob = System.Convert.FromBase64String(OtherPublicKeyTextBox.Text); var otherPartyPublicKey = CngKey.Import(otherPartyKeyBlob, CngKeyBlobFormat.EccPublicBlob); var symetricKey = ecdh.DeriveKeyMaterial(otherPartyPublicKey); var symetricKeyBase64 = ToBase64(symetricKey); var dataBytes = System.Text.Encoding.UTF8.GetBytes(DataTextBox.Text); // Append random prefix. dataBytes = AddRandom(dataBytes); var encryptedBytes = Encrypt(symetricKey, dataBytes); var encryptedBase64 = ToBase64(encryptedBytes); // Display the encrypted data. EncryptedDataTextBox.Foreground = System.Windows.SystemColors.ControlTextBrush; EncryptedDataTextBox.Text = encryptedBase64; } catch (Exception ex) { EncryptedDataTextBox.Foreground = new SolidColorBrush(System.Windows.Media.Colors.DarkRed); EncryptedDataTextBox.Text = ex.Message; } }
private void Decrypt() { if (string.IsNullOrEmpty(OtherEncryptedDataTextBox.Text)) { OtherDecryptedTextBox.Text = ""; return; } OtherDecryptedTextBox.Text = "Decrypting..."; try { var keyBlob = System.Convert.FromBase64String(PrivateKeyTextBox.Text); var privateKey = CngKey.Import(keyBlob, CngKeyBlobFormat.EccPrivateBlob); var ecdh = new System.Security.Cryptography.ECDiffieHellmanCng(privateKey); // Other key var otherPartyKeyBlob = System.Convert.FromBase64String(OtherPublicKeyTextBox.Text); var otherPartyPublicKey = CngKey.Import(otherPartyKeyBlob, CngKeyBlobFormat.EccPublicBlob); // Decrypt the passed byte array and specify OAEP padding. var symetricKey = ecdh.DeriveKeyMaterial(otherPartyPublicKey); var symetricKeyBase64 = ToBase64(symetricKey); var encryptedBytes = System.Convert.FromBase64String(OtherEncryptedDataTextBox.Text); var decryptedBytes = Decrypt(symetricKey, encryptedBytes); // Remove random prefix. decryptedBytes = RemoveRandom(decryptedBytes); var decryptedData = System.Text.Encoding.UTF8.GetString(decryptedBytes); OtherDecryptedTextBox.Foreground = System.Windows.SystemColors.ControlTextBrush; OtherDecryptedTextBox.Text = decryptedData; } catch (Exception ex) { OtherDecryptedTextBox.Foreground = new SolidColorBrush(System.Windows.Media.Colors.DarkRed); OtherDecryptedTextBox.Text = ex.Message; } }
/// <summary> /// Get a handle to the secret agreement generated between two parties /// </summary> public SafeNCryptSecretHandle DeriveSecretAgreementHandle(ECDiffieHellmanPublicKey otherPartyPublicKey) { if (otherPartyPublicKey == null) { throw new ArgumentNullException(nameof(otherPartyPublicKey)); } if (otherPartyPublicKey is ECDiffieHellmanCngPublicKey otherKey) { using (CngKey importedKey = otherKey.Import()) { return(DeriveSecretAgreementHandle(importedKey)); } } ECParameters otherPartyParameters = otherPartyPublicKey.ExportParameters(); using (ECDiffieHellmanCng otherPartyCng = (ECDiffieHellmanCng)Create(otherPartyParameters)) using (otherKey = (ECDiffieHellmanCngPublicKey)otherPartyCng.PublicKey) using (CngKey importedKey = otherKey.Import()) { return(DeriveSecretAgreementHandle(importedKey)); } }
/// <summary> /// Stop this instance. /// </summary> public void Stop() { if (this.client != null) { if (this.cngECC != null) { this.cngECC.Clear(); this.cngECC = null; } this.client.Close(); this.client = null; } }
public Client(Server parent, TcpClient client) { this.server = parent; this.client = client; this.cngECC = new ECDiffieHellmanCng(parent.GetKey()); (new System.Random()).NextBytes(this.rsaSecretKey); this.cipher = CipherUtilities.GetCipher("AES/CTR/NoPadding"); }
/// <summary> /// Both parties are static and authenticated. /// </summary> public static byte[] GetSharedDhmSecret(this CngKey privateDhmKey, CngKey publicDhmKey, byte[] contextAppend = null, byte[] contextPrepend = null) { using (var ecdh = new ECDiffieHellmanCng(privateDhmKey) { HashAlgorithm = CngAlgorithm.Sha384, SecretAppend = contextAppend, SecretPrepend = contextPrepend }) return ecdh.DeriveKeyMaterial(publicDhmKey); }
/// <summary>公開鍵・暗号化サービスプロバイダの生成</summary> /// <returns>公開鍵・暗号化サービスプロバイダ</returns> private AsymmetricAlgorithm CreateAsymmetricAlgorithmServiceProvider() { // 公開鍵・暗号化サービスプロバイダ AsymmetricAlgorithm aa = null; if (this.comboBox4.SelectedItem.ToString() == "DSACryptoServiceProvider") { // DSACryptoServiceProviderサービスプロバイダ aa = new DSACryptoServiceProvider(); } else if (this.comboBox4.SelectedItem.ToString() == "ECDiffieHellmanCng") { // ECDiffieHellmanCngサービスプロバイダ aa = new ECDiffieHellmanCng(); } else if (this.comboBox4.SelectedItem.ToString() == "ECDsaCng") { // ECDsaCngサービスプロバイダ aa = new ECDsaCng(); } else if (this.comboBox4.SelectedItem.ToString() == "RSACryptoServiceProvider") { // RSACryptoServiceProviderサービスプロバイダ aa = new RSACryptoServiceProvider(); } return aa; }