Skip to content

Instantly share code, notes, and snippets.

@davidsheardown
Created December 8, 2017 09:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save davidsheardown/6781a4c45eaf85917392678d7c3993d6 to your computer and use it in GitHub Desktop.
Save davidsheardown/6781a4c45eaf85917392678d7c3993d6 to your computer and use it in GitHub Desktop.
.NET Core 2 Encrypt/Decrypt String
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;
}
}
}
@john-katebini
Copy link

FYI I think Ln56 has a bug, perhaps it should be
Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, **cipher**.Length);
otherwise it won't work when you encrypt larger strings

@PradeepRT9860
Copy link

You need some modification on DecryptString

  1. Change >> var cipher = new byte[16]; to >> var cipher = new byte[fullCipher.Length - iv.Length];
    2 . and instead of Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, cipher.Length); use
    Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, fullCipher.Length - iv.Length);

following is the complete working code if loner the length of string

    public string DecryptString(string cipherText, string keyString)
    { 
        var fullCipher = Convert.FromBase64String(cipherText); 

        var iv = new byte[16];
        var cipher = new byte[fullCipher.Length - iv.Length]; //changes here

        Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
        // Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, cipher.Length);
        Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, fullCipher.Length - iv.Length); // changes here
        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;
            }
        }
    }

@dalvirsaini
Copy link

yes it works. thx Pardeep

@jay-doshi
Copy link

jay-doshi commented Dec 9, 2019

Receiving below error when "using (var encryptor = aesAlg.CreateEncryptor(_key, aesAlg.IV))" is executed in EncryptString function.
Error Message: ArgumentException: Specified key is not a valid size for this algorithm. Parameter name: rgbKey

Can anyone help?

@JonasJasas
Copy link

Receiving below error when "using (var encryptor = aesAlg.CreateEncryptor(_key, aesAlg.IV))" is executed in EncryptString function.
Error Message: ArgumentException: Specified key is not a valid size for this algorithm. Parameter name: rgbKey

Can anyone help?

Same same

@jay-doshi
Copy link

Use this as encryption key: "E546C8DF278CD5931069B522E695D4F2".
It will work for me now after updating key.

@CycoPH
Copy link

CycoPH commented Mar 4, 2020

The key sizes need to be 128, 192 or 256 bits. Since the code above reads bytes from a UTF8 string min key length is 16 characters, 24 and 32 chars lengths will also work. Anything else will throw an exception

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment