The AES 256 / Rijndael encryption standard had a lot of ASP.NET C# implementations within the past few years: projects like BouncyCastle, SharpAESCrypt and CryptoN, just to name a few of them, are all quite simple to use and 100% working. So, why should we publish "yet another" AES 256 C# implementation class?
The answer is basically the same we usually do whenever we end up reinventing the weel, just like we did when we wrote our C# random password generator, our PDF-to-TXT and PDF-to-HTML converter and many other helper classes: we needed to do something that couldn't be done with the existing alternatives. This time we weren't looking for a "simple" implementation to handle the standard AES encryption/decryption tasks in the seamless possible way: conversely, we needed to configure some specific aspects of the AES cryptographic algorythm, such as the BlockSize, the Cipher mode, the Crypt algorithm, the Password Hashing algorithm (if any), the number of password iterations (if any), the Initialization Vector (IV), the Key Length (whenever we need it fixed), the Salt, the Padding mode, and so on.
In order to fullfill this tasks we came up with the following package, which we called AESCrypt - pretty original, isn't it? The usage is still fairly simple and very similar to the other AES-based packages - as long as you don't need to mess up with all these settings and are ok with the industry-standard defaults - yet it also has a decent (and further expandable) option class that can be configured to handle most of the encryption details.
Usage Samples
Let's start with a couple encrypt & decrypt code samples to see how it can be used in a typical back-end scenario:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// text to encrypt var text = "Hello world!"; // passPhrase (32 bit length for AES256) var passPhrase = "12345678901234567890123456789012"; // Initialization Vector (16 bit length) var iv = "1234567890123456"; // Encrypt & Decrypt (with standard settings) var encryptedText = new AESCrypt(passPhrase, iv).Encrypt(); var sourceText = new AESCrypt(passPhrase, iv).Decrypt(encryptedText); // Encrypt & Decrypt (with advanced settings) var opts = new AESCryptOptions() { PasswordHash = AESPasswordHash.SHA1, PasswordHashIterations = 2, PasswordHashSalt = "23$9uBsDjf8", PaddingMode = PaddingMode.Zeroes, MinSaltLength = 4, MaxSaltLength = 8 }; var encryptedText = new AESCrypt(passPhrase, iv, opts).Encrypt(); var sourceText = new AESCrypt(passPhrase, iv, opts).Decrypt(encryptedText); |
As we can see, we can use either the simple mode - which uses the most common AES standards - or an advanced mode if we need more granular control.
The AESCrypt project is licensed under the Apache License 2.0 and is available on GitHub: we strongly suggest to go there in order to get the updated code.
However, in the following paragraph we'll briefly explain how it works and publish the full source code for all the package classes as it is to the present day - July 13, 2018.
Source Code
The package is made of three classes:
- AESCrypt - the main crypto handler, containing the Encrypt and Decrypt methods and the actual implementation logic, which is built upon the AesManaged and AESCryptOptions ASP.NET legacy classes from the SystemSecurity.Cryptography namespace.
- AESCryptOptions - a POCO class containing the AES encrypt/decrypt options, together with their default settings.
- AESPasswordHash - a simple ENUM containing the available options for password hash - SHA1, MD5 or None.
AESCrypt.cs
Let's start with the AESCrypt class (AESCrypt.cs file):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 |
///////////////////////////////////////////////////////////////////////////////////////////////////// // AESCrypt - Symmetric key encryption and decryption using AES/Rijndael algorythm (128, 192 and 256) // https://www.ryadel.com/ , 2016 ///////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; using System.Security.Cryptography; using System.ComponentModel; namespace Ryadel.Components.Security { /// <summary> /// This class uses a symmetric key algorithm (AES) to encrypt and decrypt data. As long as it is initialized with the same constructor /// parameters, the class will use the same key. Before performing encryption, the class can prepend random bytes to plain text and generate different /// encrypted values from the same plain text, encryption key, initialization vector, and other parameters. This class is thread-safe. /// </summary> public class AESCrypt { #region Private members // These members will be used to perform encryption and decryption. private ICryptoTransform encryptor = null; private ICryptoTransform decryptor = null; private AESCryptOptions Options = null; #endregion #region Constructors /// <summary> /// Use this constructor to perform encryption/decryption with the following options: /// - 128/192/256-bit key (depending on passPhrase length in bits) /// - SHA-1 password hashing algorithm with 4-to-8 byte long password hash salt and 1 password iteration /// - hashing without salt /// - no initialization vector /// - electronic codebook (ECB) mode /// </summary> /// <param name="passPhrase"> /// Passphrase (in string format) from which a pseudo-random password will be derived. The derived password will be used to generate the encryption key. /// </param> /// <remarks> /// This constructor is NOT recommended because it does not use initialization vector and uses the ECB cipher mode, which is less secure than the CBC mode. /// </remarks> public AESCrypt(string passPhrase) : this(passPhrase, null) { } /// <summary> /// Use this constructor to perform encryption/decryption with the following options: /// - 128/192/256-bit key (depending on passPhrase length in bits) /// - SHA-1 password hashing algorithm with 4-to-8 byte long password hash salt and 1 password iteration /// - hashing without salt /// - cipher block chaining (CBC) mode /// </summary> /// <param name="passPhrase"> /// Passphrase (in string format) from which a pseudo-random password will be derived. The derived password will be used to generate the encryption key. /// </param> /// <param name="initVector"> /// Initialization vector (IV). This value is required to encrypt the first block of plaintext data. IV must be exactly 16 ASCII characters long. /// </param> public AESCrypt(string passPhrase, string initVector) : this(passPhrase, initVector, new AESCryptOptions()) { } /// <summary> /// Use this constructor to perform encryption/decryption with custom options. /// See AESCryptOptions documentation for details. /// </summary> /// <param name="passPhrase"> /// Passphrase (in string format) from which a pseudo-random password will be derived. The derived password will be used to generate the encryption key. /// </param> /// <param name="initVector"> /// Initialization vector (IV). This value is required to encrypt the first block of plaintext data. IV must be exactly 16 ASCII characters long. /// </param> /// <param name="options"> /// A set of customized (or default) options to use for the encryption/decryption: see AESCryptOptions documentation for details. /// </param> public AESCrypt(string passPhrase, string initVector, AESCryptOptions options) { // store the options object locally. this.Options = options; // Checks for the correct (or null) size of cryptographic key. if (Options.FixedKeySize.HasValue && Options.FixedKeySize != 128 && Options.FixedKeySize != 192 && Options.FixedKeySize != 256) throw new NotSupportedException("ERROR: options.FixedKeySize must be NULL (for auto-detect) or have a value of 128, 192 or 256"); // Initialization vector converted to a byte array. byte[] initVectorBytes = null; // Salt used for password hashing (to generate the key, not during // encryption) converted to a byte array. byte[] saltValueBytes = null; // Get bytes of initialization vector. if (initVector == null) initVectorBytes = new byte[0]; else initVectorBytes = Encoding.UTF8.GetBytes(initVector); // Gets the KeySize int keySize = (Options.FixedKeySize.HasValue) ? Options.FixedKeySize.Value : GetAESKeySize(passPhrase); // Get bytes of password (hashing it or not) byte[] keyBytes = null; if (Options.PasswordHash == AESPasswordHash.None) { // Convert passPhrase to a byte array keyBytes = System.Text.Encoding.UTF8.GetBytes(passPhrase); } else { // Get bytes of password hash salt if (Options.PasswordHashSalt == null) saltValueBytes = new byte[0]; else saltValueBytes = Encoding.UTF8.GetBytes(options.PasswordHashSalt); // Generate password, which will be used to derive the key. PasswordDeriveBytes password = new PasswordDeriveBytes( passPhrase, saltValueBytes, Options.PasswordHash.ToString().ToUpper().Replace("-", ""), Options.PasswordHashIterations); // Convert key to a byte array adjusting the size from bits to bytes. keyBytes = password.GetBytes(keySize / 8); } // Initialize AES key object. AesManaged symmetricKey = new AesManaged(); // Sets the padding mode symmetricKey.Padding = Options.PaddingMode; // Use the unsafe ECB cypher mode (not recommended) if no IV has been provided, otherwise use the more secure CBC mode. symmetricKey.Mode = (initVectorBytes.Length == 0) ? CipherMode.ECB : CipherMode.CBC; // Create the encryptor and decryptor objects, which we will use for cryptographic operations. encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes); decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes); } #endregion #region Encryption routines /// <summary> /// Encrypts a string value generating a base64-encoded string. /// </summary> /// <param name="plainText"> /// Plain text string to be encrypted. /// </param> /// <returns> /// Cipher text formatted as a base64-encoded string. /// </returns> public string Encrypt(string plainText) { return Encrypt(Encoding.UTF8.GetBytes(plainText)); } /// <summary> /// Encrypts a byte array generating a base64-encoded string. /// </summary> /// <param name="plainTextBytes"> /// Plain text bytes to be encrypted. /// </param> /// <returns> /// Cipher text formatted as a base64-encoded string. /// </returns> public string Encrypt(byte[] plainTextBytes) { return Convert.ToBase64String(EncryptToBytes(plainTextBytes)); } /// <summary> /// Encrypts a string value generating a byte array of cipher text. /// </summary> /// <param name="plainText"> /// Plain text string to be encrypted. /// </param> /// <returns> /// Cipher text formatted as a byte array. /// </returns> public byte[] EncryptToBytes(string plainText) { return EncryptToBytes(Encoding.UTF8.GetBytes(plainText)); } /// <summary> /// Encrypts a byte array generating a byte array of cipher text. /// </summary> /// <param name="plainTextBytes"> /// Plain text bytes to be encrypted. /// </param> /// <returns> /// Cipher text formatted as a byte array. /// </returns> public byte[] EncryptToBytes(byte[] plainTextBytes) { // Add salt at the beginning of the plain text bytes (if needed). byte[] plainTextBytesWithSalt = (UseSalt()) ? AddSalt(plainTextBytes) : plainTextBytes; byte[] cipherTextBytes = null; // Let's make cryptographic operations thread-safe. lock (this) { // Encryption will be performed using memory stream. using (MemoryStream memoryStream = new MemoryStream()) { // To perform encryption, we must use the Write mode. using (CryptoStream cryptoStream = new CryptoStream( memoryStream, encryptor, CryptoStreamMode.Write)) { // Start encrypting data. cryptoStream.Write(plainTextBytesWithSalt, 0, plainTextBytesWithSalt.Length); // Finish the encryption operation. cryptoStream.FlushFinalBlock(); // Move encrypted data from memory into a byte array. cipherTextBytes = memoryStream.ToArray(); cryptoStream.Close(); } memoryStream.Close(); } // Return encrypted data. return cipherTextBytes; } } #endregion #region Decryption routines /// <summary> /// Decrypts a base64-encoded cipher text value generating a string result. /// </summary> /// <param name="cipherText"> /// Base64-encoded cipher text string to be decrypted. /// </param> /// <returns> /// Decrypted string value. /// </returns> public string Decrypt(string cipherText) { return Decrypt(Convert.FromBase64String(cipherText)); } /// <summary> /// Decrypts a byte array containing cipher text value and generates a /// string result. /// </summary> /// <param name="cipherTextBytes"> /// Byte array containing encrypted data. /// </param> /// <returns> /// Decrypted string value. /// </returns> public string Decrypt(byte[] cipherTextBytes) { return Encoding.UTF8.GetString(DecryptToBytes(cipherTextBytes)); } /// <summary> /// Decrypts a base64-encoded cipher text value and generates a byte array /// of plain text data. /// </summary> /// <param name="cipherText"> /// Base64-encoded cipher text string to be decrypted. /// </param> /// <returns> /// Byte array containing decrypted value. /// </returns> public byte[] DecryptToBytes(string cipherText) { return DecryptToBytes(Convert.FromBase64String(cipherText)); } /// <summary> /// Decrypts a base64-encoded cipher text value and generates a byte array /// of plain text data. /// </summary> /// <param name="cipherTextBytes"> /// Byte array containing encrypted data. /// </param> /// <returns> /// Byte array containing decrypted value. /// </returns> public byte[] DecryptToBytes(byte[] cipherTextBytes) { byte[] decryptedBytes = null; byte[] plainTextBytes = null; int decryptedByteCount = 0; int saltLen = 0; // Since we do not know how big decrypted value will be, use the same // size as cipher text. Cipher text is always longer than plain text // (in block cipher encryption), so we will just use the number of // decrypted data byte after we know how big it is. decryptedBytes = new byte[cipherTextBytes.Length]; // Let's make cryptographic operations thread-safe. lock (this) { using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes)) { // To perform decryption, we must use the Read mode. using (CryptoStream cryptoStream = new CryptoStream( memoryStream, decryptor, CryptoStreamMode.Read)) { // Decrypting data and get the count of plain text bytes. decryptedByteCount = cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length); cryptoStream.Close(); } memoryStream.Close(); } } // If we are using salt, get its length from the first 4 bytes of plain text data. if (UseSalt()) { saltLen = (decryptedBytes[0] & 0x03) | (decryptedBytes[1] & 0x0c) | (decryptedBytes[2] & 0x30) | (decryptedBytes[3] & 0xc0); } // Allocate the byte array to hold the original plain text (without salt). plainTextBytes = new byte[decryptedByteCount - saltLen]; // Copy original plain text discarding the salt value if needed. Array.Copy(decryptedBytes, saltLen, plainTextBytes, 0, decryptedByteCount - saltLen); // Return original plain text value. return plainTextBytes; } #endregion #region Helper functions /// <summary> /// Gets the KeySize by the password length in bytes. /// </summary> /// <param name="p"></param> /// <returns></returns> public static int GetAESKeySize(string passPhrase) { switch (passPhrase.Length) { case 16: return 128; case 24: return 192; case 32: return 256; default: throw new NotSupportedException("ERROR: AES Password must be of 16, 24 or 32 bits length!"); } } /// <summary> /// Checks if salt must be used or not for the encryption/decryption. /// </summary> /// <returns></returns> private bool UseSalt() { // Use salt if the max salt value is greater than 0 and equal or greater than min salt length. return (Options.MaxSaltLength > 0 && Options.MaxSaltLength >= Options.MinSaltLength); } /// <summary> /// Adds an array of randomly generated bytes at the beginning of the /// array holding original plain text value. /// </summary> /// <param name="plainTextBytes"> /// Byte array containing original plain text value. /// </param> /// <returns> /// Either original array of plain text bytes (if salt is not used) or a /// modified array containing a randomly generated salt added at the /// beginning of the plain text bytes. /// </returns> private byte[] AddSalt(byte[] plainTextBytes) { // Additional check if (!UseSalt()) return plainTextBytes; // Generate the salt. byte[] saltBytes = GenerateSalt(Options.MinSaltLength, Options.MaxSaltLength); // Allocate array which will hold salt and plain text bytes. byte[] plainTextBytesWithSalt = new byte[plainTextBytes.Length + saltBytes.Length]; // First, copy salt bytes. Array.Copy(saltBytes, plainTextBytesWithSalt, saltBytes.Length); // Append plain text bytes to the salt value. Array.Copy(plainTextBytes, 0, plainTextBytesWithSalt, saltBytes.Length, plainTextBytes.Length); return plainTextBytesWithSalt; } /// <summary> /// Generates an array holding cryptographically strong bytes. /// </summary> /// <returns> /// Array of randomly generated bytes. /// </returns> /// <remarks> /// Salt size will be defined at random or exactly as specified by the /// minSlatLen and maxSaltLen parameters passed to the object constructor. /// The first four bytes of the salt array will contain the salt length /// split into four two-bit pieces. /// </remarks> private byte[] GenerateSalt(int minSaltLen, int maxSaltLen) { // We don't have the length, yet. int saltLen = 0; // If min and max salt values are the same, it should not be random. if (minSaltLen == maxSaltLen) saltLen = minSaltLen; // Use random number generator to calculate salt length. else saltLen = GenerateRandomNumber(minSaltLen, maxSaltLen); // Allocate byte array to hold our salt. byte[] salt = new byte[saltLen]; // Populate salt with cryptographically strong bytes. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetNonZeroBytes(salt); // Split salt length (always one byte) into four two-bit pieces and // store these pieces in the first four bytes of the salt array. salt[0] = (byte)((salt[0] & 0xfc) | (saltLen & 0x03)); salt[1] = (byte)((salt[1] & 0xf3) | (saltLen & 0x0c)); salt[2] = (byte)((salt[2] & 0xcf) | (saltLen & 0x30)); salt[3] = (byte)((salt[3] & 0x3f) | (saltLen & 0xc0)); return salt; } /// <summary> /// Generates random integer. /// </summary> /// <param name="minValue"> /// Min value (inclusive). /// </param> /// <param name="maxValue"> /// Max value (inclusive). /// </param> /// <returns> /// Random integer value between the min and max values (inclusive). /// </returns> /// <remarks> /// This methods overcomes the limitations of .NET Framework's Random /// class, which - when initialized multiple times within a very short /// period of time - can generate the same "random" number. /// </remarks> private int GenerateRandomNumber(int minValue, int maxValue) { // We will make up an integer seed from 4 bytes of this array. byte[] randomBytes = new byte[4]; // Generate 4 random bytes. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(randomBytes); // Convert four random bytes into a positive integer value. int seed = ((randomBytes[0] & 0x7f) << 24) | (randomBytes[1] << 16) | (randomBytes[2] << 8) | (randomBytes[3]); // Now, this looks more like real randomization. Random random = new Random(seed); // Calculate a random number. return random.Next(minValue, maxValue + 1); } #endregion } } |
AESCryptOptions.cs
This is the AESCryptOptions POCO class (AESCryptOptions.cs file):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
///////////////////////////////////////////////////////////////////////////////////////////////////// // AESCrypt - Symmetric key encryption and decryption using AES/Rijndael algorythm (128, 192 and 256) // https://www.ryadel.com/ , 2016 ///////////////////////////////////////////////////////////////////////////////////////////////////// using System.Security.Cryptography; namespace Ryadel.Components.Security { public class AESCryptOptions { #region Private members // Do not allow salt to be longer than 255 bytes, because we have only // 1 byte to store its length. private static int MAX_ALLOWED_SALT_LEN = 255; // Do not allow salt to be smaller than 4 bytes, because we use the first // 4 bytes of salt to store its length. private static int MIN_ALLOWED_SALT_LEN = 4; // Random salt value will be between 4 and 8 bytes long. private static int DEFAULT_MIN_SALT_LEN = MIN_ALLOWED_SALT_LEN; private static int DEFAULT_MAX_SALT_LEN = 8; // These members will be used to perform encryption and decryption. private ICryptoTransform encryptor = null; private ICryptoTransform decryptor = null; #endregion #region Constructor public AESCryptOptions() { PasswordHash = AESPasswordHash.SHA1; PasswordHashIterations = 1; MinSaltLength = 0; MaxSaltLength = 0; FixedKeySize = null; PaddingMode = PaddingMode.PKCS7; } #endregion #region Properties /// <summary> /// Key Size: this is typically 128, 192 or 256, depending on the password length in bit (16, 24 or 32 respectively). /// Default is NULL, meaning that it will be calculated on-the-fly using the password bit length. /// </summary> public int? FixedKeySize { get; set; } /// <summary> /// Password hashing mode: None, MD5 or SHA1. /// SHA1 is the recommended mode for most scenarios. /// </summary> public AESPasswordHash PasswordHash { get; set; } /// <summary> /// Password iterations - not used when [PasswordHash] is set to [AESPasswordHash.None] /// </summary> public int PasswordHashIterations { get; set; } /// <summary> /// Minimum Salt Length: must be equal or smaller than MaxSaltLength. /// Default is 0. /// </summary> public int MinSaltLength { get; set; } /// <summary> /// Maximum Salt Length: must be equal or greater than MinSaltLength. /// Default is 0, meaning that no salt will be used. /// </summary> public int MaxSaltLength { get; set; } /// <summary> /// Salt value used for password hashing during key generation. /// NOTE: This is not the same as the salt we will use during encryption. /// This parameter can be any string (set it to NULL for no password hash salt): default is NULL. /// </summary> public string PasswordHashSalt { get; set; } /// <summary> /// Sets the Padding Mode (default is PaddingMode.PKCS7) /// </summary> public PaddingMode PaddingMode { get; set; } #endregion } } |
AESPasswordHash.cs
Last but not least, the AESPasswordHash enum (AESPasswordHash.cs file):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
///////////////////////////////////////////////////////////////////////////////////////////////////// // AESCrypt - Symmetric key encryption and decryption using AES/Rijndael algorythm (128, 192 and 256) // https://www.ryadel.com/ , 2016 ///////////////////////////////////////////////////////////////////////////////////////////////////// namespace Ryadel.Components.Security { /// <summary> /// AES Password Hash: set "None" for no hashing. /// </summary> public enum AESPasswordHash : int { None = 0, MD5 = 1, SHA1 = 2 } } |
All the classes are all quite self-explanatory, hence most developers should be able to use them at will without having any major issue... you'll just have to follow the Intellisense.
That's about it: we sincerely hope that this package will help other ASP.NET developers to properly implement the AES encryption standard within their projects!