Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Security.Cryptography;
- using System.Text.RegularExpressions;
- using Newtonsoft.Json.Linq;
- using Microsoft.Extensions.Configuration;
- namespace Settings
- {
- public static class CustomConfigurationExtensions
- {
- public static IConfigurationBuilder AddEncryptedAndJsonFiles(this IConfigurationBuilder builder, string fileName, string basePath, bool optional, bool reloadOnChange = false)
- {
- string jsonFilePath = builder.GetFileProvider().GetFileInfo(fileName).PhysicalPath;
- var encryptedConfiguration = new EncryptedConfigurationSource(jsonFilePath, basePath);
- encryptedConfiguration.UpdateStoredSettings();
- return builder
- .AddJsonFile(fileName, optional, reloadOnChange)
- .Add(encryptedConfiguration);
- }
- }
- public class EncryptedConfigurationProvider : ConfigurationProvider
- {
- EncryptedConfigurationSource _source;
- public EncryptedConfigurationProvider(EncryptedConfigurationSource source)
- {
- _source = source;
- }
- public override void Load()
- {
- if (!File.Exists(_source.JsonFilePath))
- return;
- var jsonRoot = JObject.Parse(File.ReadAllText(_source.JsonFilePath));
- string keyPath = _source.GetEncryptionKeyPath(jsonRoot);
- if (String.IsNullOrEmpty(keyPath))
- return; // no encryption is to be done on this file
- Aes aes = _source.GetEncryptionAlgorithm(keyPath);
- if(!File.Exists(_source.EncryptedFilePath))
- throw new Exception("Encryption file not found at given path.");
- JObject encJsonRoot = _source.GetEncryptedContents(File.ReadAllBytes(_source.EncryptedFilePath), aes);
- foreach (JToken item in new JsonInOrderIterator(encJsonRoot))
- {
- if (item.Parent.Type != JTokenType.Property)
- continue;
- var prop = item.Parent as JProperty;
- Data[prop.Name] = prop.Value.ToString(); // means that newer values will overwrite older ones.
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement