protected override void Dispose(Boolean disposing) { if (disposing) { Aes.Dispose(); } }
protected override void OnDispose(bool disposing) { if (disposing) { _key.Dispose(); } }
/// <summary>Instantly dispose of all resources.</summary> public void Dispose() { Disposed = true; Aes.Dispose(); Allocator.ReturnKey(ref Key); Allocator.ReturnIV(ref IV); }
/// <summary> /// AES加密 /// </summary> /// <param name="value">待加密字段</param> /// <param name="keyVal">密钥值(最短:16位长度,过长也只取16位)</param> /// <param name="ivVal">加密辅助向量(最短:16位长度,过长也只取16位)</param> /// <returns></returns> public static string AesStr(this string value, string keyVal, string ivVal) { if (value == null) { throw new ArgumentNullException("未将对象引用设置到对象的实例。"); } var encoding = Encoding.UTF8; byte[] btKey = keyVal.FormatByte(encoding); byte[] btIv = ivVal.FormatByte(encoding); byte[] byteArray = encoding.GetBytes(value); string encrypt; Aes aes = Aes.Create(); //Rijndael aes = Rijndael.Create(); using (MemoryStream mStream = new MemoryStream()) { using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(btKey, btIv), CryptoStreamMode.Write)) { cStream.Write(byteArray, 0, byteArray.Length); cStream.FlushFinalBlock(); encrypt = Convert.ToBase64String(mStream.ToArray()); } } aes.Dispose(); return(encrypt); }
protected override void Dispose(bool disposing) { if (disposing) { _impl.Dispose(); } }
private bool disposedValue = false; // To detect redundant calls protected override void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { try { topStream.Dispose(); // This call will flush and dispose all chained streams. } catch (CryptographicException) { topStream.Dispose(); throw; } finally { transform.Dispose(); csp.Dispose(); sha.Dispose(); } } disposedValue = true; } }
/// <summary> /// Close the stream. /// </summary> public override void Close() { TraceOutput("Close {0:X8}", this.GetHashCode()); // In the degenerate case, no bytes have been written to the // stream at all. Need to check here, and NOT emit the // final block if Write has not been called. if (_pendingCount > 0) { WriteTransformFinalBlock(); _s.Write(_PendingWriteBlock, 0, _pendingCount); _totalBytesXferred += _pendingCount; _pendingCount = 0; } _s.Close(); _xform.Dispose(); _aesCipher.Dispose(); #if WANT_TRACE untransformed.Close(); transformed.Close(); Console.WriteLine("\nuntransformed bytestream is in {0}", traceFileUntransformed); Console.WriteLine("\ntransformed bytestream is in {0}", traceFileTransformed); #endif TraceOutput("-------------------------------------------------------"); }
public void Dispose() { m_Disposed = true; m_Encryptor.Dispose(); m_Decryptor.Dispose(); m_Aes.Dispose(); m_EncryptHMAC.Dispose(); }
public void Dispose() { if (_aes != null) { _aes.Dispose(); _aes = null; } }
public void Dispose() { if (aes != null) { aes.Dispose(); aes = null; } }
/// <summary> /// Decrypt the given string. Assumes the string was encrypted using /// EncryptStringAES(), using an identical sharedSecret. /// </summary> /// <param name="cipherText">The text to decrypt.</param> /// <param name="sharedSecret">A password used to generate a key for decryption.</param> public static string DecryptStringAES(string cipherText, string sharedSecret) { if (_salt == null) { throw new ArgumentNullException(nameof(_salt)); } if (string.IsNullOrEmpty(cipherText)) { throw new ArgumentNullException(nameof(cipherText)); } if (string.IsNullOrEmpty(sharedSecret)) { throw new ArgumentNullException(nameof(sharedSecret)); } // Declare the RijndaelManaged object // used to decrypt the data. Aes aesAlg = Aes.Create(); // Declare the string used to hold // the decrypted text. string plaintext = null; try { // generate the key from the shared secret and the salt Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); // Create the streams used for decryption. byte[] bytes = Convert.FromBase64String(cipherText); using (MemoryStream msDecrypt = new MemoryStream(bytes)) { // Create a RijndaelManaged object // with the specified key and IV. aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); // Get the initialization vector from the encrypted stream aesAlg.IV = ReadByteArray(msDecrypt); // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } } } finally { // Clear the RijndaelManaged object. aesAlg?.Dispose(); } return(plaintext); }
protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _aesContext.Dispose(); } }
public static string DecryptString(string cipherText, byte[] salt, string sharedSecret) { if (string.IsNullOrEmpty(cipherText)) { throw new ArgumentNullException("cipherText"); } if (string.IsNullOrEmpty(sharedSecret)) { throw new ArgumentNullException("sharedSecret"); } // Declare the RijndaelManaged object // used to decrypt the data. Aes aes = null; // Declare the string used to hold // the decrypted text. string plaintext = null; try { // generate the key from the shared secret and the salt var key = new Rfc2898DeriveBytes(sharedSecret, salt); // Create a RijndaelManaged object // with the specified key and IV. aes = Aes.Create(); aes.Key = key.GetBytes(aes.KeySize / 8); aes.IV = key.GetBytes(aes.BlockSize / 8); // Create a decrytor to perform the stream transform. var decryptor = aes.CreateDecryptor(aes.Key, aes.IV); // Create the streams used for decryption. byte[] bytes = Convert.FromBase64String(cipherText); using (var msDecrypt = new MemoryStream(bytes)) { using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (var srDecrypt = new StreamReader(csDecrypt)) // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } } } finally { // Clear the RijndaelManaged object. if (aes != null) { aes.Dispose(); } } return(plaintext); }
protected virtual void Dispose(bool disposing) { if (disposing) { _aes?.Dispose(); _diffieHellman?.Dispose(); } }
public void Dispose() { if (disposed) { return; } aes.Dispose(); disposed = true; }
public void Dispose() { if (_publicKeyTaskInitialized && _publicKeyTask.IsCompleted) { _publicKeyTask.Result.Dispose(); } _aes?.Dispose(); }
public void Dispose() { if (!m_disposed) { m_aes.Dispose(); m_md5.Dispose(); m_disposed = true; } }
public void Disconnect() { if (AesManaged != null) { AesManaged.Dispose(); } this.Hash = null; }
public override void Dispose(bool disposing) { if (disposing) { _aes.Dispose(); } base.Dispose(disposing); }
/// <summary> /// Encrypt the given string using AES. The string can be decrypted using /// DecryptStringAES(). The sharedSecret parameters must match. /// </summary> /// <param name="plainText">The text to encrypt.</param> /// <param name="sharedSecret">A password used to generate a key for encryption.</param> public static string EncryptStringAES(string plainText, string sharedSecret) { if (_salt == null) { throw new ArgumentNullException(nameof(_salt)); } if (string.IsNullOrEmpty(plainText)) { throw new ArgumentNullException(nameof(plainText)); } if (string.IsNullOrEmpty(sharedSecret)) { throw new ArgumentNullException(nameof(sharedSecret)); } string outStr = null; // Encrypted string to return Aes aesAlg = Aes.Create();; // RijndaelManaged object used to encrypt the data. try { // generate the key from the shared secret and the salt Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); // Create a RijndaelManaged object //aesAlg = new RijndaelManaged(); aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); // Create a decryptor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. using (MemoryStream msEncrypt = new MemoryStream()) { // prepend the IV msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int)); msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length); using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(plainText); } } outStr = Convert.ToBase64String(msEncrypt.ToArray()); } } finally { // Clear the RijndaelManaged object. aesAlg?.Dispose(); } // Return the encrypted bytes from the memory stream. return(outStr); }
/// <summary> /// Criptografa dados com a cifra AES /// </summary> /// <param name="PlainText">O texto claro a ser criptografado</param> /// <param name="Key">A chave secreta responsável pela encriptação</param> /// <param name="IV">Vetor de inicialização do AES/CBC mode</param> /// <returns></returns> public static byte[] Encrypt(string PlainText, byte[] Key, byte[] IV) { byte[] CipherText; //Verifica possíveis erros try { //Inicia a instância do AES using (Aes AES256 = Aes.Create()) { AES256.Key = Key; AES256.IV = IV; //Inicia a encriptação AES passando a chave e o IV ICryptoTransform crypto = AES256.CreateEncryptor(AES256.Key, AES256.IV); //Armazena espaço na memória para um texto cifrado using (var memory = new MemoryStream()) { //Indica a operação criptografica a ser feita e o tipo de fluxo using (var cryptoStream = new CryptoStream(memory, crypto, CryptoStreamMode.Write)) { //Responsável por escrever o texto cifrado no buffer using (var writer = new StreamWriter(cryptoStream)) { //Escreve o texto cifrado writer.Write(PlainText); writer.Close(); } //Envia todos os bytes cifrados ao array de bytes CipherText = memory.ToArray(); cryptoStream.Close(); } memory.Close(); } //Fecha todo o fluxo criptográfico AES256.Dispose(); } } catch (CryptographicException ex) { MessageBox.Show("Erro de criptografia: " + ex.Message, "Erro criptográfico!", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } //Retorna o texto cifrado return(CipherText); }
protected virtual void Dispose(bool disposing) { if (disposing) { if (_aes != null) { _aes.Dispose(); _aes = null; } } }
public static string EncryptString(string plainText, byte[] salt, string sharedSecret) { if (string.IsNullOrEmpty(plainText)) { throw new ArgumentNullException("plainText"); } if (string.IsNullOrEmpty(sharedSecret)) { throw new ArgumentNullException("sharedSecret"); } // Encrypted string to return string outStr = null; // Object used to encrypt data Aes aes = null; try { // Generate key from shared secret and salt var key = new Rfc2898DeriveBytes(sharedSecret, salt); aes = Aes.Create(); aes.Key = key.GetBytes(aes.KeySize / 8); aes.IV = key.GetBytes(aes.BlockSize / 8); var encryptor = aes.CreateEncryptor(aes.Key, aes.IV); // Create the streams used for encryption. using (var msEncrypt = new MemoryStream()) { using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (var swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(plainText); } } outStr = Convert.ToBase64String(msEncrypt.ToArray()); } } finally { // Clear the RijndaelManaged object. if (aes != null) { aes.Dispose(); } } // Return the encrypted bytes from the memory stream. return(outStr); }
/// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"> /// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only /// unmanaged resources. /// </param> protected override void DisposeResources(bool disposing) { if (!disposing) { return; } _encryptor?.Dispose(); _dh?.Dispose(); }
protected override void Dispose(bool disposing) { if (disposing) { #if !OS_WINDOWS _impl.Dispose(); #else _impl.Clear(); #endif } }
protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { aes.Dispose(); } DisposeHelper.OnDispose <AESCryptoProvider>(disposing); disposed = true; } }
protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { _aes.Dispose(); } _disposedValue = true; } }
/// <summary> /// Decrypt some encrypted text with a key and salt /// </summary> /// <param name="encryptionKey">Encryption Key</param> /// <param name="encryptionSalt">Encryption Salt</param> /// <param name="encryptedText">Encrypted string</param> /// <returns>Decrypted string</returns> private string Decrypt(string encryptionKey, string encryptionSalt, string encryptedText) { string retVal = string.Empty; if (!string.IsNullOrEmpty(encryptedText)) { // Declare the RijndaelManaged object // used to encrypt the data. // Create a RijndaelManaged object // with the specified key and IV. using (Aes aesAlg = Aes.Create()) { try { byte[] encryptedTextBytes = Convert.FromBase64String(encryptedText); byte[] passwordSaltBytes = Encoding.UTF8.GetBytes(encryptionSalt); Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(encryptionKey, passwordSaltBytes, this.KeyGenerationIterationCount); aesAlg.Key = pdb.GetBytes(AlgorithmKeyBytes); aesAlg.IV = pdb.GetBytes(AlgorithmInitializationVectorBytes); // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. MemoryStream memoryStreamDecrypt = new MemoryStream(encryptedTextBytes); // CA2202: Nested usings can have Dispose() called twice http://msdn.microsoft.com/en-us/library/ms182334.aspx using (StreamReader streamReaderDecrypt = new StreamReader(new CryptoStream(memoryStreamDecrypt, decryptor, CryptoStreamMode.Read))) { // Read the decrypted bytes from the decrypting stream // and place them in a string. retVal = streamReaderDecrypt.ReadToEnd(); } } catch (Exception e) { LogManager.CreateLogger <AESManager>().LogError(e, e.Message); } finally { // Clear the RijndaelManaged object. if (aesAlg != null) { aesAlg.Dispose(); } } } } return(retVal); }
public void Dispose() { if (!disposed) { aes.Dispose(); encryptor.Dispose(); Array.Clear(counter, 0, BlockSize); Array.Clear(keyStream.Array, 0, KeyStreamBufferSize); disposed = true; } }
/// <summary> /// Realiza a encriptação simétrica com a cifra AES (Padrão de Encriptação Avançado). /// </summary> /// <param name="text">O texto claro a ser criptografado</param> /// <param name="AES_KEY">A chave criptográfica</param> /// <param name="AES_IV">O vetor de inicialização (IV) das cifras simétricas</param> /// <param name="AES_KEY_SIZE">O tamanho da chave criptográfica (Em bits)></param> /// <returns></returns> public static byte[] Encrypt(string text, byte[] AES_KEY, byte[] AES_IV, int AES_KEY_SIZE) { try { if (!String.IsNullOrEmpty(text) && !String.IsNullOrWhiteSpace(text)) { byte[] Encrypted; using (Aes AES = Aes.Create()) { AES.KeySize = AES_KEY_SIZE; AES.Key = AES_KEY; AES.IV = AES_IV; ICryptoTransform TransfAES = AES.CreateEncryptor(AES.Key, AES.IV); MyKey = AES_KEY; using (var Memory = new MemoryStream()) { using (var Cryp = new CryptoStream(Memory, TransfAES, CryptoStreamMode.Write)) { using (var Stream = new StreamWriter(Cryp)) { Stream.Write(text); Stream.Close(); } Encrypted = Memory.ToArray(); Cryp.Close(); } AES.Dispose(); } return(Encrypted); } } } catch (CryptographicException ex) { Console.WriteLine("Erro na criptografia AES!\nMotivo: " + ex.Message); } catch (Exception ex) { Console.WriteLine("Erro na criptografia AES!\nMotivo: " + ex.Message); } return(null); }