Click here to Skip to main content
15,305,508 members
Articles / Security / Encryption
Article
Posted 6 May 2014

Tagged as

Stats

479K views
22.5K downloads
140 bookmarked

C# AES 256 bits Encryption Library with Salt

Rate me:
Please Sign up or sign in to vote.
4.78/5 (92 votes)
9 May 2014Public Domain2 min read
A C# universal AES Encryption Library.

Core Encryption Code

C#
using System.Security.Cryptography;
using System.IO;

Encryption

C#
public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
    byte[] encryptedBytes = null;

    // Set your salt here, change it to meet your flavor:
    // The salt bytes must be at least 8 bytes.
    byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

    using (MemoryStream ms = new MemoryStream())
    {
        using (RijndaelManaged AES = new RijndaelManaged())
        {
            AES.KeySize = 256;
            AES.BlockSize = 128;

            var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
            AES.Key = key.GetBytes(AES.KeySize / 8);
            AES.IV = key.GetBytes(AES.BlockSize / 8);

            AES.Mode = CipherMode.CBC;

            using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                cs.Close();
            }
            encryptedBytes = ms.ToArray();
        }
    }

    return encryptedBytes;
}

Decryption

C#
public byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
{
    byte[] decryptedBytes = null;

    // Set your salt here, change it to meet your flavor:
    // The salt bytes must be at least 8 bytes.
    byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

    using (MemoryStream ms = new MemoryStream())
    {
        using (RijndaelManaged AES = new RijndaelManaged())
        {
            AES.KeySize = 256;
            AES.BlockSize = 128;

            var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
            AES.Key = key.GetBytes(AES.KeySize / 8);
            AES.IV = key.GetBytes(AES.BlockSize / 8);

            AES.Mode = CipherMode.CBC;

            using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                cs.Close();
            }
            decryptedBytes = ms.ToArray();
        }
    }

    return decryptedBytes;
}

Example of Encrypting String

Encrypt String

C#
public string EncryptText(string input, string password)
{
    // Get the bytes of the string
    byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input);
    byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

    // Hash the password with SHA256
    passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

    byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);

    string result = Convert.ToBase64String(bytesEncrypted);

    return result;
}

Decrypt String

C#
public string DecryptText(string input, string password)
{
    // Get the bytes of the string
    byte[] bytesToBeDecrypted = Convert.FromBase64String(input);
    byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
    passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

    byte[] bytesDecrypted = AES_Decrypt(bytesToBeDecrypted, passwordBytes);

    string result = Encoding.UTF8.GetString(bytesDecrypted);

    return result;
}

You'll notice that the encrypted string is stored in base64 encoded mode. For those who is not familiar with base64 encoding, you may want to read Base What? A Practical Introduction to Base Encoding[^]

Example of Encrypting File

Encrypt File

C#
public void EncryptFile()
{
    string file = "C:\\SampleFile.DLL";
    string password = "abcd1234";

    byte[] bytesToBeEncrypted = File.ReadAllBytes(file);
    byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

    // Hash the password with SHA256
    passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

    byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);

    string fileEncrypted = "C:\\SampleFileEncrypted.DLL";

    File.WriteAllBytes(fileEncrypted, bytesEncrypted);
}

Decrypt File

C#
public void DecryptFile()
{
    string fileEncrypted = "C:\\SampleFileEncrypted.DLL";
    string password = "abcd1234";

    byte[] bytesToBeDecrypted = File.ReadAllBytes(fileEncrypted);
    byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
    passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

    byte[] bytesDecrypted = AES_Decrypt(bytesToBeDecrypted, passwordBytes);

    string file = "C:\\SampleFile.DLL";
    File.WriteAllBytes(file, bytesDecrypted);
}

Getting Randomized Encryption Result with Salt

If we encrypt the same context (i.e. string of "Hello World") for 10 times, the encrypted results will be the same. What if we want the results different from each time it is encrypted?

What I do is appending a random salt bytes in front of the original bytes before encryption, and remove it after decryption.

Example of Appending Randomized Salt Before Encrypting a String

C#
public static string EncryptString(string text, string password)
{
    byte[] baPwd = Encoding.UTF8.GetBytes(password);

    // Hash the password with SHA256
    byte[] baPwdHash = SHA256Managed.Create().ComputeHash(baPwd);

    byte[] baText = Encoding.UTF8.GetBytes(text);

    byte[] baSalt = GetRandomBytes();
    byte[] baEncrypted = new byte[baSalt.Length + baText.Length];

    // Combine Salt + Text
    for (int i = 0; i < baSalt.Length; i++)
        baEncrypted[i] = baSalt[i];
    for (int i = 0; i < baText.Length; i++)
        baEncrypted[i + baSalt.Length] = baText[i];

    baEncrypted = AES_Encrypt(baEncrypted, baPwdHash);

    string result = Convert.ToBase64String(baEncrypted);
    return result;
}

Example of Removing the Salt after Decryption

C#
public static string DecryptString(string text, string password)
{
    byte[] baPwd = Encoding.UTF8.GetBytes(password);

    // Hash the password with SHA256
    byte[] baPwdHash = SHA256Managed.Create().ComputeHash(baPwd);

    byte[] baText = Convert.FromBase64String(text);

    byte[] baDecrypted = AES_Decrypt(baText, baPwdHash);

    // Remove salt
    int saltLength = GetSaltLength();
    byte[] baResult = new byte[baDecrypted.Length - saltLength];
    for (int i = 0; i < baResult.Length; i++)
        baResult[i] = baDecrypted[i + saltLength];

    string result = Encoding.UTF8.GetString(baResult);
    return result;
}

Code for getting random bytes

C#
public static byte[] GetRandomBytes()
{
    int saltLength = GetSaltLength();
    byte[] ba = new byte[saltLength];
    RNGCryptoServiceProvider.Create().GetBytes(ba);
    return ba;
}

public static int GetSaltLength()
{
    return 8;
}

Another way of getting random bytes is by using System.Random. However, System.Random is strongly not recommended to be used in cryptography. This is because System.Random is not a true random. The changes of the value are following a specific sequence and pattern and it is predictable. RNGCrypto is truly randomize and the generated values does not follow a pattern and it is unpredictable.

About Storing Password in System.String

If you are working this on a desktop pc application, you are recommended not to store the password in plain string. Strings cannot be manually disposed. It will be disposed by Garbage Collector, however, it is hard to tell how long will the string continue to stay in memory before it is completely dispose. At the time it remains in memory, it is easily retrievable. One of the suggested method is by capturing the password key strokes and store it into byte array (or list of bytes) and wipe off the byte array immediately after it is used (for example, fill the byte array with 0 (zero), etc).

Another option is by using System.Security.SecureString. System.Security.SecureString can be destroyed manually at any time. The value stored within System.Security.SecureString is encrypted.

Example of Using SecureString

C#
using System.Security;
using System.Runtime.InteropServices; 

Storing text into SecureString:

C#
SecureString secureString = new SecureString();
secureString.AppendChar('h');
secureString.AppendChar('e');
secureString.AppendChar('l');
secureString.AppendChar('l');
secureString.AppendChar('o'); 

Retrieving data from SecureString

byte[] secureStringBytes = null;
// Convert System.SecureString to Pointer
IntPtr unmanagedBytes = Marshal.SecureStringToGlobalAllocAnsi(secureString);
try
{
    unsafe
    {
        byte* byteArray = (byte*)unmanagedBytes.ToPointer();
        // Find the end of the string
        byte* pEnd = byteArray;
        while (*pEnd++ != 0) { }
        // Length is effectively the difference here (note we're 1 past end) 
        int length = (int)((pEnd - byteArray) - 1);
        secureStringBytes = new byte[length];
        for (int i = 0; i < length; ++i)
        {
            // Work with data in byte array as necessary, via pointers, here
            secureStringBytes[i] = *(byteArray + i);
        }
    }
}
finally
{
    // This will completely remove the data from memory
    Marshal.ZeroFreeGlobalAllocAnsi(unmanagedBytes);
} 
return secureStringBytes; 

Retriving data from SecureString involves executing unsafe code (for handling unmanaged bytes). Therefore you have to allow your project to be built with unsafe code allowed. This option is available at your project's Properties settings.

Image 1

Or else you will receive error message:

Unsafe code may only appear if compiling with /unsafe 

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication

Share

About the Author

adriancs
Software Developer
Other Other
Programming is an art.

Comments and Discussions

 
GeneralRe: Nice Code But It Need More Optimizing Pin
@cromx23-Jun-15 18:50
Member@cromx23-Jun-15 18:50 
QuestionWhy not work with online tools? Pin
Member 111686668-Apr-15 23:52
MemberMember 111686668-Apr-15 23:52 
AnswerRe: Why not work with online tools? Pin
Ahmed Amer Jaf25-Apr-15 1:34
MemberAhmed Amer Jaf25-Apr-15 1:34 
GeneralGreat example Pin
Michael Mendelson2-Apr-15 9:36
MemberMichael Mendelson2-Apr-15 9:36 
QuestionNeed some explanations Pin
Member 834244024-Mar-15 2:21
MemberMember 834244024-Mar-15 2:21 
QuestionDoubt about the logic - 128 or 256 bits Pin
Renanrs20-Mar-15 7:57
MemberRenanrs20-Mar-15 7:57 
BugCode Error? Pin
BotFactory15-Mar-15 12:45
MemberBotFactory15-Mar-15 12:45 
GeneralRe: Code Error? Pin
Ahmed Amer Jaf25-Apr-15 1:37
MemberAhmed Amer Jaf25-Apr-15 1:37 
GetRandomBytes() Is A Function And It's Doesn't Have Any Arguments.

My Regards. Smile | :)
GeneralMy vote of 4 Pin
EveryNameIsTakenEvenThisOne3-Mar-15 5:56
professionalEveryNameIsTakenEvenThisOne3-Mar-15 5:56 
QuestionSir(adriancs) after encrption output is 24 character. But i need 32 character.Is it possible? Pin
phmani46925-Feb-15 1:06
Memberphmani46925-Feb-15 1:06 
AnswerRe: Sir(adriancs) after encrption output is 24 character. But i need 32 character.Is it possible? Pin
adriancs25-Feb-15 13:30
professionaladriancs25-Feb-15 13:30 
QuestionExcellent work, but I have a question . Pin
muh.d16-Feb-15 5:14
Membermuh.d16-Feb-15 5:14 
SuggestionWinRT Pin
lesvaches5-Feb-15 1:38
Memberlesvaches5-Feb-15 1:38 
QuestionWhy we need password filed here? Pin
Member 1117705323-Dec-14 2:28
MemberMember 1117705323-Dec-14 2:28 
GeneralGreat Pin
Mahsa Hassankashi28-Nov-14 6:28
MemberMahsa Hassankashi28-Nov-14 6:28 
GeneralThis is a beauty! Pin
Member 422552214-Oct-14 5:06
MemberMember 422552214-Oct-14 5:06 
GeneralMy vote of 5 Pin
Mitchell J.10-Oct-14 22:42
professionalMitchell J.10-Oct-14 22:42 
QuestionAES256-NI Vs AES-256 Pin
sachin_nike23-Sep-14 1:13
Membersachin_nike23-Sep-14 1:13 
AnswerRe: AES256-NI Vs AES-256 Pin
adriancs23-Sep-14 2:59
professionaladriancs23-Sep-14 2:59 
Questionwho can i add "the Marshal" code in my project ?? when i merge it with my project it's start giving error " the "Marshal" does not eist in the current context" Pin
Member 1106327918-Sep-14 22:00
MemberMember 1106327918-Sep-14 22:00 
AnswerRe: who can i add "the Marshal" code in my project ?? when i merge it with my project it's start giving error " the "Marshal" does not eist in the current context" Pin
adriancs12-Nov-14 22:50
professionaladriancs12-Nov-14 22:50 
Generalnice writeup Pin
panthro5517-Sep-14 8:49
Memberpanthro5517-Sep-14 8:49 
Bug[My vote of 1] Error in Authentaction Pin
Hus_loia14-Jul-14 17:50
MemberHus_loia14-Jul-14 17:50 
GeneralRe: [My vote of 1] Error in Authentaction Pin
adriancs14-Jul-14 19:45
professionaladriancs14-Jul-14 19:45 
QuestionCross platform applicability Pin
Kedyr24-Jun-14 4:22
MemberKedyr24-Jun-14 4:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.