Database Reference
In-Depth Information
You declare the AES object on line 31 and instantiate it on line 35 using the static Create() method
on the Aes class. This method creates the vector automatically on line 36 and sets the private key
discussed earlier.
On line 40, you create a cryptographic object using the CreateEncryptor() method. A call to its
TransformFinalBlock() method does the trick and outputs a variable-length byte array that you store in
the CipherText structure instance on line 43. You save the previously generated vector as well and return
the structure on line 47.
That was simple, right? Now all you have to do is store the CipherText content in the UserProperties
table. But before doing this, let's discuss hashing.
Note This example uses AES, but other algorithms are available with the .NET framework. Because you also
use an initialization vector, running the same code over and over yields different output, given the same input. That
makes the encrypted value harder to crack. The Visual Studio Solution provided includes additional methods to
decrypt data.
Hashing
Hashing isn't nearly as complicated as you've seen so far. And although you can store the values you've
encrypted so far in the database, in this example you hash all the columns of the rows (except the ID
value) to make sure they're unchanged. Why? The answer goes back to the integrity concern of the CIA
triad discussed earlier. You want a way to tell whether your data has been modified outside of your code.
Encrypting your secret value makes it virtually impossible to break the confidentiality aspect of the triad,
but someone can still update the PropertyName column—or, worse, the Value column. Hashing doesn't
prevent data from being modified, but you have a way to detect whether it was changed without your
authorization.
To simplify the code, start by creating a couple of extension methods. Extension methods are a
handy way to extend the methods available to a class (or data type) even if you don't have the original
source code. Here you can see how to declare an extension method on the string and DateTime data
types:
1. public static class Extensions
2. {
3. public static byte[] GetBytes(this string value)
4. {
5. byte[] buffer = UTF8Encoding.UTF8.GetBytes(value);
6. return buffer;
7. }
8.
9. public static byte[] GetBytes(this DateTime value)
10. {
11. return value.ToString().GetBytes();
12. }
13. }
This code adds a GetBytes() method to the string and DateTime data types. You also create a utility
class that allows you to create a hash value based on a collection of byte arrays. The following code
shows that class:
1. public class Util
Search WWH ::




Custom Search