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); }
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; }
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; }
public static string Request(string requestParams, string devKey, string devIV, string devID) { // Create an unencrypted request as an array of bytes byte[] request = UTF8Encoding.UTF8.GetBytes(requestParams); byte[] key = UTF8Encoding.UTF8.GetBytes(devKey); byte[] iv = UTF8Encoding.UTF8.GetBytes(devIV); AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); aes.Key = key; aes.IV = iv; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.Zeros; // Get the transformer from the AES Encryptor ICryptoTransform cTransform = aes.CreateEncryptor(); // Use the transformer to encrypt our request byte[] result = cTransform.TransformFinalBlock(request, 0, request.Length); aes.Clear(); // Encode to base64 string encryptedRequest = Convert.ToBase64String(result, 0, result.Length); // Send request to API string requestUri = "http://api.blackoutrugby.com/?d=" + devID + "&er=" + encryptedRequest; string xmlResponse = getWebResponse(requestUri); return XmlToJson(xmlResponse); }
/// <summary> /// 解密字节数组 /// </summary> /// <param name="inputData">要解密的字节数据</param> /// <param name="password">密码</param> /// <returns></returns> public static byte[] Decrypt(byte[] inputData, string password) { AesCryptoServiceProvider aes = new AesCryptoServiceProvider { Key = GetKeyArray(password), Mode = cipherMode, Padding = paddingMode }; var transform = aes.CreateDecryptor(); byte[] data = null; try { data = transform.TransformFinalBlock(inputData, 0, inputData.Length); } catch { return null; } aes.Clear(); return data; }
/// <summary> /// 解密字节数组 /// </summary> /// <param name="inputData">要解密的字节数据</param> /// <param name="password">密码</param> /// <returns></returns> public static byte[] Decrypt(byte[] inputData, string password) { AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); aes.Key = GetKeyArray(password); aes.Mode = AesCipherMode; aes.Padding = AesPaddingMode; ICryptoTransform transform = aes.CreateDecryptor(); byte[] data = transform.TransformFinalBlock(inputData, 0, inputData.Length); aes.Clear(); return data; }
/// <summary> /// 加密一个字符串 /// </summary> /// <param name="plainText">要加密的字符串</param> /// <param name="key">用于加密的密钥</param> /// <returns>加密后的BASE64字符串</returns> public override string Encrypt(string plainText, string key) { var inputData = System.Text.UTF8Encoding.UTF8.GetBytes(plainText); AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); aes.Key = System.Text.UTF8Encoding.UTF8.GetBytes(key); aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; ICryptoTransform transform = aes.CreateEncryptor(); byte[] data = transform.TransformFinalBlock(inputData, 0, inputData.Length); aes.Clear(); return Convert.ToBase64String(data); }
public TestSymmetricKeyProvider() { byte[] key; byte[] iv; using (var provider = new AesCryptoServiceProvider()) { provider.GenerateIV(); provider.GenerateKey(); key = provider.Key; iv = provider.IV; provider.Clear(); } _key = new TestSymmetricKey(key, iv); }
/// <summary> /// 解密一段BASE64字符串 /// </summary> /// <param name="base64String">需要解密的字符串</param> /// <param name="key">解密用的密钥</param> /// <returns>解密后的明文字符串</returns> public override String Decrypt(string base64String, string key) { var inputData = Convert.FromBase64String(base64String); AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); aes.Key = System.Text.UTF8Encoding.UTF8.GetBytes(key); aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; ICryptoTransform transform = aes.CreateDecryptor(); byte[] data = null; try { data = transform.TransformFinalBlock(inputData, 0, inputData.Length); } catch { return null; } aes.Clear(); return System.Text.UTF8Encoding.UTF8.GetString(data); }
public static string DecryptAES(string hash, string key, bool hashKey = true) { if (hash == null || key == null) return null; var keyArray = HexStringToByteArray(hashKey ? HashMD5(key) : key); var toEncryptArray = HexStringToByteArray(hash); var aes = new AesCryptoServiceProvider { Key = keyArray, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; var cTransform = aes.CreateDecryptor(); var resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); aes.Clear(); return Encoding.UTF8.GetString(resultArray); }
public static string EncryptAES(string phrase, string key, bool hashKey = true) { if (phrase == null || key == null) return null; var keyArray = HexStringToByteArray(hashKey ? HashMD5(key) : key); var toEncryptArray = Encoding.UTF8.GetBytes(phrase); byte[] result; using (var aes = new AesCryptoServiceProvider { Key = keyArray, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }) { var cTransform = aes.CreateEncryptor(); result = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); aes.Clear(); } return ByteArrayToHexString(result); }
public static string SymmetricDecrypt(this string cipherText, string key, SymmetricAlgorithm algorithm) { if (string.IsNullOrWhiteSpace(cipherText)) throw new ArgumentNullException("cipherText", "Cannot decrypt an empty cipher text."); if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException("key", "Cannot decrypt with an empty key."); byte[] keyBuffer = Convert.FromBase64String(key.Hash(HashAlgorithm.MD5)); byte[] cipherTextBuffer = Convert.FromBase64String(cipherText); System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm; switch (algorithm) { // case SymmetricAlgorithmEnum.DES: // symmetricAlgorithm = new DESCryptoServiceProvider(); // break; case SymmetricAlgorithm.RC2: symmetricAlgorithm = new RC2CryptoServiceProvider(); break; case SymmetricAlgorithm.TripleDES: symmetricAlgorithm = new TripleDESCryptoServiceProvider(); break; case SymmetricAlgorithm.Aes: default: symmetricAlgorithm = new AesCryptoServiceProvider(); break; } symmetricAlgorithm.Key = keyBuffer; symmetricAlgorithm.Mode = CipherMode.ECB; // The legacy code did not indicate padding - not sure if this will effect the ouput much but we probably shouldn't change it // symmetricAlgorithm.Padding = PaddingMode.PKCS7; var decryptor = symmetricAlgorithm.CreateDecryptor(); byte[] plainTextBuffer = decryptor.TransformFinalBlock(cipherTextBuffer, 0, cipherTextBuffer.Length); symmetricAlgorithm.Clear(); return Encoding.Default.GetString(plainTextBuffer); }
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; }
public TestSymmetricKeyProvider(params string[] ids) { _keys = new Dictionary<string, TestSymmetricKey>(); foreach (var id in ids.Concat(new[] {"default"}).Distinct()) { byte[] key; byte[] iv; using (var provider = new AesCryptoServiceProvider()) { provider.GenerateIV(); provider.GenerateKey(); key = provider.Key; iv = provider.IV; provider.Clear(); } _keys.Add(id, new TestSymmetricKey(key, iv)); } }
private static void BobReceivesData(byte[] encryptedData) { Console.WriteLine("Bob receives encrypted data"); 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 bobAlgro = new ECDiffieHellmanCng(bobKey)) { using(CngKey alicePubKey = CngKey.Import(alicePubKeyBlod, CngKeyBlobFormat.GenericPublicBlob)) { byte[] symmKey = bobAlgro.DeriveKeyMaterial(alicePubKey); Console.WriteLine("Bob creates this symmetric key with ALices public key information : {0}", 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(encryptedData, nBytes, encryptedData.Length - nBytes); cs.Close(); rawData = ms.ToArray(); Console.WriteLine("Bob decrypts message to {0}", Encoding.UTF8.GetString(rawData)); } } } } aes.Clear(); }
/// <summary> /// Encrypts the specified data using a 128-bit cipher. The key can be any length. /// </summary> /// <param name="Data">The data to be encrypted.</param> /// <param name="Key">The key used to encrypt the data.</param> /// <returns>A byte array containing the encoded data.</returns> public static byte[] Encrypt128Byte(string Data, byte[] Key) { AesCryptoServiceProvider AES = null; var MS = new MemoryStream(); CryptoStream CS = null; try { //Get the IV and length corrected Key. KeyData KeyData = GenerateKeyIV128(Key); //Create the AES crytpograhy object. AES = new AesCryptoServiceProvider { BlockSize = 128, KeySize = 128, Key = KeyData.Key, IV = KeyData.IV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }; CS = new CryptoStream(MS, AES.CreateEncryptor(), CryptoStreamMode.Write); CS.Write(System.Text.Encoding.Default.GetBytes(Data), 0, System.Text.Encoding.Default.GetByteCount(Data)); CS.FlushFinalBlock(); return MS.ToArray(); } finally { if (AES != null) AES.Clear(); if (CS != null) CS.Dispose(); MS.Dispose(); } }
/// <summary> /// Encrypts the specified data using a 128-bit cipher. The key can be any length. /// </summary> /// <param name="Data">The data to be encrypted. Must be UTF8.</param> /// <param name="Key">The key used to encrypt the data.</param> /// <returns>A Base-64 string containing the encoded data.</returns> public static string Encrypt128Base64Secure(System.Security.SecureString Data, byte[] Key) { AesCryptoServiceProvider AES = null; var MS = new MemoryStream(); CryptoStream CS = null; try { //Get the IV and length corrected Key. KeyData KeyData = GenerateKeyIV128(Key); //Create the AES crytpograhy object. AES = new AesCryptoServiceProvider { BlockSize = 128, KeySize = 128, Key = KeyData.Key, IV = KeyData.IV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }; CS = new CryptoStream(MS, AES.CreateEncryptor(), CryptoStreamMode.Write); byte[] D = System.Text.Encoding.UTF8.GetBytes(ConvertToUnsecureString(Data)); CS.Write(D, 0, D.Length); CS.FlushFinalBlock(); return Convert.ToBase64String(MS.ToArray()); } finally { if (AES != null) AES.Clear(); if (CS != null) CS.Dispose(); MS.Dispose(); } }
/// <summary> /// Encrypts the specified data using a 128-bit cipher. The key can be any length. /// </summary> /// <param name="Data">The data to be encrypted.</param> /// <param name="Key">The key used to encrypt the data.</param> /// <returns>A Base-64 string containing the encoded data.</returns> public static string Encrypt128Base64(Stream Data, byte[] Key) { AesCryptoServiceProvider AES = null; var MS = new MemoryStream(); CryptoStream CS = null; BinaryReader DR = null; try { //Get the IV and length corrected Key. KeyData KeyData = GenerateKeyIV128(Key); //Create the AES crytpograhy object. AES = new AesCryptoServiceProvider { BlockSize = 128, KeySize = 128, Key = KeyData.Key, IV = KeyData.IV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }; CS = new CryptoStream(MS, AES.CreateEncryptor(), CryptoStreamMode.Write); DR = new BinaryReader(Data); var D = new byte[DR.BaseStream.Length]; DR.Read(D, 0, (int)DR.BaseStream.Length - 1); CS.Write(D, 0, D.Length); CS.FlushFinalBlock(); return Convert.ToBase64String(MS.ToArray()); } finally { if (AES != null) AES.Clear(); if (CS != null) CS.Dispose(); MS.Dispose(); if (DR != null) DR.Close(); } }
/// <summary> /// Decrypts the specified data using a 256-bit cipher. The key can be any length. /// </summary> /// <param name="Data">The data to be decrypted. Will be converted to UTF8.</param> /// <param name="Key">The key used to decrypt the data.</param> /// <returns>A string containing the decoded data.</returns> public static System.Security.SecureString Decrypt256StringSecure(Stream Data, byte[] Key) { AesCryptoServiceProvider AES = null; CryptoStream CS = null; StreamReader DS = null; try { //Get the IV and length corrected Key. KeyData KeyData = GenerateKeyIV128(Key); //Create the AES crytpograhy object. AES = new AesCryptoServiceProvider { BlockSize = 256, KeySize = 256, Key = KeyData.Key, IV = KeyData.IV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }; CS = new CryptoStream(Data, AES.CreateDecryptor(), CryptoStreamMode.Read); DS = new StreamReader(CS); var ss = new System.Security.SecureString(); while (DS.EndOfStream == false) ss.AppendChar(Convert.ToChar(DS.Read())); ss.MakeReadOnly(); return ss; } finally { if (AES != null) AES.Clear(); if (CS != null) CS.Dispose(); if (DS != null) DS.Dispose(); } }
/// <summary> /// Decrypts the specified data using a 128-bit cipher. The key can be any length. /// </summary> /// <param name="Data">The data to be decrypted.</param> /// <param name="Key">The key used to decrypt the data.</param> /// <returns>A string containing the decoded data.</returns> public static byte[] Decrypt128Byte(byte[] Data, byte[] Key) { AesCryptoServiceProvider AES = null; var MS = new MemoryStream(Data); CryptoStream CS = null; StreamReader DS = null; try { //Get the IV and length corrected Key. KeyData KeyData = GenerateKeyIV128(Key); //Create the AES crytpograhy object. AES = new AesCryptoServiceProvider { BlockSize = 128, KeySize = 128, Key = KeyData.Key, IV = KeyData.IV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }; CS = new CryptoStream(MS, AES.CreateDecryptor(), CryptoStreamMode.Read); DS = new StreamReader(CS); var D = new byte[CS.Length]; CS.Read(D, 0, (int)CS.Length - 1); return D; } finally { if (AES != null) AES.Clear(); MS.Dispose(); if (CS != null) CS.Dispose(); if (DS != null) DS.Dispose(); } }
/// <summary> /// Decrypts the specified data using a 256-bit cipher. The key can be any length. /// </summary> /// <param name="Data">The data to be decrypted.</param> /// <param name="Key">The key used to decrypt the data.</param> /// <returns>A string containing the decoded data.</returns> public static string Decrypt256String(Stream Data, byte[] Key) { AesCryptoServiceProvider AES = null; CryptoStream CS = null; StreamReader DS = null; try { //Get the IV and length corrected Key. KeyData KeyData = GenerateKeyIV128(Key); //Create the AES crytpograhy object. AES = new AesCryptoServiceProvider { BlockSize = 256, KeySize = 256, Key = KeyData.Key, IV = KeyData.IV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }; CS = new CryptoStream(Data, AES.CreateDecryptor(), CryptoStreamMode.Read); DS = new StreamReader(CS); return DS.ReadToEnd(); } finally { if (AES != null) AES.Clear(); if (CS != null) CS.Dispose(); if (DS != null) DS.Dispose(); } }
/// <summary> /// Encrypts the specified data using a 256-bit cipher. The key can be any length. /// </summary> /// <param name="Data">The data to be encrypted.</param> /// <param name="Key">The key used to encrypt the data.</param> /// <returns>A stream containing the encoded data.</returns> public static Stream Encrypt256Stream(byte[] Data, byte[] Key) { AesCryptoServiceProvider AES = null; var MS = new MemoryStream(); CryptoStream CS = null; try { //Get the IV and length corrected Key. KeyData KeyData = GenerateKeyIV128(Key); //Create the AES crytpograhy object. AES = new AesCryptoServiceProvider { BlockSize = 256, KeySize = 256, Key = KeyData.Key, IV = KeyData.IV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }; CS = new CryptoStream(MS, AES.CreateEncryptor(), CryptoStreamMode.Write); CS.Write(Data, 0, Data.Length); CS.FlushFinalBlock(); return MS; } finally { if (AES != null) AES.Clear(); if (CS != null) CS.Dispose(); MS.Dispose(); } }
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; }
public static string Decrypt(string orgidata, byte[] key = null, CryptoStringFormat format = CryptoStringFormat.Base64, string iv = null) { if (orgidata == null) { return null; } using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) { key = GetCheckKey(key); aes.Key = key == null ? appkeykey : key; byte[] _iv = new byte[aes.BlockSize / 8]; if (string.IsNullOrEmpty(iv)) { Array.Copy(aes.Key, 0, _iv, 0, _iv.Length); } else { byte[] pIV = Encoding.GetBytes(iv); if (pIV.Length == _iv.Length) { _iv = pIV; } else if (pIV.Length > _iv.Length) { Array.Copy(pIV, 0, _iv, 0, _iv.Length); } else if (pIV.Length < _iv.Length) { Array.Copy(pIV, 0, _iv, 0, pIV.Length); for (int i = pIV.Length; i < _iv.Length; i++) { _iv[i] = 48; } } } aes.Mode = cipherMode; aes.Padding = paddingMode; aes.IV = _iv; using (ICryptoTransform transform = aes.CreateDecryptor()) { byte[] data = null; try { byte[] orgi = null; switch (format) { case CryptoStringFormat.Base64: orgi = Convert.FromBase64String(orgidata); break; case CryptoStringFormat.Encoding: orgi = Encoding.GetBytes(orgidata); break; } data = transform.TransformFinalBlock(orgi, 0, orgi.Length); } catch (Exception ex) { Log.WriteException(ex); return null; } aes.Clear(); if (data != null) return Encoding.GetString(data); return null; } } }
private async Task BobReceivesDataAsync(byte[] encryptedData) { WriteLine("Bob receives encrypted data"); 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(_bobKey)) using (CngKey alicePubKey = CngKey.Import(_alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey); WriteLine("Bob creates this symmetric key with " + $"Alices public key information: {Convert.ToBase64String(symmKey)}"); aes.Key = symmKey; aes.IV = iv; using (ICryptoTransform decryptor = aes.CreateDecryptor()) using (MemoryStream ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write)) { await cs.WriteAsync(encryptedData, nBytes, encryptedData.Length - nBytes); } rawData = ms.ToArray(); WriteLine($"Bob decrypts message to: {Encoding.UTF8.GetString(rawData)}"); } aes.Clear(); } }
public static string SymmetricEncrypt(this string plaintext, string key, SymmetricAlgorithm algorithm) { if (string.IsNullOrEmpty(plaintext)) throw new ArgumentNullException("plaintext", "Cannot encrypt an empty string."); if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key", "Cannot encrypt with an empty key."); byte[] keyBuffer = Convert.FromBase64String(key.Hash(HashAlgorithm.MD5)); byte[] plainTextBuffer = UTF8Encoding.UTF8.GetBytes(plaintext); System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm; switch (algorithm) { //case SymmetricAlgorithm.DES: // symmetricAlgorithm = new DESCryptoServiceProvider(); // break; case SymmetricAlgorithm.RC2: symmetricAlgorithm = new RC2CryptoServiceProvider(); break; case SymmetricAlgorithm.TripleDES: symmetricAlgorithm = new TripleDESCryptoServiceProvider(); break; case SymmetricAlgorithm.Aes: default: symmetricAlgorithm = new AesCryptoServiceProvider(); break; } symmetricAlgorithm.Key = keyBuffer; symmetricAlgorithm.Mode = CipherMode.ECB; symmetricAlgorithm.Padding = PaddingMode.PKCS7; var encryptor = symmetricAlgorithm.CreateEncryptor(); byte[] cipherBuffer = encryptor.TransformFinalBlock(plainTextBuffer, 0, plainTextBuffer.Length); symmetricAlgorithm.Clear(); return Convert.ToBase64String(cipherBuffer); }
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(); }