Database Reference
In-Depth Information
2. {
3. /// <summary>
4. /// Computes a hash value based on an array of byte arrays
5. /// </summary>
6. /// <param name="bytes">Array of byte arrays</param>
7. public static byte[] ComputeHash(params byte[][] bytes)
8. {
9. SHA256 sha = SHA256Managed.Create();
10. MemoryStream ms = new MemoryStream();
11.
12. for (int i = 0; i < bytes.Length; i++)
13. ms.Write(bytes[i], 0, bytes[i].Length);
14.
15. ms.Flush();
16. ms.Position = 0;
17.
18. return sha.ComputeHash(ms);
19. }
20. }
This Util class is very handy shortly. Note on line 7 the declaration of the variable as params
byte[][] ; this means each parameter passed to this method must be a byte array. You declare a memory
stream, loop on each byte-array variable, and append it to the memory stream on line 13. Finally, you
return the computed hash of the memory stream on line 18. You see how to call this method shortly.
The UserProperties class is next, in the following example, and makes the actual call to the SQL
Azure database. It takes two input parameters: the property name to save and its encrypted value stored
in the CipherText structure. On line 13, you retrieve the connection string from another class and open
the database connection on line 15. You then create the command object, specifying a call to a stored
procedure. The code for the stored procedure is provided later. The hash value is then created on line 39;
as you can see, you call the ComputeHash method just reviewed by passing each stored procedure
parameter as a byte array. This is where you use both the extension methods created earlier and the
hashing method. After the hash result is calculated, you pass it into the last stored procedure parameter
on line 45:
1. using System.Data.SqlDbType;
2. public class UserProperties
3. {
4.
5. /// <summary>
6. /// Saves a property value in a SQL Azure database
7. /// </summary>
8. /// <param name="propertyName">The property name</param>
9. /// <param name="ct">The CipherText structure to save</param>
10. public static void Save(string propertyName, CipherText ct)
11. {
12. using (SqlConnection sqlConn =
13. new SqlConnection(CDatabase.ConnectionString))
14. {
15. sqlConn.Open();
16.
17. using (SqlCommand sqlCmd = new SqlCommand())
18. {
19.
Search WWH ::




Custom Search