Skip to content

Instantly share code, notes, and snippets.

@mark-adams
Created December 12, 2014 15:02
Show Gist options
  • Save mark-adams/87aa34da3a5ed48ed0c7 to your computer and use it in GitHub Desktop.
Save mark-adams/87aa34da3a5ed48ed0c7 to your computer and use it in GitHub Desktop.
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

thank you very much for your code

@aaronhoffman
Copy link

@mgrfn
Copy link

mgrfn commented Aug 24, 2018

i used your code, thank you.

@CarlosACepeda
Copy link

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

@jipsonsds
Copy link

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

@mark-adams
Copy link
Author

@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

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

@MuriloMazzeu
Copy link

Thanks man, awesome code!

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