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
{
///
///
///
///
public class ProtectDataConfigurationProvider : ConfigurationProvider
{
private readonly IConfigurationRoot _configurationRoot;
private readonly Func _decryptFunc;
private readonly Func _encryptFunc;
///
/// Initializes a new instance of the class.
///
/// The configuration root.
/// The decrypt function.
/// The encrypt function.
public ProtectDataConfigurationProvider(IConfigurationRoot configurationRoot, Func encryptFunc, Func decryptFunc)
{
_configurationRoot = configurationRoot;
_decryptFunc = decryptFunc;
_encryptFunc = encryptFunc;
}
///
/// Attempts to find a value with the given key, returns true if one is found, false otherwise.
///
/// The key to lookup.
/// The value found at key if one is found.
/// True if key has a value, false otherwise.
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;
}
///
/// Sets a value for a given key.
///
/// The configuration key to set.
/// The value to set.
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));
}
}
}
}
}
}