Program.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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.Runtime.InteropServices;
  6. using Microsoft.AspNetCore.DataProtection;
  7. using Microsoft.AspNetCore.DataProtection.KeyManagement;
  8. using Microsoft.Extensions.DependencyInjection;
  9. namespace KeyManagementSample
  10. {
  11. public class Program
  12. {
  13. public static void Main(string[] args)
  14. {
  15. var keysFolder = Path.Combine(Directory.GetCurrentDirectory(), "temp-keys");
  16. var serviceCollection = new ServiceCollection();
  17. var builder = serviceCollection.AddDataProtection()
  18. // point at a specific folder and use DPAPI to encrypt keys
  19. .PersistKeysToFileSystem(new DirectoryInfo(keysFolder));
  20. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  21. {
  22. builder.ProtectKeysWithDpapi();
  23. }
  24. var services = serviceCollection.BuildServiceProvider();
  25. // perform a protect operation to force the system to put at least
  26. // one key in the key ring
  27. services.GetDataProtector("Sample.KeyManager.v1").Protect("payload");
  28. Console.WriteLine("Performed a protect operation.");
  29. // get a reference to the key manager
  30. var keyManager = services.GetService<IKeyManager>();
  31. // list all keys in the key ring
  32. var allKeys = keyManager.GetAllKeys();
  33. Console.WriteLine($"The key ring contains {allKeys.Count} key(s).");
  34. foreach (var key in allKeys)
  35. {
  36. Console.WriteLine($"Key {key.KeyId:B}: Created = {key.CreationDate:u}, IsRevoked = {key.IsRevoked}");
  37. }
  38. // revoke all keys in the key ring
  39. keyManager.RevokeAllKeys(DateTimeOffset.Now, reason: "Revocation reason here.");
  40. Console.WriteLine("Revoked all existing keys.");
  41. // add a new key to the key ring with immediate activation and a 1-month expiration
  42. keyManager.CreateNewKey(
  43. activationDate: DateTimeOffset.Now,
  44. expirationDate: DateTimeOffset.Now.AddMonths(1));
  45. Console.WriteLine("Added a new key.");
  46. // list all keys in the key ring
  47. allKeys = keyManager.GetAllKeys();
  48. Console.WriteLine($"The key ring contains {allKeys.Count} key(s).");
  49. foreach (var key in allKeys)
  50. {
  51. Console.WriteLine($"Key {key.KeyId:B}: Created = {key.CreationDate:u}, IsRevoked = {key.IsRevoked}");
  52. }
  53. }
  54. }
  55. }