Database Reference
In-Depth Information
9. }
10.
11. /// <summary>
12. /// The encryption class that encapsulates the complexity behind encrypting
13. /// and decrypting values
14. /// </summary>
15. public class Encryption
16. {
17. private byte[] _SECRET_KEY_ = new byte[] { 160, 225, 229, 3,
18. 148, 219, 67, 89, 247, 133, 213, 26, 129, 160, 235, 41,
19. 42, 177, 202, 251, 38, 56, 232, 90, 54, 88, 158, 169,
20. 200, 24, 19, 27 };
21.
22./// <summary>
23./// Encrypt using AES
24./// </summary>
25./// <param name="value">The string to encrypt</param>
26.public CipherText EncryptAES(string value)
27.{
28. // Prepare variables...
29. byte[] buffer = UTF8Encoding.UTF8.GetBytes(value);
30. CipherText ct = new CipherText();
31. System.Security.Cryptography.Aes aes = null;
32. ICryptoTransform transform = null;
33.
34. // Create the AES object
35. aes = System.Security.Cryptography.Aes.Create();
36. aes.GenerateIV();
37. aes.Key = _SECRET_KEY_;
38.
39. // Create the encryption object
40. transform = aes.CreateEncryptor();
41.
42. // Encrypt and store the result in the structure
43. ct.cipher = transform.TransformFinalBlock(buffer, 0, buffer.Length);
44. // Save the vector used for future use
45. ct.vector = aes.IV;
46.
47. return ct;
48. }
49.}
The CipherText structure (line 5) is used as a return value. Each encrypted byte array comes with its
initialization vector, which is a security mechanism that prevents dictionary attacks on your database.
The Encryption class contains an EncryptAES method that performs the actual encryption of a string
value; this method returns CipherText .
Because AES requires a secret key, you created one in the form of a byte array on line 17. The secret
key must be 32 bytes in length. You can easily generate your own by using the GenerateKey method
provided by the Aes class provided by .NET.
On line 29, you transform the string value to its byte representation using UTF-8 encoding. UTF-8
encoding is very practical because it automatically chooses between ASCII and Unicode based on the
input value.
Search WWH ::




Custom Search