Uutiset

Adafyn kuulumisia

Encrypt & Decrypt String in ASP.NET Core

<p>This post shows how to encrypt and decrypt string in ASP.NET Core.</p><p><br /></p><img src="/posts/files/8f17aed4-e362-4f49-a587-c7aab5ab4a65.jpeg" alt="Encrypt decrypt output" /><br /><br /><p>Lately I’ve been working with ASP.NET Core. The .NET Core moves things around a little bit, at least until .NET Standard 2.0 arrives. Here’s some simple code which I’ve been using to encrypt and decrypt a string in ASP.NET Core using a static key.</p><h2>First, the example console app:</h2><pre class="vb" name="code"> 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();
}
</pre><h2>Secondly, the source code for EncryptString and DecryptString:</h2><pre class="vb" name="code"> 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;
}
}
}
</pre><p><a href="http://mikaelkoskinen.net/posts/files/27b1e7b8-ccec-45b3-8322-48904af9b01e.png"><img title="image" style="border-top:0;border-right:0;background-image:none;border-bottom:0;padding-top:0;padding-left:0;border-left:0;display:inline;padding-right:0" border="0" alt="image" src="http://mikaelkoskinen.net/posts/files/91464899-2b56-48ca-806f-e61dfb8a21c1.png" width="453" height="83" /></a></p>