protected AesCryptoServiceBase(AesCspParameters aesCspParameters) { if (null == aesCspParameters) { throw new ArgumentNullException(nameof(aesCspParameters)); } aes = new AesCryptoServiceProvider { Key = HexTk.UnHex(aesCspParameters.AesKey), IV = HexTk.UnHex(aesCspParameters.AesIv) }; }
/// <summary> /// inverts the encryption of a string - works if the same AES key has been used for encryption. /// Notice for programmers: Each decryption needs a fresh decryptor, reuse of decryptor throws ugly exceptions. /// </summary> /// <param name="encryptedText"></param> /// <returns></returns> protected string DecryptString(string encryptedText) { var decrypted = string.Empty; try { var trimmed = encryptedText.ParseText(); if (!string.IsNullOrEmpty(trimmed)) { var unHexed = HexTk.UnHex(trimmed); using var msDecrypt = new MemoryStream(unHexed); // must get a fresh Decryptor for each decryption var decryptor = aes.CreateDecryptor(); using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); using var srDecrypt = new StreamReader(csDecrypt); decrypted = srDecrypt.ReadToEnd(); } } catch (Exception exception) { Log.Warning(exception, AesResources.Decryption_Failed, encryptedText); } return(decrypted); }