Skip to content

Instantly share code, notes, and snippets.

@rabieedev1996
Created February 19, 2022 18:43
Show Gist options
  • Save rabieedev1996/570652f2603382edad867b0d434f6e09 to your computer and use it in GitHub Desktop.
Save rabieedev1996/570652f2603382edad867b0d434f6e09 to your computer and use it in GitHub Desktop.
Aes decryption in c#
public static string DecryptStringFromBytes(string cipherTextString, string KeyString, string IVString)
{
var Key = Convert.FromBase64String(KeyString);
var IV = Convert.FromBase64String(IVString);
var cipherText = Convert.FromBase64String(cipherTextString);
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
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();
}
}
}
}
return plaintext;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment