Advertisement
Guest User

Untitled

a guest
Feb 27th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Security.Cryptography;
  5. using System.Text.RegularExpressions;
  6. using Newtonsoft.Json.Linq;
  7. using Microsoft.Extensions.Configuration;
  8.  
  9. namespace Settings
  10. {
  11. public static class CustomConfigurationExtensions
  12. {
  13. public static IConfigurationBuilder AddEncryptedAndJsonFiles(this IConfigurationBuilder builder, string fileName, string basePath, bool optional, bool reloadOnChange = false)
  14. {
  15. string jsonFilePath = builder.GetFileProvider().GetFileInfo(fileName).PhysicalPath;
  16. var encryptedConfiguration = new EncryptedConfigurationSource(jsonFilePath, basePath);
  17. encryptedConfiguration.UpdateStoredSettings();
  18.  
  19. return builder
  20. .AddJsonFile(fileName, optional, reloadOnChange)
  21. .Add(encryptedConfiguration);
  22. }
  23. }
  24.  
  25. public class EncryptedConfigurationProvider : ConfigurationProvider
  26. {
  27. EncryptedConfigurationSource _source;
  28. public EncryptedConfigurationProvider(EncryptedConfigurationSource source)
  29. {
  30. _source = source;
  31. }
  32.  
  33. public override void Load()
  34. {
  35. if (!File.Exists(_source.JsonFilePath))
  36. return;
  37. var jsonRoot = JObject.Parse(File.ReadAllText(_source.JsonFilePath));
  38. string keyPath = _source.GetEncryptionKeyPath(jsonRoot);
  39. if (String.IsNullOrEmpty(keyPath))
  40. return; // no encryption is to be done on this file
  41. Aes aes = _source.GetEncryptionAlgorithm(keyPath);
  42.  
  43. if(!File.Exists(_source.EncryptedFilePath))
  44. throw new Exception("Encryption file not found at given path.");
  45.  
  46. JObject encJsonRoot = _source.GetEncryptedContents(File.ReadAllBytes(_source.EncryptedFilePath), aes);
  47. foreach (JToken item in new JsonInOrderIterator(encJsonRoot))
  48. {
  49. if (item.Parent.Type != JTokenType.Property)
  50. continue;
  51. var prop = item.Parent as JProperty;
  52. Data[prop.Name] = prop.Value.ToString(); // means that newer values will overwrite older ones.
  53. }
  54. }
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement