Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AES String Encryption (CBC) Example Code for C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace aes_example
{
using System;
using System.IO;
using System.Security.Cryptography;
class Program
{
public static void Main()
{
try
{
string original = "Here is some data to encrypt!";
// Create a new instance of the Aes
// class. This generates a new key and initialization
// vector (IV).
using (var random = new RNGCryptoServiceProvider())
{
var key = new byte[16];
random.GetBytes(key);
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes_Aes(original, key);
// Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes_Aes(encrypted, key);
//Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Encrypted (b64-encode): {0}", Convert.ToBase64String(encrypted));
Console.WriteLine("Round Trip: {0}", roundtrip);
Console.ReadKey();
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key)
{
byte[] encrypted;
byte[] IV;
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.GenerateIV();
IV = aesAlg.IV;
aesAlg.Mode = CipherMode.CBC;
var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
var combinedIvCt = new byte[IV.Length + encrypted.Length];
Array.Copy(IV, 0, combinedIvCt, 0, IV.Length);
Array.Copy(encrypted, 0, combinedIvCt, IV.Length, encrypted.Length);
// Return the encrypted bytes from the memory stream.
return combinedIvCt;
}
static string DecryptStringFromBytes_Aes(byte[] cipherTextCombined, byte[] Key)
{
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
byte[] IV = new byte[aesAlg.BlockSize/8];
byte[] cipherText = new byte[cipherTextCombined.Length - IV.Length];
Array.Copy(cipherTextCombined, IV, IV.Length);
Array.Copy(cipherTextCombined, IV.Length, cipherText, 0, cipherText.Length);
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (var msDecrypt = new MemoryStream(cipherText))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
@obredan
Copy link

obredan commented Jan 13, 2017

hello....thats some good code

@mirjahongir
Copy link

mirjahongir commented May 14, 2017

thank you very much for your code

@aaronhoffman
Copy link

aaronhoffman commented Jun 26, 2017

@mgrfn
Copy link

mgrfn commented Aug 24, 2018

i used your code, thank you.

@CarlosACepeda
Copy link

CarlosACepeda commented Mar 26, 2019

Is this aes-128-cbc? thanks
Nice code though

@jipsonsds
Copy link

jipsonsds commented Jul 4, 2019

I have a file encrypted by AES 256

SaltIterationCount = 20000;
SaltLength = 16;
Salt[NfmsPackager::kSaltLength] = {0xd3, 0x31, 0x29, 0x4a, 0xae, 0x3d, 0xe5, 0xc5, 0xdf, 0x64, 0xd0, 0xf2, 0xa4, 0x97, 0xa2, 0x15};
InitializationVectorLength = 16; //128 bits long key
Password = "helloword";
Algorithm : PKCS5_PBKDF2_HMAC_SHA1

how can i decrypt

Copy link

ghost commented Jul 5, 2019

@jipsonsds, In this example, the text is encrypted and not the file

@kelalaka-153
Copy link

kelalaka-153 commented Sep 13, 2019

@mark-adams
Copy link
Author

mark-adams commented Sep 21, 2019

@kelalaka-153 No, I did not write this code. The fine folks at Microsoft did, but I’m guessing that you may already know that since you pasted a link to their site in your original comment. 😄

I copied this code into a snippet to make it easier for me to find and reference without having to search for it again.

@kelalaka-153
Copy link

kelalaka-153 commented Oct 1, 2019

No, I don't know. Usually, I put a link on top of the class, function.

@MuriloMazzeu
Copy link

MuriloMazzeu commented Sep 15, 2020

Thanks man, awesome code!

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