ProtectDataConfigurationProvider.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using Microsoft.Extensions.Configuration;
  2. using Microsoft.Extensions.Primitives;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using EasyDevCore.Common;
  9. namespace EasyDevCore.Configuration
  10. {
  11. /// <summary>
  12. ///
  13. /// </summary>
  14. /// <seealso cref="Microsoft.Extensions.Configuration.ConfigurationProvider" />
  15. public class ProtectDataConfigurationProvider : ConfigurationProvider
  16. {
  17. private readonly IConfigurationRoot _configurationRoot;
  18. private readonly Func<string, string, string> _decryptFunc;
  19. private readonly Func<string, string, string> _encryptFunc;
  20. /// <summary>
  21. /// Initializes a new instance of the <see cref="ProtectDataConfigurationProvider" /> class.
  22. /// </summary>
  23. /// <param name="configurationRoot">The configuration root.</param>
  24. /// <param name="decryptFunc">The decrypt function.</param>
  25. /// <param name="encryptFunc">The encrypt function.</param>
  26. public ProtectDataConfigurationProvider(IConfigurationRoot configurationRoot, Func<string, string, string> encryptFunc, Func<string, string, string> decryptFunc)
  27. {
  28. _configurationRoot = configurationRoot;
  29. _decryptFunc = decryptFunc;
  30. _encryptFunc = encryptFunc;
  31. }
  32. /// <summary>
  33. /// Attempts to find a value with the given key, returns true if one is found, false otherwise.
  34. /// </summary>
  35. /// <param name="key">The key to lookup.</param>
  36. /// <param name="value">The value found at key if one is found.</param>
  37. /// <returns>True if key has a value, false otherwise.</returns>
  38. public override bool TryGet(string key, out string value)
  39. {
  40. try
  41. {
  42. foreach (var provider in _configurationRoot.Providers.Reverse())
  43. {
  44. if (provider != this)
  45. {
  46. if (_decryptFunc != null && provider.TryGet(key, out value))
  47. {
  48. if (value != null)
  49. {
  50. value = _decryptFunc(key, value);
  51. }
  52. }
  53. }
  54. }
  55. }
  56. catch { }
  57. value = null;
  58. return false;
  59. }
  60. /// <summary>
  61. /// Sets a value for a given key.
  62. /// </summary>
  63. /// <param name="key">The configuration key to set.</param>
  64. /// <param name="value">The value to set.</param>
  65. public override void Set(string key, string value)
  66. {
  67. foreach (var provider in _configurationRoot.Providers)
  68. {
  69. if (provider != this)
  70. {
  71. if (_encryptFunc != null && value != null)
  72. {
  73. provider.Set(key, _encryptFunc(key, value));
  74. }
  75. }
  76. }
  77. }
  78. }
  79. }