public static string Encrypt(string plainText, string password) { Contract.Requires(!string.IsNullOrWhiteSpace(plainText)); Contract.Requires(!string.IsNullOrWhiteSpace(password)); Contract.Ensures(!string.IsNullOrWhiteSpace(Contract.Result <string>())); var hashProvider = new SHA256CryptoServiceProvider(); var algorithm = new AesManaged { Key = hashProvider.ComputeHash(_utf8.GetBytes(password)), Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; try { using (var encryptor = algorithm.CreateEncryptor()) { var abData = _utf8.GetBytes(plainText); var abResult = encryptor.TransformFinalBlock(abData, 0, abData.Length); var result = System.Convert.ToBase64String(abResult); return(result); } } finally { algorithm.Clear(); algorithm.Dispose(); hashProvider.Clear(); hashProvider.Dispose(); } }
public void Dispose() { _DerivedBytes.Dispose(); _CryptoStream.Dispose(); _CryptoTransform.Dispose(); _Aes.Dispose(); }
internal void _Dispose(Exception err = null) { lock (_loc) { if (_disposed) { return; } _disposed = true; _msgs.Clear(); _msglen = 0; } _cancel.Cancel(); _cancel.Dispose(); _socket.Dispose(); _listen?.Dispose(); _aes.Dispose(); var dis = Disposed; if (dis == null) { return; } Task.Run(() => { if (err == null) { err = new OperationCanceledException("Client disposed manually or by GC."); } var arg = new LinkEventArgs <Exception>(err); dis.Invoke(this, arg); }); }
/// <summary> /// Decrypts a given data byte array using AES /// </summary> /// <param name="input">The byte array data to decrypt</param> /// <returns>The decrypted array of data</returns> public byte[] Decrypt(byte[] input) { var aesManaged = new AesManaged { Key = Key, IV = IV }; var decryptor = aesManaged.CreateDecryptor(Key, IV); byte[] output; using (var memoryStream = new MemoryStream(input)) { using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { var bytes = new List <byte>(); var read = cryptoStream.ReadByte(); while (read != -1) { bytes.Add((byte)read); //Safe cast as read will be a byte or -1, and -1 is handled read = cryptoStream.ReadByte(); } output = bytes.ToArray(); } } aesManaged.Dispose(); return(output); }
private string DecryptIP(string hash) { byte[] key = { 246, 85, 186, 157, 9, 161, 18, 212, 150, 140, 99, 87, 157, 181, 144, 180 }; byte[] iv = { 152, 52, 76, 46, 238, 134, 195, 153, 72, 144, 89, 37, 133, 180, 159, 128 }; var bytesIn = toNumbers(hash); AesManaged aesmanage = new AesManaged(); aesmanage.KeySize = key.Length * 8; aesmanage.Padding = PaddingMode.None; aesmanage.Key = key; aesmanage.IV = iv; aesmanage.Mode = CipherMode.CBC; ICryptoTransform decrypter = aesmanage.CreateDecryptor(); byte[] decrypted = decrypter.TransformFinalBlock(bytesIn, 0, bytesIn.Length); string decrypteddata = BitConverter.ToString(decrypted); decrypteddata = decrypteddata.Replace("-", "").ToLower(); decrypter.Dispose(); aesmanage.Dispose(); return(decrypteddata); }
protected virtual void Dispose(bool isDisposing) { if (isDisposing) { _algorithm.Dispose(); } }
protected override void Dispose(bool b) { if (_aes != null) { _aes.Dispose(); } }
internal static string DecryptBrokerResponse(string encryptedBrokerResponse, ICoreLogger logger) { byte[] outputBytes = Base64UrlHelpers.DecodeBytes(encryptedBrokerResponse); if (TryGetBrokerKey(out byte[] key)) { AesManaged algo = null; CryptoStream cryptoStream = null; MemoryStream memoryStream = null; try { memoryStream = new MemoryStream(outputBytes); algo = CreateSymmetricAlgorith(key); cryptoStream = new CryptoStream( memoryStream, algo.CreateDecryptor(), CryptoStreamMode.Read); using (StreamReader srDecrypt = new StreamReader(cryptoStream)) { string plaintext = srDecrypt.ReadToEnd(); return(plaintext); } } finally { memoryStream?.Dispose(); cryptoStream?.Dispose(); algo?.Dispose(); } } throw new MsalClientException( MsalError.BrokerKeyFetchFailed, MsalErrorMessage.iOSBrokerKeyFetchFailed); }
/// <summary> /// Encrypts supplied text with supplied encryption key and initialization vector /// </summary> /// <param name="plainText">Text to be encrypted</param> /// <param name="key">Encryption Key</param> /// <param name="initializationVector">Initialization Vector</param> /// <returns>EncryptionData instance containing cipher, key, and initialization vector</returns> public AesEncryptionData Encrypt(string plainText, string key, string initializationVector) { var aesAlg = new AesManaged(); try { TryAssignKeyAndIv(key, initializationVector, ref aesAlg); ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(plainText); } string cipher = _converter.Convert(msEncrypt.ToArray()); return(new AesEncryptionData(cipher, initializationVector, key)); } } } finally { aesAlg.Dispose(); } }
internal void _Dispose(Exception err = null) { lock (_locker) { if (_disposed) { return; } _disposed = true; _messageQueue.Clear(); _messageLength = 0; } _cancellationSource.Cancel(); _cancellationSource.Dispose(); _socket.Dispose(); _listen?.Dispose(); _aes.Dispose(); var dis = Disposed; if (dis == null) { return; } _ = Task.Run(() => { if (err == null) { err = new OperationCanceledException("Client disposed."); } var arg = new LinkEventArgs <Exception>(err); dis.Invoke(this, arg); }); }
public static byte[] Decrypt(string key, byte[] encrypted) { byte[] buffer; // Create the streams used for encryption. AesManaged managed = null; try { managed = new AesManaged { IV = GetIv(key), Key = GetKey(key) }; ICryptoTransform encryptor = managed.CreateDecryptor(); MemoryStream msEncrypt = new MemoryStream(); // csEncrypt.Dispose() should call msEncrypt.Dispose() using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { csEncrypt.Write(encrypted, 0, encrypted.Length); buffer = msEncrypt.ToArray(); } } finally { managed?.Dispose(); } return(buffer); }
/// <summary> /// Decrypt the supplied cipher based on supplied encryption key and initialization vector /// </summary> /// <param name="cipher">Cipher to decrypt</param> /// <param name="key">Encryption Key</param> /// <param name="initializationVector">Initialization Vector</param> /// <returns>Plain text of decrypted cipher</returns> public string Decrypt(string cipher, string key, string initializationVector) { if (!Util.IsValidHexString(cipher)) { throw new InvalidCipherException(string.Format("Invalid cipher supplied: \"{0}\"", cipher)); } var aesAlg = new AesManaged(); string plainText = null; try { TryAssignKeyAndIv(key, initializationVector, ref aesAlg); ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msDecrypt = new MemoryStream(_converter.Convert(cipher))) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { plainText = srDecrypt.ReadToEnd(); } } } } finally { aesAlg.Dispose(); } return(plainText); }
private static byte[] Encrypt(byte[] unencrypted, out byte[] Iv, out byte[] Key) { byte[] encrypted; // Create the streams used for encryption. AesManaged managed = null; try { managed = new AesManaged(); Iv = managed.IV; Key = managed.Key; // Create a decrytor to perform the stream transform. ICryptoTransform encryptor = managed.CreateEncryptor(managed.Key, managed.IV); MemoryStream msEncrypt = new MemoryStream(); // csEncrypt.Dispose() should call msEncrupt.Dispose() using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { csEncrypt.Write(unencrypted, 0, unencrypted.Length); encrypted = msEncrypt.ToArray(); } } finally { if (managed != null) { managed.Dispose(); } } return(encrypted); }
public void Dispose() { CanDescramble = false; _Decryptor.Dispose(); _Aes.Dispose(); _Decryptor = null; _Aes = null; }
/// <inheritdoc/> public void Dispose() { if (aes != null) { aes.Dispose(); aes = null; } }
/// <summary> /// 关闭加密传输模块 /// </summary> private void SecurityClose() { if (_aes != null) { _aes.Clear(); // 清除敏感数据 _aes.Dispose(); // 释放资源 _aes = null; } }
/** * * @param _inputText * Text to be encrypted or decrypted * @param _encryptionKey * Encryption key to used for encryption / decryption * @param _mode * specify the mode encryption / decryption * @param _initVector * initialization vector * @return encrypted or decrypted string based on the mode */ private String encryptDecrypt(string _inputText, string _encryptionKey, EncryptMode _mode, string _initVector) { string _out = ""; // output string //_encryptionKey = MD5Hash (_encryptionKey); _pwd = Encoding.UTF8.GetBytes(_encryptionKey); _ivBytes = Encoding.UTF8.GetBytes(_initVector); int len = _pwd.Length; if (len > _key.Length) { len = _key.Length; } int ivLenth = _ivBytes.Length; if (ivLenth > _iv.Length) { ivLenth = _iv.Length; } Array.Copy(_pwd, _key, len); Array.Copy(_ivBytes, _iv, ivLenth); _rcipher.Key = _key; _rcipher.IV = _iv; if (_mode.Equals(EncryptMode.ENCRYPT)) { //encrypt byte[] plainText = _rcipher.CreateEncryptor().TransformFinalBlock(_enc.GetBytes(_inputText), 0, _inputText.Length); _out = Convert.ToBase64String(plainText); } if (_mode.Equals(EncryptMode.DECRYPT)) { //decrypt byte[] plainText = _rcipher.CreateDecryptor().TransformFinalBlock(Convert.FromBase64String(_inputText), 0, Convert.FromBase64String(_inputText).Length); _out = _enc.GetString(plainText); } _rcipher.Dispose(); return(_out); // return encrypted/decrypted string }
protected override void Dispose(bool disposing) { if (disposing) { encryptor?.Dispose(); aesAlg?.Dispose(); if (autoDisposeBaseStream) { baseStream?.Dispose(); } } base.Dispose(disposing); }
protected override void Dispose(bool disposing) { try { if (disposing) { Aes.Dispose(); } } finally { base.Dispose(disposing); } }
protected override void Dispose(bool disposing) { if (disposing) { _encryptor?.Dispose(); _aes?.Dispose(); if (AutoDisposeBaseStream) { _baseStream?.Dispose(); } } base.Dispose(disposing); }
/// <summary> /// Decrypts data that was encrypted using <see cref="ISymmetricCryptography.EncryptWithPassword(byte[],string)"/>. /// </summary> /// <param name="encryptedBytes">The encrypted data.</param> /// <param name="password">The password that was used to encrypt the data.</param> /// <returns>The decrypted <c>byte[]</c> array.</returns> public byte[] DecryptWithPassword(byte[] encryptedBytes, string password) { int encryptedBytesLength = encryptedBytes?.Length ?? 0; if (encryptedBytesLength <= 32 || string.IsNullOrEmpty(password)) { return(Array.Empty <byte>()); } byte[] decryptedBytes; byte[] salt = new byte[32]; for (int i = 0; i < 32; i++) { salt[i] = encryptedBytes[i]; } AesManaged aes = null; Rfc2898DeriveBytes rfc = null; try { rfc = new Rfc2898DeriveBytes(password, salt, RFC_ITERATIONS); aes = new AesManaged { KeySize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7, IV = rfc.GetBytes(16), Key = rfc.GetBytes(32) }; using ICryptoTransform decryptor = aes.CreateDecryptor(); decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 32, encryptedBytesLength - 32); } catch { decryptedBytes = null; } finally { aes?.Dispose(); rfc?.Dispose(); } return(decryptedBytes); }
private bool disposedValue = false; // 중복 호출을 검색하려면 protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: 관리되는 상태(관리되는 개체)를 삭제합니다. _aes?.Dispose(); } // TODO: 관리되지 않는 리소스(관리되지 않는 개체)를 해제하고 아래의 종료자를 재정의합니다. // TODO: 큰 필드를 null로 설정합니다. _utf8Encoding = null; disposedValue = true; } }
void Encrypt(OnCommandArgs args, string[] inMsg) { if (inMsg.Length < 3) { _ircInterface.Client.SendMessage(SendType.Message, args.Source, args.Nick + " the syntax for this command is .encrypt <key> <data>"); return; } try{ var key = AsciiToBase10(inMsg[1].ToCharArray()); var msg = AssembleMessage(inMsg.Skip(2).ToList()); msg = msg.Remove(msg.Length - 1); var msgByte = AsciiToBase10(msg.ToCharArray()); if (msgByte.Length % 16 != 0) { var paddedLen = (msgByte.Length / 16 + 1) * 16; msgByte = PKCS7(msgByte, paddedLen); } var aes = new AesManaged(); aes.KeySize = 128; aes.Mode = CipherMode.CBC; aes.Key = PKCS7(key, 16); aes.Padding = PaddingMode.None; aes.IV = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; var memStrm = new MemoryStream(msgByte.Length); var cryptStrm = new CryptoStream(memStrm, aes.CreateEncryptor(), CryptoStreamMode.Write); cryptStrm.Write(msgByte, 0, msgByte.Length); var ret = memStrm.ToArray(); aes.Dispose(); cryptStrm.Dispose(); memStrm.Dispose(); var retb10 = new string(Convert.ToBase64String(ret).ToCharArray()); _ircInterface.Client.SendMessage(SendType.Message, args.Source, args.Nick + ": " + retb10); } catch { _ircInterface.Client.SendMessage(SendType.Message, args.Source, args.Nick + ": something went wrong during encryption."); } }
protected string Encrypt(string blob, string externalKey) { var self = new ECDiffieHellmanCng(); self.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; self.HashAlgorithm = CngAlgorithm.Sha256; publicKey = Convert.ToBase64String(self.PublicKey.ToByteArray()); var externalKeyBytes = Convert.FromBase64String(externalKey); var externalKeyObject = ECDiffieHellmanCngPublicKey.FromByteArray(externalKeyBytes, CngKeyBlobFormat.GenericPublicBlob); var sharedSecret = self.DeriveKeyMaterial(externalKeyObject); var aes = new AesManaged(); aes.Key = sharedSecret; aes.GenerateIV(); var transform = aes.CreateEncryptor(); using (var memoryStream = new MemoryStream()) { var cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write); var data = Encoding.ASCII.GetBytes(blob); cryptoStream.Write(data, 0, data.Length); cryptoStream.Close(); var encryptedData = memoryStream.ToArray(); blob = Convert.ToBase64String(encryptedData); self.Dispose(); aes.Dispose(); return(AddEncryptionHeaders(blob)); } }
/// <summary> /// Encrypt a given string using AES /// </summary> /// <param name="input">The string to encrypt</param> /// <returns>The encrypted data as a byte array</returns> public byte[] Encrypt(byte[] input) { var aesManaged = new AesManaged { Key = Key, IV = IV }; var encryptor = aesManaged.CreateEncryptor(Key, IV); byte[] output; using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(input, 0, input.Length); } output = memoryStream.ToArray(); } aesManaged.Dispose(); return(output); }
public static byte[] DecryptWithString(byte[] encryptedData, string key) { var pdb = new PasswordDeriveBytes(key, Encoding.ASCII.GetBytes(key)); var ms = new MemoryStream(); var aes = new AesManaged(); aes.Key = pdb.GetBytes(aes.KeySize / 8); aes.IV = pdb.GetBytes(aes.BlockSize / 8); var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(encryptedData, 0, encryptedData.Length); cs.Close(); aes.Dispose(); pdb.Dispose(); return(ms.ToArray()); }
/// <summary> /// Decrypts the specified <see cref="EncryptionResult"/> that was obtained using <see cref="ISymmetricCryptography.Encrypt(byte[])"/>. /// </summary> /// <param name="encryptionResult">The <see cref="EncryptionResult"/> that was obtained using <see cref="ISymmetricCryptography.Encrypt(byte[])"/>.</param> /// <returns>Decrypted <c>byte[]</c> array or <c>null</c> if decryption failed.</returns> public byte[] Decrypt(EncryptionResult encryptionResult) { int encryptedBytesLength = encryptionResult?.EncryptedData?.Length ?? 0; if (encryptedBytesLength == 0) { return(Array.Empty <byte>()); } byte[] result; AesManaged aes = null; ICryptoTransform decryptor = null; try { aes = new AesManaged { KeySize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7, IV = encryptionResult.IV, Key = encryptionResult.Key }; decryptor = aes.CreateDecryptor(); result = decryptor.TransformFinalBlock(encryptionResult.EncryptedData, 0, encryptedBytesLength); } catch { result = null; } finally { aes?.Dispose(); decryptor?.Dispose(); } return(result); }
public static string Encrypt(string data, string password = null) { if (string.IsNullOrEmpty(password)) { password = GetPassword(); Contract.Assert(!string.IsNullOrEmpty(password), "No password in AppSettings found or no password specified"); } var hashProvider = new SHA256CryptoServiceProvider(); var algorithm = new AesManaged { Key = hashProvider.ComputeHash(_utf8.GetBytes(password)), Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; string result; try { var abData = _utf8.GetBytes(data); using (var encryptor = algorithm.CreateEncryptor()) { var abResult = encryptor.TransformFinalBlock(abData, 0, abData.Length); result = System.Convert.ToBase64String(abResult); } } finally { algorithm.Clear(); algorithm.Dispose(); hashProvider.Clear(); hashProvider.Dispose(); } return(result); }
void Decrypt(OnCommandArgs args, string[] inMsg) { if (inMsg.Length < 3) { _ircInterface.Client.SendMessage(SendType.Message, args.Source, args.Nick + " the syntax for this command is .decrypt <key> <data>"); return; } try{ var key = AsciiToBase10(inMsg[1].ToCharArray()); var msgByte = Convert.FromBase64CharArray(inMsg[2].ToCharArray(), 0, inMsg[2].Length); var aes = new AesManaged(); aes.Mode = CipherMode.CBC; aes.IV = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; aes.KeySize = 128; var keyPad = PKCS7(key, 16); aes.Key = keyPad; aes.Padding = PaddingMode.None; var memStrm = new MemoryStream(msgByte.Length); var cryptStrm = new CryptoStream(memStrm, aes.CreateDecryptor(), CryptoStreamMode.Write); cryptStrm.Write(msgByte, 0, msgByte.Length); var ret = memStrm.ToArray(); aes.Dispose(); cryptStrm.Dispose(); memStrm.Dispose(); ret = StripPKCS7(ret); var retStr = new string(Base10ToAscii(ret)); _ircInterface.Client.SendMessage(SendType.Message, args.Source, args.Nick + ": " + retStr); } catch { _ircInterface.Client.SendMessage (SendType.Message, args.Source, args.Nick + ": something went wrong during decryption. did you change the encrypted string?"); } }
public void Dispose() { aesCryptoProvider?.Dispose(); cipher?.Dispose(); }