Created
December 7, 2020 06:28
-
-
Save dev-sankhadip/6e71d763e1e4b7d61712f11825bd35d2 to your computer and use it in GitHub Desktop.
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
//AES Encryption | |
public static string EncryptString(string plainText, string keyToUse) { | |
byte[] iv = new byte[16]; | |
byte[] array; | |
using(Aes aes = Aes.Create()) { | |
aes.Key = Encoding.UTF8.GetBytes(Get128BitString(keyToUse)); | |
aes.IV = iv; | |
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); | |
using(MemoryStream memoryStream = new MemoryStream()) { | |
using(CryptoStream cryptoStream = new CryptoStream((Stream) memoryStream, encryptor, CryptoStreamMode.Write)) { | |
using(StreamWriter streamWriter = new StreamWriter((Stream) cryptoStream)) { | |
streamWriter.Write(plainText); | |
} | |
array = memoryStream.ToArray(); | |
} | |
} | |
} | |
return Convert.ToBase64String(array); | |
} | |
public static string DecryptString(string cipherText, string keyToUse) { | |
byte[] iv = new byte[16]; | |
byte[] buffer = Convert.FromBase64String(cipherText); | |
using(Aes aes = Aes.Create()) { | |
aes.Key = Encoding.UTF8.GetBytes(Get128BitString(keyToUse)); | |
aes.IV = iv; | |
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); | |
using(MemoryStream memoryStream = new MemoryStream(buffer)) { | |
using(CryptoStream cryptoStream = new CryptoStream((Stream) memoryStream, decryptor, CryptoStreamMode.Read)) { | |
using(StreamReader streamReader = new StreamReader((Stream) cryptoStream)) { | |
return streamReader.ReadToEnd(); | |
} | |
} | |
} | |
} | |
} | |
public static string Get128BitString(string keyToConvert) { | |
StringBuilder b = new StringBuilder(); | |
for (int i = 0; i < 16; i++) { | |
b.Append(keyToConvert[i % keyToConvert.Length]); | |
} | |
keyToConvert = b.ToString(); | |
return keyToConvert; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment