SqlClientSymmetricKey.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //------------------------------------------------------------------------------
  2. // <copyright file="SqlException.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">balnee</owner>
  6. // <owner current="true" primary="false">krishnib</owner>
  7. //------------------------------------------------------------------------------
  8. namespace System.Data.SqlClient
  9. {
  10. using System;
  11. using System.Data.SqlClient;
  12. using System.Security.Cryptography;
  13. /// <summary>
  14. /// Base class containing raw key bytes for symmetric key algorithms. Some encryption algorithms can use the key directly while others derive sub keys from this.
  15. /// If an algorithm needs to derive more keys, have a derived class from this and use it in the corresponding encryption algorithm.
  16. /// </summary>
  17. internal class SqlClientSymmetricKey
  18. {
  19. /// <summary>
  20. /// DPAPI protected key
  21. /// </summary>
  22. protected readonly byte[] _rootKey;
  23. /// <summary>
  24. /// Constructor that initializes the root key.
  25. /// </summary>
  26. /// <param name="rootKey">root key</param>
  27. internal SqlClientSymmetricKey(byte[] rootKey)
  28. {
  29. // Key validation
  30. if (rootKey == null || rootKey.Length == 0) {
  31. throw SQL.NullColumnEncryptionKeySysErr();
  32. }
  33. _rootKey = rootKey;
  34. }
  35. /// <summary>
  36. /// Returns a copy of the plain text key
  37. /// This is needed for actual encryption/decryption.
  38. /// </summary>
  39. internal virtual byte[] RootKey
  40. {
  41. get
  42. {
  43. return _rootKey;
  44. }
  45. }
  46. /// <summary>
  47. /// Computes SHA256 value of the plain text key bytes
  48. /// </summary>
  49. /// <returns>A string containing SHA256 hash of the root key</returns>
  50. internal virtual string GetKeyHash()
  51. {
  52. return SqlSecurityUtility.GetSHA256Hash(RootKey);
  53. }
  54. /// <summary>
  55. /// Gets the length of the root key
  56. /// </summary>
  57. /// <returns>
  58. /// Returns the length of the root key
  59. /// </returns>
  60. internal virtual int Length()
  61. {
  62. // Note: DPAPI preserves the original byte length
  63. // so for now, this is as same as returning the length of the raw key.
  64. return _rootKey.Length;
  65. }
  66. }
  67. }