12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Primitives;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Security.Cryptography;
- using System.Text;
- using EasyDevCore.Common;
- namespace EasyDevCore.Configuration
- {
- /// <summary>
- ///
- /// </summary>
- /// <seealso cref="Microsoft.Extensions.Configuration.ConfigurationProvider" />
- public class ProtectDataConfigurationProvider : ConfigurationProvider
- {
- private readonly IConfigurationRoot _configurationRoot;
- private readonly Func<string, string, string> _decryptFunc;
- private readonly Func<string, string, string> _encryptFunc;
- /// <summary>
- /// Initializes a new instance of the <see cref="ProtectDataConfigurationProvider" /> class.
- /// </summary>
- /// <param name="configurationRoot">The configuration root.</param>
- /// <param name="decryptFunc">The decrypt function.</param>
- /// <param name="encryptFunc">The encrypt function.</param>
- public ProtectDataConfigurationProvider(IConfigurationRoot configurationRoot, Func<string, string, string> encryptFunc, Func<string, string, string> decryptFunc)
- {
- _configurationRoot = configurationRoot;
- _decryptFunc = decryptFunc;
- _encryptFunc = encryptFunc;
- }
- /// <summary>
- /// Attempts to find a value with the given key, returns true if one is found, false otherwise.
- /// </summary>
- /// <param name="key">The key to lookup.</param>
- /// <param name="value">The value found at key if one is found.</param>
- /// <returns>True if key has a value, false otherwise.</returns>
- public override bool TryGet(string key, out string value)
- {
- try
- {
- foreach (var provider in _configurationRoot.Providers.Reverse())
- {
- if (provider != this)
- {
- if (_decryptFunc != null && provider.TryGet(key, out value))
- {
- if (value != null)
- {
- value = _decryptFunc(key, value);
- }
- }
- }
- }
- }
- catch { }
- value = null;
- return false;
- }
- /// <summary>
- /// Sets a value for a given key.
- /// </summary>
- /// <param name="key">The configuration key to set.</param>
- /// <param name="value">The value to set.</param>
- public override void Set(string key, string value)
- {
- foreach (var provider in _configurationRoot.Providers)
- {
- if (provider != this)
- {
- if (_encryptFunc != null && value != null)
- {
- provider.Set(key, _encryptFunc(key, value));
- }
- }
- }
- }
- }
- }
|