Program.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. using System;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Security.Cryptography.X509Certificates;
  7. using Microsoft.AspNetCore.DataProtection;
  8. using Microsoft.Extensions.Configuration;
  9. using Microsoft.Extensions.DependencyInjection;
  10. using Microsoft.Extensions.Logging;
  11. namespace ConsoleApplication
  12. {
  13. public class Program
  14. {
  15. public static void Main(string[] args)
  16. {
  17. var builder = new ConfigurationBuilder();
  18. builder.SetBasePath(Directory.GetCurrentDirectory());
  19. builder.AddJsonFile("settings.json");
  20. var config = builder.Build();
  21. var store = new X509Store(StoreLocation.CurrentUser);
  22. store.Open(OpenFlags.ReadOnly);
  23. var cert = store.Certificates.Find(X509FindType.FindByThumbprint, config["CertificateThumbprint"], false);
  24. var serviceCollection = new ServiceCollection();
  25. serviceCollection.AddLogging(loggingBuilder => loggingBuilder.AddConsole());
  26. serviceCollection.AddDataProtection()
  27. .PersistKeysToFileSystem(new DirectoryInfo("."))
  28. .ProtectKeysWithAzureKeyVault(config["KeyId"], config["ClientId"], cert.OfType<X509Certificate2>().Single());
  29. var serviceProvider = serviceCollection.BuildServiceProvider();
  30. var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
  31. var protector = serviceProvider.GetDataProtector("Test");
  32. Console.WriteLine(protector.Protect("Hello world"));
  33. }
  34. }
  35. }