Created
February 19, 2022 18:29
-
-
Save rabieedev1996/159b2939f69cbd4699bb02c2be5c07ba to your computer and use it in GitHub Desktop.
Aes Encryption In c#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static string EncryptStringToBytes(string plainText, string KeyString, string IVString) | |
| { | |
| var Key = Convert.FromBase64String(KeyString); | |
| var IV = Convert.FromBase64String(IVString); | |
| // Check arguments. | |
| if (plainText == null || plainText.Length <= 0) | |
| throw new ArgumentNullException("plainText"); | |
| if (Key == null || Key.Length <= 0) | |
| throw new ArgumentNullException("Key"); | |
| if (IV == null || IV.Length <= 0) | |
| throw new ArgumentNullException("IV"); | |
| byte[] encrypted; | |
| // Create an RijndaelManaged object | |
| // with the specified key and IV. | |
| using (RijndaelManaged rijAlg = new RijndaelManaged()) | |
| { | |
| rijAlg.Key = Key; | |
| rijAlg.IV = IV; | |
| // Create an encryptor to perform the stream transform. | |
| ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV); | |
| // Create the streams used for encryption. | |
| using (MemoryStream msEncrypt = new MemoryStream()) | |
| { | |
| using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) | |
| { | |
| using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) | |
| { | |
| //Write all data to the stream. | |
| swEncrypt.Write(plainText); | |
| } | |
| encrypted = msEncrypt.ToArray(); | |
| } | |
| } | |
| } | |
| // Return the encrypted bytes from the memory stream. | |
| return Convert.ToBase64String(encrypted); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment