-
-
Save Andrei-Fogoros/bd657a50626e47c1a3f6c1757f606048 to your computer and use it in GitHub Desktop.
.NET Core 2 Encrypt/Decrypt String
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 void Main(string[] args) | |
{ | |
var content = "Example test"; | |
var key = "E546C8DF278CD5931069B522E695D4F2"; | |
var encrypted = EncryptString(content, key); | |
Console.WriteLine(encrypted); | |
var decrypted = DecryptString(encrypted, key); | |
Console.WriteLine(decrypted); | |
Console.ReadLine(); | |
} | |
public static string EncryptString(string text, string keyString) | |
{ | |
var key = Encoding.UTF8.GetBytes(keyString); | |
using (var aesAlg = Aes.Create()) | |
{ | |
using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV)) | |
{ | |
using (var msEncrypt = new MemoryStream()) | |
{ | |
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) | |
using (var swEncrypt = new StreamWriter(csEncrypt)) | |
{ | |
swEncrypt.Write(text); | |
} | |
var iv = aesAlg.IV; | |
var decryptedContent = msEncrypt.ToArray(); | |
var result = new byte[iv.Length + decryptedContent.Length]; | |
Buffer.BlockCopy(iv, 0, result, 0, iv.Length); | |
Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length); | |
return Convert.ToBase64String(result); | |
} | |
} | |
} | |
} | |
public static string DecryptString(string cipherText, string keyString) | |
{ | |
var fullCipher = Convert.FromBase64String(cipherText); | |
var iv = new byte[16]; | |
var cipher = new byte[16]; | |
Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length); | |
Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length); | |
var key = Encoding.UTF8.GetBytes(keyString); | |
using (var aesAlg = Aes.Create()) | |
{ | |
using (var decryptor = aesAlg.CreateDecryptor(key, iv)) | |
{ | |
string result; | |
using (var msDecrypt = new MemoryStream(cipher)) | |
{ | |
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) | |
{ | |
using (var srDecrypt = new StreamReader(csDecrypt)) | |
{ | |
result = srDecrypt.ReadToEnd(); | |
} | |
} | |
} | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment