Sfoglia il codice sorgente

Enable nullable on DataProtection (#28583)

James Newton-King 5 anni fa
parent
commit
69600972f6
73 ha cambiato i file con 374 aggiunte e 344 eliminazioni
  1. 3 1
      eng/targets/CSharp.Common.targets
  2. 1 1
      src/DataProtection/Abstractions/src/Infrastructure/IApplicationDiscriminator.cs
  3. 1 1
      src/DataProtection/Abstractions/src/PublicAPI.Shipped.txt
  4. 1 1
      src/DataProtection/Cryptography.Internal/src/Cng/CachedAlgorithmHandles.cs
  5. 1 1
      src/DataProtection/Cryptography.Internal/src/Cng/OSVersionUtil.cs
  6. 1 1
      src/DataProtection/Cryptography.Internal/src/Microsoft.AspNetCore.Cryptography.Internal.csproj
  7. 2 2
      src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptAlgorithmHandle.cs
  8. 1 1
      src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHashHandle.cs
  9. 1 1
      src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptKeyHandle.cs
  10. 7 3
      src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs
  11. 5 5
      src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs
  12. 6 7
      src/DataProtection/Cryptography.Internal/src/WeakReferenceHelpers.cs
  13. 3 3
      src/DataProtection/DataProtection/src/ArraySegmentExtensions.cs
  14. 5 3
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/AuthenticatedEncryptorFactory.cs
  15. 7 5
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/CngCbcAuthenticatedEncryptorFactory.cs
  16. 5 3
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/CngGcmAuthenticatedEncryptorFactory.cs
  17. 4 4
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/AuthenticatedEncryptorDescriptorDeserializer.cs
  18. 2 2
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngCbcAuthenticatedEncryptorConfiguration.cs
  19. 8 8
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngCbcAuthenticatedEncryptorDescriptorDeserializer.cs
  20. 1 1
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngGcmAuthenticatedEncryptorConfiguration.cs
  21. 5 5
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngGcmAuthenticatedEncryptorDescriptorDeserializer.cs
  22. 1 1
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/ManagedAuthenticatedEncryptorConfiguration.cs
  23. 1 1
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/ManagedAuthenticatedEncryptorDescriptor.cs
  24. 7 7
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/ManagedAuthenticatedEncryptorDescriptorDeserializer.cs
  25. 2 2
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/IAuthenticatedEncryptorFactory.cs
  26. 9 7
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/ManagedAuthenticatedEncryptorFactory.cs
  27. 1 1
      src/DataProtection/DataProtection/src/Cng/CbcAuthenticatedEncryptor.cs
  28. 1 1
      src/DataProtection/DataProtection/src/Cng/GcmAuthenticatedEncryptor.cs
  29. 1 1
      src/DataProtection/DataProtection/src/DataProtectionOptions.cs
  30. 3 3
      src/DataProtection/DataProtection/src/DataProtectionUtilityExtensions.cs
  31. 7 7
      src/DataProtection/DataProtection/src/EphemeralDataProtectionProvider.cs
  32. 2 2
      src/DataProtection/DataProtection/src/Error.cs
  33. 2 2
      src/DataProtection/DataProtection/src/IRegistryPolicyResolver.cs
  34. 2 2
      src/DataProtection/DataProtection/src/Internal/HostingApplicationDiscriminator.cs
  35. 4 4
      src/DataProtection/DataProtection/src/Internal/KeyManagementOptionsSetup.cs
  36. 1 1
      src/DataProtection/DataProtection/src/KeyManagement/DefaultKeyResolver.cs
  37. 1 1
      src/DataProtection/DataProtection/src/KeyManagement/DeferredKey.cs
  38. 1 1
      src/DataProtection/DataProtection/src/KeyManagement/IKey.cs
  39. 2 1
      src/DataProtection/DataProtection/src/KeyManagement/Internal/CacheableKeyRing.cs
  40. 2 2
      src/DataProtection/DataProtection/src/KeyManagement/Internal/DefaultKeyResolution.cs
  41. 1 1
      src/DataProtection/DataProtection/src/KeyManagement/Internal/IInternalXmlKeyManager.cs
  42. 2 2
      src/DataProtection/DataProtection/src/KeyManagement/Internal/IKeyRing.cs
  43. 2 2
      src/DataProtection/DataProtection/src/KeyManagement/KeyBase.cs
  44. 1 1
      src/DataProtection/DataProtection/src/KeyManagement/KeyEscrowServiceProviderExtensions.cs
  45. 3 3
      src/DataProtection/DataProtection/src/KeyManagement/KeyManagementOptions.cs
  46. 7 9
      src/DataProtection/DataProtection/src/KeyManagement/KeyRing.cs
  47. 15 6
      src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs
  48. 3 3
      src/DataProtection/DataProtection/src/KeyManagement/KeyRingProvider.cs
  49. 40 36
      src/DataProtection/DataProtection/src/KeyManagement/XmlKeyManager.cs
  50. 73 72
      src/DataProtection/DataProtection/src/LoggingExtensions.cs
  51. 3 3
      src/DataProtection/DataProtection/src/LoggingServiceProviderExtensions.cs
  52. 4 4
      src/DataProtection/DataProtection/src/Managed/ManagedAuthenticatedEncryptor.cs
  53. 3 1
      src/DataProtection/DataProtection/src/Microsoft.AspNetCore.DataProtection.csproj
  54. 29 29
      src/DataProtection/DataProtection/src/PublicAPI.Shipped.txt
  55. 3 3
      src/DataProtection/DataProtection/src/RegistryPolicy.cs
  56. 8 8
      src/DataProtection/DataProtection/src/RegistryPolicyResolver.cs
  57. 5 5
      src/DataProtection/DataProtection/src/Repositories/DefaultKeyStorageDirectories.cs
  58. 1 1
      src/DataProtection/DataProtection/src/Repositories/FileSystemXmlRepository.cs
  59. 3 3
      src/DataProtection/DataProtection/src/Repositories/IDefaultKeyStorageDirectory.cs
  60. 6 6
      src/DataProtection/DataProtection/src/Repositories/RegistryXmlRepository.cs
  61. 4 4
      src/DataProtection/DataProtection/src/SP800_108/ManagedSP800_108_CTR_HMACSHA512.cs
  62. 1 1
      src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Extensions.cs
  63. 6 6
      src/DataProtection/DataProtection/src/SimpleActivator.cs
  64. 2 2
      src/DataProtection/DataProtection/src/XmlEncryption/CertificateResolver.cs
  65. 4 3
      src/DataProtection/DataProtection/src/XmlEncryption/CertificateXmlEncryptor.cs
  66. 3 3
      src/DataProtection/DataProtection/src/XmlEncryption/DpapiNGXmlDecryptor.cs
  67. 1 1
      src/DataProtection/DataProtection/src/XmlEncryption/DpapiNGXmlEncryptor.cs
  68. 2 2
      src/DataProtection/DataProtection/src/XmlEncryption/DpapiXmlDecryptor.cs
  69. 11 11
      src/DataProtection/DataProtection/src/XmlEncryption/EncryptedXmlDecryptor.cs
  70. 1 1
      src/DataProtection/DataProtection/src/XmlEncryption/ICertificateResolver.cs
  71. 1 1
      src/DataProtection/DataProtection/src/XmlEncryption/NullXmlEncryptor.cs
  72. 4 4
      src/DataProtection/DataProtection/src/XmlEncryption/XmlEncryptionExtensions.cs
  73. 2 1
      src/DataProtection/DataProtection/src/XmlEncryption/XmlKeyDecryptionOptions.cs

+ 3 - 1
eng/targets/CSharp.Common.targets

@@ -77,8 +77,10 @@
         by compiling the annotations (as internal types).
         The code block that follows sets it up so projects in this repo that target ns2.0 or netfx can compile when Nullable is configured.
         Based on https://github.com/dotnet/runtime/blob/93b6c449d4f31ddd7d573d1d3769e681d5ebceb9/src/libraries/Directory.Build.targets#L215-L222
+
+        SuppressNullableAttributesImport to disable. Used when attributes are already present from another project because of InternalsVisibleTo.
      -->
-    <When Condition="'$(Nullable)' != '' AND ('$(TargetFrameworkIdentifier)' == '.NETStandard' OR '$(TargetFrameworkIdentifier)' == '.NETFramework')">
+    <When Condition="'$(Nullable)' != '' AND '$(SuppressNullableAttributesImport)' != 'true' AND ('$(TargetFrameworkIdentifier)' == '.NETStandard' OR '$(TargetFrameworkIdentifier)' == '.NETFramework')">
       <PropertyGroup>
         <DefineConstants>$(DefineConstants),INTERNAL_NULLABLE_ATTRIBUTES</DefineConstants>
         <NoWarn>$(NoWarn);nullable</NoWarn>

+ 1 - 1
src/DataProtection/Abstractions/src/Infrastructure/IApplicationDiscriminator.cs

@@ -20,6 +20,6 @@ namespace Microsoft.AspNetCore.DataProtection.Infrastructure
         /// An identifier that uniquely discriminates this application from all other
         /// applications on the machine.
         /// </summary>
-        string Discriminator { get; }
+        string? Discriminator { get; }
     }
 }

+ 1 - 1
src/DataProtection/Abstractions/src/PublicAPI.Shipped.txt

@@ -6,7 +6,7 @@ Microsoft.AspNetCore.DataProtection.IDataProtector
 Microsoft.AspNetCore.DataProtection.IDataProtector.Protect(byte[]! plaintext) -> byte[]!
 Microsoft.AspNetCore.DataProtection.IDataProtector.Unprotect(byte[]! protectedData) -> byte[]!
 Microsoft.AspNetCore.DataProtection.Infrastructure.IApplicationDiscriminator
-Microsoft.AspNetCore.DataProtection.Infrastructure.IApplicationDiscriminator.Discriminator.get -> string!
+Microsoft.AspNetCore.DataProtection.Infrastructure.IApplicationDiscriminator.Discriminator.get -> string?
 static Microsoft.AspNetCore.DataProtection.DataProtectionCommonExtensions.CreateProtector(this Microsoft.AspNetCore.DataProtection.IDataProtectionProvider! provider, System.Collections.Generic.IEnumerable<string!>! purposes) -> Microsoft.AspNetCore.DataProtection.IDataProtector!
 static Microsoft.AspNetCore.DataProtection.DataProtectionCommonExtensions.CreateProtector(this Microsoft.AspNetCore.DataProtection.IDataProtectionProvider! provider, string! purpose, params string![]! subPurposes) -> Microsoft.AspNetCore.DataProtection.IDataProtector!
 static Microsoft.AspNetCore.DataProtection.DataProtectionCommonExtensions.GetDataProtectionProvider(this System.IServiceProvider! services) -> Microsoft.AspNetCore.DataProtection.IDataProtectionProvider!

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/Cng/CachedAlgorithmHandles.cs

@@ -75,7 +75,7 @@ namespace Microsoft.AspNetCore.Cryptography.Cng
         // Warning: mutable struct!
         private struct CachedAlgorithmInfo
         {
-            private WeakReference<BCryptAlgorithmHandle> _algorithmHandle;
+            private WeakReference<BCryptAlgorithmHandle>? _algorithmHandle;
             private readonly Func<BCryptAlgorithmHandle> _factory;
 
             public CachedAlgorithmInfo(Func<BCryptAlgorithmHandle> factory)

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/Cng/OSVersionUtil.cs

@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Cryptography.Cng
         private static OSVersion GetOSVersion()
         {
             const string BCRYPT_LIB = "bcrypt.dll";
-            SafeLibraryHandle bcryptLibHandle = null;
+            SafeLibraryHandle? bcryptLibHandle = null;
             try
             {
                 bcryptLibHandle = SafeLibraryHandle.Open(BCRYPT_LIB);

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/Microsoft.AspNetCore.Cryptography.Internal.csproj

@@ -7,7 +7,7 @@
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <GenerateDocumentationFile>true</GenerateDocumentationFile>
     <PackageTags>aspnetcore;dataprotection</PackageTags>
-    <Nullable>annotations</Nullable>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
 
 </Project>

+ 2 - 2
src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptAlgorithmHandle.cs

@@ -130,7 +130,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles
             return digestLength;
         }
 
-        public static BCryptAlgorithmHandle OpenAlgorithmHandle(string algorithmId, string implementation = null, bool hmac = false)
+        public static BCryptAlgorithmHandle OpenAlgorithmHandle(string algorithmId, string? implementation = null, bool hmac = false)
         {
             // from bcrypt.h
             const uint BCRYPT_ALG_HANDLE_HMAC_FLAG = 0x00000008;
@@ -161,7 +161,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles
 
         public void SetChainingMode(string chainingMode)
         {
-            fixed (char* pszChainingMode = chainingMode ?? String.Empty)
+            fixed (char* pszChainingMode = chainingMode)
             {
                 SetProperty(Constants.BCRYPT_CHAINING_MODE, pszChainingMode, checked((uint)(chainingMode.Length + 1 /* null terminator */) * sizeof(char)));
             }

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHashHandle.cs

@@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles
 {
     internal unsafe sealed class BCryptHashHandle : BCryptHandle
     {
-        private BCryptAlgorithmHandle _algProviderHandle;
+        private BCryptAlgorithmHandle? _algProviderHandle;
 
         // Called by P/Invoke when returning SafeHandles
         private BCryptHashHandle() { }

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptKeyHandle.cs

@@ -7,7 +7,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles
 {
     internal sealed class BCryptKeyHandle : BCryptHandle
     {
-        private BCryptAlgorithmHandle _algProviderHandle;
+        private BCryptAlgorithmHandle? _algProviderHandle;
 
         // Called by P/Invoke when returning SafeHandles
         private BCryptKeyHandle() { }

+ 7 - 3
src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs

@@ -2,6 +2,7 @@
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 using System;
+using System.Diagnostics.CodeAnalysis;
 using System.Runtime.ConstrainedExecution;
 using System.Runtime.InteropServices;
 using System.Security;
@@ -49,7 +50,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles
         /// <summary>
         /// Formats a message string using the resource table in the specified library.
         /// </summary>
-        public string FormatMessage(int messageId)
+        public string? FormatMessage(int messageId)
         {
             // from winbase.h
             const uint FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
@@ -72,7 +73,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles
                 // Successfully retrieved the message.
                 using (messageHandle)
                 {
-                    return new String((char*)messageHandle.DangerousGetHandle(), 0, numCharsOutput).Trim();
+                    return new string((char*)messageHandle.DangerousGetHandle(), 0, numCharsOutput).Trim();
                 }
             }
             else
@@ -85,7 +86,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles
         /// <summary>
         /// Gets a delegate pointing to a given export from this library.
         /// </summary>
-        public TDelegate GetProcAddress<TDelegate>(string lpProcName, bool throwIfNotFound = true) where TDelegate : class
+        public TDelegate? GetProcAddress<TDelegate>(string lpProcName, bool throwIfNotFound = true) where TDelegate : class
         {
             IntPtr pfnProc = UnsafeNativeMethods.GetProcAddress(this, lpProcName);
             if (pfnProc == IntPtr.Zero)
@@ -168,11 +169,14 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles
                 [In] IntPtr hFile,
                 [In] uint dwFlags);
 
+#pragma warning disable CS8763 // A method marked [DoesNotReturn] should not return.
+            [DoesNotReturn]
             internal static void ThrowExceptionForLastWin32Error()
             {
                 int hr = Marshal.GetHRForLastWin32Error();
                 Marshal.ThrowExceptionForHR(hr);
             }
+#pragma warning restore CS8763 // A method marked [DoesNotReturn] should not return.
         }
     }
 }

+ 5 - 5
src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs

@@ -180,7 +180,7 @@ namespace Microsoft.AspNetCore.Cryptography
         internal static extern int BCryptOpenAlgorithmProvider(
             [Out] out BCryptAlgorithmHandle phAlgorithm,
             [In, MarshalAs(UnmanagedType.LPWStr)] string pszAlgId,
-            [In, MarshalAs(UnmanagedType.LPWStr)] string pszImplementation,
+            [In, MarshalAs(UnmanagedType.LPWStr)] string? pszImplementation,
             [In] uint dwFlags);
 
         [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)]
@@ -319,16 +319,16 @@ namespace Microsoft.AspNetCore.Cryptography
         [MethodImpl(MethodImplOptions.NoInlining)]
         private static void ThrowExceptionForBCryptStatusImpl(int ntstatus)
         {
-            string message = _lazyBCryptLibHandle.Value.FormatMessage(ntstatus);
+            var message = _lazyBCryptLibHandle.Value.FormatMessage(ntstatus);
             throw new CryptographicException(message);
         }
 
         public static void ThrowExceptionForLastCrypt32Error()
         {
-            int lastError = Marshal.GetLastWin32Error();
+            var lastError = Marshal.GetLastWin32Error();
             Debug.Assert(lastError != 0, "This method should only be called if there was an error.");
 
-            string message = _lazyCrypt32LibHandle.Value.FormatMessage(lastError);
+            var message = _lazyCrypt32LibHandle.Value.FormatMessage(lastError);
             throw new CryptographicException(message);
         }
 
@@ -345,7 +345,7 @@ namespace Microsoft.AspNetCore.Cryptography
         [MethodImpl(MethodImplOptions.NoInlining)]
         private static void ThrowExceptionForNCryptStatusImpl(int ntstatus)
         {
-            string message = _lazyNCryptLibHandle.Value.FormatMessage(ntstatus);
+            var message = _lazyNCryptLibHandle.Value.FormatMessage(ntstatus);
             throw new CryptographicException(message);
         }
     }

+ 6 - 7
src/DataProtection/Cryptography.Internal/src/WeakReferenceHelpers.cs

@@ -9,20 +9,19 @@ namespace Microsoft.AspNetCore.Cryptography
 {
     internal static class WeakReferenceHelpers
     {
-        public static T GetSharedInstance<T>(ref WeakReference<T> weakReference, Func<T> factory)
+        public static T GetSharedInstance<T>(ref WeakReference<T>? weakReference, Func<T> factory)
             where T : class, IDisposable
         {
             // First, see if the WR already exists and points to a live object.
-            WeakReference<T> existingWeakRef = Volatile.Read(ref weakReference);
-            T newTarget = null;
-            WeakReference<T> newWeakRef = null;
+            WeakReference<T>? existingWeakRef = Volatile.Read(ref weakReference);
+            T? newTarget = null;
+            WeakReference<T>? newWeakRef = null;
 
             while (true)
             {
                 if (existingWeakRef != null)
                 {
-                    T existingTarget;
-                    if (weakReference.TryGetTarget(out existingTarget))
+                    if (weakReference!.TryGetTarget(out var existingTarget))
                     {
                         // If we created a new target on a previous iteration of the loop but we
                         // weren't able to store the target into the desired location, dispose of it now.
@@ -42,7 +41,7 @@ namespace Microsoft.AspNetCore.Cryptography
                 Debug.Assert(newWeakRef != null);
 
                 // Try replacing the existing WR with our newly-created one.
-                WeakReference<T> currentWeakRef = Interlocked.CompareExchange(ref weakReference, newWeakRef, existingWeakRef);
+                WeakReference<T>? currentWeakRef = Interlocked.CompareExchange(ref weakReference, newWeakRef, existingWeakRef);
                 if (ReferenceEquals(currentWeakRef, existingWeakRef))
                 {
                     // success, 'weakReference' now points to our newly-created WR

+ 3 - 3
src/DataProtection/DataProtection/src/ArraySegmentExtensions.cs

@@ -10,13 +10,13 @@ namespace Microsoft.AspNetCore.DataProtection
         public static byte[] AsStandaloneArray(this ArraySegment<byte> arraySegment)
         {
             // Fast-track: Don't need to duplicate the array.
-            if (arraySegment.Offset == 0 && arraySegment.Count == arraySegment.Array.Length)
+            if (arraySegment.Offset == 0 && arraySegment.Count == arraySegment.Array!.Length)
             {
                 return arraySegment.Array;
             }
 
             var retVal = new byte[arraySegment.Count];
-            Buffer.BlockCopy(arraySegment.Array, arraySegment.Offset, retVal, 0, retVal.Length);
+            Buffer.BlockCopy(arraySegment.Array!, arraySegment.Offset, retVal, 0, retVal.Length);
             return retVal;
         }
 
@@ -24,7 +24,7 @@ namespace Microsoft.AspNetCore.DataProtection
         {
             // Since ArraySegment<T> is a struct, it can be improperly initialized or torn.
             // We call the ctor again to make sure the instance data is valid.
-            var unused = new ArraySegment<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
+            var unused = new ArraySegment<T>(arraySegment.Array!, arraySegment.Offset, arraySegment.Count);
         }
     }
 }

+ 5 - 3
src/DataProtection/DataProtection/src/AuthenticatedEncryption/AuthenticatedEncryptorFactory.cs

@@ -3,6 +3,7 @@
 
 using System;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Runtime.InteropServices;
 using System.Security.Cryptography;
 using Microsoft.AspNetCore.Cryptography;
@@ -26,7 +27,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
             _loggerFactory = loggerFactory;
         }
 
-        public IAuthenticatedEncryptor CreateEncryptorInstance(IKey key)
+        public IAuthenticatedEncryptor? CreateEncryptorInstance(IKey key)
         {
             var descriptor = key.Descriptor as AuthenticatedEncryptorDescriptor;
             if (descriptor == null)
@@ -37,9 +38,10 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
             return CreateAuthenticatedEncryptorInstance(descriptor.MasterKey, descriptor.Configuration);
         }
 
-        internal IAuthenticatedEncryptor CreateAuthenticatedEncryptorInstance(
+        [return: NotNullIfNotNull("authenticatedConfiguration")]
+        internal IAuthenticatedEncryptor? CreateAuthenticatedEncryptorInstance(
             ISecret secret,
-            AuthenticatedEncryptorConfiguration authenticatedConfiguration)
+            AuthenticatedEncryptorConfiguration? authenticatedConfiguration)
         {
             if (authenticatedConfiguration == null)
             {

+ 7 - 5
src/DataProtection/DataProtection/src/AuthenticatedEncryption/CngCbcAuthenticatedEncryptorFactory.cs

@@ -3,6 +3,7 @@
 
 using System;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Runtime.InteropServices;
 using System.Runtime.Versioning;
 using Microsoft.AspNetCore.Cryptography;
@@ -27,7 +28,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
             _logger = loggerFactory.CreateLogger<CngCbcAuthenticatedEncryptorFactory>();
         }
 
-        public IAuthenticatedEncryptor CreateEncryptorInstance(IKey key)
+        public IAuthenticatedEncryptor? CreateEncryptorInstance(IKey key)
         {
             var descriptor = key.Descriptor as CngCbcAuthenticatedEncryptorDescriptor;
             if (descriptor == null)
@@ -40,9 +41,10 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
         }
 
         [SupportedOSPlatform("windows")]
-        internal CbcAuthenticatedEncryptor CreateAuthenticatedEncryptorInstance(
+        [return: NotNullIfNotNull("configuration")]
+        internal CbcAuthenticatedEncryptor? CreateAuthenticatedEncryptorInstance(
             ISecret secret,
-            CngCbcAuthenticatedEncryptorConfiguration configuration)
+            CngCbcAuthenticatedEncryptorConfiguration? configuration)
         {
             if (configuration == null)
             {
@@ -66,7 +68,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
             }
 
             _logger.OpeningCNGAlgorithmFromProviderWithHMAC(configuration.HashAlgorithm, configuration.HashAlgorithmProvider);
-            BCryptAlgorithmHandle algorithmHandle = null;
+            BCryptAlgorithmHandle? algorithmHandle = null;
 
             // Special-case cached providers
             if (configuration.HashAlgorithmProvider == null)
@@ -105,7 +107,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
 
             _logger.OpeningCNGAlgorithmFromProviderWithChainingModeCBC(configuration.EncryptionAlgorithm, configuration.EncryptionAlgorithmProvider);
 
-            BCryptAlgorithmHandle algorithmHandle = null;
+            BCryptAlgorithmHandle? algorithmHandle = null;
 
             // Special-case cached providers
             if (configuration.EncryptionAlgorithmProvider == null)

+ 5 - 3
src/DataProtection/DataProtection/src/AuthenticatedEncryption/CngGcmAuthenticatedEncryptorFactory.cs

@@ -3,6 +3,7 @@
 
 using System;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Runtime.InteropServices;
 using System.Runtime.Versioning;
 using Microsoft.AspNetCore.Cryptography;
@@ -27,7 +28,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
             _logger = loggerFactory.CreateLogger<CngGcmAuthenticatedEncryptorFactory>();
         }
 
-        public IAuthenticatedEncryptor CreateEncryptorInstance(IKey key)
+        public IAuthenticatedEncryptor? CreateEncryptorInstance(IKey key)
         {
             var descriptor = key.Descriptor as CngGcmAuthenticatedEncryptorDescriptor;
             if (descriptor == null)
@@ -41,7 +42,8 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
         }
 
         [SupportedOSPlatform("windows")]
-        internal GcmAuthenticatedEncryptor CreateAuthenticatedEncryptorInstance(
+        [return: NotNullIfNotNull("configuration")]
+        internal GcmAuthenticatedEncryptor? CreateAuthenticatedEncryptorInstance(
             ISecret secret,
             CngGcmAuthenticatedEncryptorConfiguration configuration)
         {
@@ -69,7 +71,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
                 throw Error.Common_PropertyMustBeNonNegative(nameof(configuration.EncryptionAlgorithmKeySize));
             }
 
-            BCryptAlgorithmHandle algorithmHandle = null;
+            BCryptAlgorithmHandle? algorithmHandle = null;
 
             _logger.OpeningCNGAlgorithmFromProviderWithChainingModeGCM(configuration.EncryptionAlgorithm, configuration.EncryptionAlgorithmProvider);
             // Special-case cached providers

+ 4 - 4
src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/AuthenticatedEncryptorDescriptorDeserializer.cs

@@ -31,14 +31,14 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.Configurat
 
             var configuration = new AuthenticatedEncryptorConfiguration();
 
-            var encryptionElement = element.Element("encryption");
-            configuration.EncryptionAlgorithm = (EncryptionAlgorithm)Enum.Parse(typeof(EncryptionAlgorithm), (string)encryptionElement.Attribute("algorithm"));
+            var encryptionElement = element.Element("encryption")!;
+            configuration.EncryptionAlgorithm = (EncryptionAlgorithm)Enum.Parse(typeof(EncryptionAlgorithm), (string)encryptionElement.Attribute("algorithm")!);
 
             // only read <validation> if not GCM
             if (!AuthenticatedEncryptorFactory.IsGcmAlgorithm(configuration.EncryptionAlgorithm))
             {
-                var validationElement = element.Element("validation");
-                configuration.ValidationAlgorithm = (ValidationAlgorithm)Enum.Parse(typeof(ValidationAlgorithm), (string)validationElement.Attribute("algorithm"));
+                var validationElement = element.Element("validation")!;
+                configuration.ValidationAlgorithm = (ValidationAlgorithm)Enum.Parse(typeof(ValidationAlgorithm), (string)validationElement.Attribute("algorithm")!);
             }
 
             Secret masterKey = ((string)element.Elements("masterKey").Single()).ToSecret();

+ 2 - 2
src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngCbcAuthenticatedEncryptorConfiguration.cs

@@ -36,7 +36,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.Configurat
         /// The default value is null.
         /// </remarks>
         [ApplyPolicy]
-        public string EncryptionAlgorithmProvider { get; set; } = null;
+        public string? EncryptionAlgorithmProvider { get; set; } = null;
 
         /// <summary>
         /// The length (in bits) of the key that will be used for symmetric encryption.
@@ -71,7 +71,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.Configurat
         /// The default value is null.
         /// </remarks>
         [ApplyPolicy]
-        public string HashAlgorithmProvider { get; set; } = null;
+        public string? HashAlgorithmProvider { get; set; } = null;
 
         public override IAuthenticatedEncryptorDescriptor CreateNewDescriptor()
         {

+ 8 - 8
src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngCbcAuthenticatedEncryptorDescriptorDeserializer.cs

@@ -33,16 +33,16 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.Configurat
 
             var configuration = new CngCbcAuthenticatedEncryptorConfiguration();
 
-            var encryptionElement = element.Element("encryption");
-            configuration.EncryptionAlgorithm = (string)encryptionElement.Attribute("algorithm");
-            configuration.EncryptionAlgorithmKeySize = (int)encryptionElement.Attribute("keyLength");
-            configuration.EncryptionAlgorithmProvider = (string)encryptionElement.Attribute("provider"); // could be null
+            var encryptionElement = element.Element("encryption")!;
+            configuration.EncryptionAlgorithm = (string)encryptionElement.Attribute("algorithm")!;
+            configuration.EncryptionAlgorithmKeySize = (int)encryptionElement.Attribute("keyLength")!;
+            configuration.EncryptionAlgorithmProvider = (string?)encryptionElement.Attribute("provider"); // could be null
 
-            var hashElement = element.Element("hash");
-            configuration.HashAlgorithm = (string)hashElement.Attribute("algorithm");
-            configuration.HashAlgorithmProvider = (string)hashElement.Attribute("provider"); // could be null
+            var hashElement = element.Element("hash")!;
+            configuration.HashAlgorithm = (string)hashElement.Attribute("algorithm")!;
+            configuration.HashAlgorithmProvider = (string?)hashElement.Attribute("provider"); // could be null
 
-            Secret masterKey = ((string)element.Element("masterKey")).ToSecret();
+            Secret masterKey = ((string)element.Element("masterKey"))!.ToSecret();
 
             return new CngCbcAuthenticatedEncryptorDescriptor(configuration, masterKey);
         }

+ 1 - 1
src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngGcmAuthenticatedEncryptorConfiguration.cs

@@ -36,7 +36,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.Configurat
         /// The default value is null.
         /// </remarks>
         [ApplyPolicy]
-        public string EncryptionAlgorithmProvider { get; set; } = null;
+        public string? EncryptionAlgorithmProvider { get; set; } = null;
 
         /// <summary>
         /// The length (in bits) of the key that will be used for symmetric encryption.

+ 5 - 5
src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngGcmAuthenticatedEncryptorDescriptorDeserializer.cs

@@ -33,12 +33,12 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.Configurat
 
             var configuration = new CngGcmAuthenticatedEncryptorConfiguration();
 
-            var encryptionElement = element.Element("encryption");
-            configuration.EncryptionAlgorithm = (string)encryptionElement.Attribute("algorithm");
-            configuration.EncryptionAlgorithmKeySize = (int)encryptionElement.Attribute("keyLength");
-            configuration.EncryptionAlgorithmProvider = (string)encryptionElement.Attribute("provider"); // could be null
+            var encryptionElement = element.Element("encryption")!;
+            configuration.EncryptionAlgorithm = (string)encryptionElement.Attribute("algorithm")!;
+            configuration.EncryptionAlgorithmKeySize = (int)encryptionElement.Attribute("keyLength")!;
+            configuration.EncryptionAlgorithmProvider = (string?)encryptionElement.Attribute("provider"); // could be null
 
-            Secret masterKey = ((string)element.Element("masterKey")).ToSecret();
+            Secret masterKey = ((string)element.Element("masterKey")!).ToSecret();
 
             return new CngGcmAuthenticatedEncryptorDescriptor(configuration, masterKey);
         }

+ 1 - 1
src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/ManagedAuthenticatedEncryptorConfiguration.cs

@@ -101,7 +101,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.Configurat
             }
             else
             {
-                return type.AssemblyQualifiedName;
+                return type.AssemblyQualifiedName!;
             }
         }
     }

+ 1 - 1
src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/ManagedAuthenticatedEncryptorDescriptor.cs

@@ -84,7 +84,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.Configurat
             }
             else
             {
-                return type.AssemblyQualifiedName;
+                return type.AssemblyQualifiedName!;
             }
         }
     }

+ 7 - 7
src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/ManagedAuthenticatedEncryptorDescriptorDeserializer.cs

@@ -32,14 +32,14 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.Configurat
 
             var configuration = new ManagedAuthenticatedEncryptorConfiguration();
 
-            var encryptionElement = element.Element("encryption");
-            configuration.EncryptionAlgorithmType = FriendlyNameToType((string)encryptionElement.Attribute("algorithm"));
-            configuration.EncryptionAlgorithmKeySize = (int)encryptionElement.Attribute("keyLength");
+            var encryptionElement = element.Element("encryption")!;
+            configuration.EncryptionAlgorithmType = FriendlyNameToType((string)encryptionElement.Attribute("algorithm")!);
+            configuration.EncryptionAlgorithmKeySize = (int)encryptionElement.Attribute("keyLength")!;
 
-            var validationElement = element.Element("validation");
-            configuration.ValidationAlgorithmType = FriendlyNameToType((string)validationElement.Attribute("algorithm"));
+            var validationElement = element.Element("validation")!;
+            configuration.ValidationAlgorithmType = FriendlyNameToType((string)validationElement.Attribute("algorithm")!);
 
-            Secret masterKey = ((string)element.Element("masterKey")).ToSecret();
+            Secret masterKey = ((string)element.Element("masterKey")!).ToSecret();
 
             return new ManagedAuthenticatedEncryptorDescriptor(configuration, masterKey);
         }
@@ -70,7 +70,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.Configurat
             }
             else
             {
-                return Type.GetType(typeName, throwOnError: true);
+                return Type.GetType(typeName, throwOnError: true)!;
             }
         }
     }

+ 2 - 2
src/DataProtection/DataProtection/src/AuthenticatedEncryption/IAuthenticatedEncryptorFactory.cs

@@ -1,4 +1,4 @@
-// Copyright (c) .NET Foundation. All rights reserved.
+// Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 using System;
@@ -17,6 +17,6 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
         /// be considered equivalent, e.g., the payload returned by one's <see cref="IAuthenticatedEncryptor.Encrypt(ArraySegment{byte}, ArraySegment{byte})"/>
         /// method should be consumable by the other's <see cref="IAuthenticatedEncryptor.Decrypt(ArraySegment{byte}, ArraySegment{byte})"/> method.
         /// </remarks>
-        IAuthenticatedEncryptor CreateEncryptorInstance(IKey key);
+        IAuthenticatedEncryptor? CreateEncryptorInstance(IKey key);
     }
 }

+ 9 - 7
src/DataProtection/DataProtection/src/AuthenticatedEncryption/ManagedAuthenticatedEncryptorFactory.cs

@@ -2,6 +2,7 @@
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 using System;
+using System.Diagnostics.CodeAnalysis;
 using System.Security.Cryptography;
 using Microsoft.AspNetCore.Cryptography.Cng;
 using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;
@@ -23,7 +24,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
             _logger = loggerFactory.CreateLogger<ManagedAuthenticatedEncryptorFactory>();
         }
 
-        public IAuthenticatedEncryptor CreateEncryptorInstance(IKey key)
+        public IAuthenticatedEncryptor? CreateEncryptorInstance(IKey key)
         {
             var descriptor = key.Descriptor as ManagedAuthenticatedEncryptorDescriptor;
             if (descriptor == null)
@@ -34,9 +35,10 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
             return CreateAuthenticatedEncryptorInstance(descriptor.MasterKey, descriptor.Configuration);
         }
 
-        internal ManagedAuthenticatedEncryptor CreateAuthenticatedEncryptorInstance(
+        [return: NotNullIfNotNull("configuration")]
+        internal ManagedAuthenticatedEncryptor? CreateAuthenticatedEncryptorInstance(
             ISecret secret,
-            ManagedAuthenticatedEncryptorConfiguration configuration)
+            ManagedAuthenticatedEncryptorConfiguration? configuration)
         {
             if (configuration == null)
             {
@@ -58,7 +60,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
                 throw Error.Common_PropertyCannotBeNullOrEmpty(nameof(configuration.ValidationAlgorithmType));
             }
 
-            _logger.UsingManagedKeyedHashAlgorithm(configuration.ValidationAlgorithmType.FullName);
+            _logger.UsingManagedKeyedHashAlgorithm(configuration.ValidationAlgorithmType.FullName!);
             if (configuration.ValidationAlgorithmType == typeof(HMACSHA256))
             {
                 return () => new HMACSHA256();
@@ -86,11 +88,11 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
                 throw Error.Common_PropertyMustBeNonNegative(nameof(configuration.EncryptionAlgorithmKeySize));
             }
 
-            _logger.UsingManagedSymmetricAlgorithm(configuration.EncryptionAlgorithmType.FullName);
+            _logger.UsingManagedSymmetricAlgorithm(configuration.EncryptionAlgorithmType.FullName!);
 
             if (configuration.EncryptionAlgorithmType == typeof(Aes))
             {
-                Func<Aes> factory = null;
+                Func<Aes>? factory = null;
                 if (OSVersionUtil.IsWindows())
                 {
                     // If we're on desktop CLR and running on Windows, use the FIPS-compliant implementation.
@@ -115,7 +117,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
             /// </summary>
             public static Func<T> CreateFactory<T>(Type implementation)
             {
-                return ((IActivator<T>)Activator.CreateInstance(typeof(AlgorithmActivatorCore<>).MakeGenericType(implementation))).Creator;
+                return ((IActivator<T>)Activator.CreateInstance(typeof(AlgorithmActivatorCore<>).MakeGenericType(implementation))!).Creator;
             }
 
             private interface IActivator<out T>

+ 1 - 1
src/DataProtection/DataProtection/src/Cng/CbcAuthenticatedEncryptor.cs

@@ -37,7 +37,7 @@ namespace Microsoft.AspNetCore.DataProtection.Cng
         private readonly uint _symmetricAlgorithmBlockSizeInBytes;
         private readonly uint _symmetricAlgorithmSubkeyLengthInBytes;
 
-        public CbcAuthenticatedEncryptor(Secret keyDerivationKey, BCryptAlgorithmHandle symmetricAlgorithmHandle, uint symmetricAlgorithmKeySizeInBytes, BCryptAlgorithmHandle hmacAlgorithmHandle, IBCryptGenRandom genRandom = null)
+        public CbcAuthenticatedEncryptor(Secret keyDerivationKey, BCryptAlgorithmHandle symmetricAlgorithmHandle, uint symmetricAlgorithmKeySizeInBytes, BCryptAlgorithmHandle hmacAlgorithmHandle, IBCryptGenRandom? genRandom = null)
         {
             _genRandom = genRandom ?? BCryptGenRandomImpl.Instance;
             _sp800_108_ctr_hmac_provider = SP800_108_CTR_HMACSHA512Util.CreateProvider(keyDerivationKey);

+ 1 - 1
src/DataProtection/DataProtection/src/Cng/GcmAuthenticatedEncryptor.cs

@@ -38,7 +38,7 @@ namespace Microsoft.AspNetCore.DataProtection.Cng
         private readonly BCryptAlgorithmHandle _symmetricAlgorithmHandle;
         private readonly uint _symmetricAlgorithmSubkeyLengthInBytes;
 
-        public GcmAuthenticatedEncryptor(Secret keyDerivationKey, BCryptAlgorithmHandle symmetricAlgorithmHandle, uint symmetricAlgorithmKeySizeInBytes, IBCryptGenRandom genRandom = null)
+        public GcmAuthenticatedEncryptor(Secret keyDerivationKey, BCryptAlgorithmHandle symmetricAlgorithmHandle, uint symmetricAlgorithmKeySizeInBytes, IBCryptGenRandom? genRandom = null)
         {
             // Is the key size appropriate?
             AlgorithmAssert.IsAllowableSymmetricAlgorithmKeySize(checked(symmetricAlgorithmKeySizeInBytes * 8));

+ 1 - 1
src/DataProtection/DataProtection/src/DataProtectionOptions.cs

@@ -20,6 +20,6 @@ namespace Microsoft.AspNetCore.DataProtection
         /// If two different applications need to share protected payloads, they should
         /// ensure that this property is set to the same value across both applications.
         /// </remarks>
-        public string ApplicationDiscriminator { get; set; }
+        public string? ApplicationDiscriminator { get; set; }
     }
 }

+ 3 - 3
src/DataProtection/DataProtection/src/DataProtectionUtilityExtensions.cs

@@ -1,4 +1,4 @@
-// Copyright (c) .NET Foundation. All rights reserved.
+// Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 using System;
@@ -30,9 +30,9 @@ namespace Microsoft.AspNetCore.DataProtection
         /// </para>
         /// </remarks>
         [EditorBrowsable(EditorBrowsableState.Never)]
-        public static string GetApplicationUniqueIdentifier(this IServiceProvider services)
+        public static string? GetApplicationUniqueIdentifier(this IServiceProvider services)
         {
-            string discriminator = null;
+            string? discriminator = null;
             if (services != null)
             {
                 discriminator = services.GetService<IApplicationDiscriminator>()?.Discriminator;

+ 7 - 7
src/DataProtection/DataProtection/src/EphemeralDataProtectionProvider.cs

@@ -84,11 +84,11 @@ namespace Microsoft.AspNetCore.DataProtection
             // Currently hardcoded to a 512-bit KDK.
             private const int NUM_BYTES_IN_KDK = 512 / 8;
 
-            public IAuthenticatedEncryptor DefaultAuthenticatedEncryptor { get; }
+            public IAuthenticatedEncryptor? DefaultAuthenticatedEncryptor { get; }
 
             public Guid DefaultKeyId { get; } = default(Guid);
 
-            public IAuthenticatedEncryptor GetAuthenticatedEncryptorByKeyId(Guid keyId, out bool isRevoked)
+            public IAuthenticatedEncryptor? GetAuthenticatedEncryptorByKeyId(Guid keyId, out bool isRevoked)
             {
                 isRevoked = false;
                 return (keyId == default(Guid)) ? DefaultAuthenticatedEncryptor : null;
@@ -99,10 +99,10 @@ namespace Microsoft.AspNetCore.DataProtection
                 return this;
             }
 
-            private static IAuthenticatedEncryptor GetDefaultEncryptor(ILoggerFactory loggerFactory)
+            private static IAuthenticatedEncryptor? GetDefaultEncryptor(ILoggerFactory loggerFactory)
             {
                 var configuration = new T();
-                if (configuration is CngGcmAuthenticatedEncryptorConfiguration)
+                if (configuration is CngGcmAuthenticatedEncryptorConfiguration cngConfiguration)
                 {
                     Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
 
@@ -110,15 +110,15 @@ namespace Microsoft.AspNetCore.DataProtection
                     return new CngGcmAuthenticatedEncryptorFactory(loggerFactory)
                         .CreateAuthenticatedEncryptorInstance(
                             descriptor.MasterKey,
-                            configuration as CngGcmAuthenticatedEncryptorConfiguration);
+                            cngConfiguration);
                 }
-                else if (configuration is ManagedAuthenticatedEncryptorConfiguration)
+                else if (configuration is ManagedAuthenticatedEncryptorConfiguration managedConfiguration)
                 {
                     var descriptor = (ManagedAuthenticatedEncryptorDescriptor)new T().CreateNewDescriptor();
                     return new ManagedAuthenticatedEncryptorFactory(loggerFactory)
                         .CreateAuthenticatedEncryptorInstance(
                             descriptor.MasterKey,
-                            configuration as ManagedAuthenticatedEncryptorConfiguration);
+                            managedConfiguration);
                 }
 
                 return null;

+ 2 - 2
src/DataProtection/DataProtection/src/Error.cs

@@ -26,7 +26,7 @@ namespace Microsoft.AspNetCore.DataProtection
             return new ArgumentException(message, parameterName);
         }
 
-        public static CryptographicException CryptCommon_GenericError(Exception inner = null)
+        public static CryptographicException CryptCommon_GenericError(Exception? inner = null)
         {
             return new CryptographicException(Resources.CryptCommon_GenericError, inner);
         }
@@ -49,7 +49,7 @@ namespace Microsoft.AspNetCore.DataProtection
             return new InvalidOperationException(message);
         }
 
-        public static CryptographicException Common_EncryptionFailed(Exception inner = null)
+        public static CryptographicException Common_EncryptionFailed(Exception? inner = null)
         {
             return new CryptographicException(Resources.Common_EncryptionFailed, inner);
         }

+ 2 - 2
src/DataProtection/DataProtection/src/IRegistryPolicyResolver.cs

@@ -8,6 +8,6 @@ namespace Microsoft.AspNetCore.DataProtection
     // even if it was not registered causing problems crossplat
     internal interface IRegistryPolicyResolver
     {
-        RegistryPolicy ResolvePolicy();
+        RegistryPolicy? ResolvePolicy();
     }
-}
+}

+ 2 - 2
src/DataProtection/DataProtection/src/Internal/HostingApplicationDiscriminator.cs

@@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.DataProtection.Internal
 {
     internal class HostingApplicationDiscriminator : IApplicationDiscriminator
     {
-        private readonly IHostEnvironment _hosting;
+        private readonly IHostEnvironment? _hosting;
 
         // the optional constructor for when IHostingEnvironment is not available from DI
         public HostingApplicationDiscriminator()
@@ -20,6 +20,6 @@ namespace Microsoft.AspNetCore.DataProtection.Internal
             _hosting = hosting;
         }
 
-        public string Discriminator => _hosting?.ContentRootPath;
+        public string? Discriminator => _hosting?.ContentRootPath;
     }
 }

+ 4 - 4
src/DataProtection/DataProtection/src/Internal/KeyManagementOptionsSetup.cs

@@ -1,4 +1,4 @@
-// Copyright (c) .NET Foundation. All rights reserved.
+// Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 using System;
@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.DataProtection.Internal
 {
     internal class KeyManagementOptionsSetup : IConfigureOptions<KeyManagementOptions>
     {
-        private readonly IRegistryPolicyResolver _registryPolicyResolver;
+        private readonly IRegistryPolicyResolver? _registryPolicyResolver;
         private readonly ILoggerFactory _loggerFactory;
 
         public KeyManagementOptionsSetup()
@@ -31,7 +31,7 @@ namespace Microsoft.AspNetCore.DataProtection.Internal
         {
         }
 
-        public KeyManagementOptionsSetup(ILoggerFactory loggerFactory, IRegistryPolicyResolver registryPolicyResolver)
+        public KeyManagementOptionsSetup(ILoggerFactory loggerFactory, IRegistryPolicyResolver? registryPolicyResolver)
         {
             _loggerFactory = loggerFactory;
             _registryPolicyResolver = registryPolicyResolver;
@@ -39,7 +39,7 @@ namespace Microsoft.AspNetCore.DataProtection.Internal
 
         public void Configure(KeyManagementOptions options)
         {
-            RegistryPolicy context = null;
+            RegistryPolicy? context = null;
             if (_registryPolicyResolver != null)
             {
                 context = _registryPolicyResolver.ResolvePolicy();

+ 1 - 1
src/DataProtection/DataProtection/src/KeyManagement/DefaultKeyResolver.cs

@@ -71,7 +71,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
             }
         }
 
-        private IKey FindDefaultKey(DateTimeOffset now, IEnumerable<IKey> allKeys, out IKey fallbackKey, out bool callerShouldGenerateNewKey)
+        private IKey? FindDefaultKey(DateTimeOffset now, IEnumerable<IKey> allKeys, out IKey? fallbackKey, out bool callerShouldGenerateNewKey)
         {
             // find the preferred default key (allowing for server-to-server clock skew)
             var preferredDefaultKey = (from key in allKeys

+ 1 - 1
src/DataProtection/DataProtection/src/KeyManagement/DeferredKey.cs

@@ -48,7 +48,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
             {
                 // It's important that the lambda above doesn't capture 'descriptorElement'. Clearing the reference here
                 // helps us detect if we've done this by causing a null ref at runtime.
-                keyElement = null;
+                keyElement = null!;
             }
         }
     }

+ 1 - 1
src/DataProtection/DataProtection/src/KeyManagement/IKey.cs

@@ -55,6 +55,6 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
         /// to and decrypt data from this key.
         /// </summary>
         /// <returns>An <see cref="IAuthenticatedEncryptor"/>.</returns>
-        IAuthenticatedEncryptor CreateEncryptor();
+        IAuthenticatedEncryptor? CreateEncryptor();
     }
 }

+ 2 - 1
src/DataProtection/DataProtection/src/KeyManagement/Internal/CacheableKeyRing.cs

@@ -3,6 +3,7 @@
 
 using System;
 using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
 using System.Threading;
 using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption;
 
@@ -31,7 +32,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement.Internal
 
         internal IKeyRing KeyRing { get; }
 
-        internal static bool IsValid(CacheableKeyRing keyRing, DateTime utcNow)
+        internal static bool IsValid([NotNullWhen(true)] CacheableKeyRing? keyRing, DateTime utcNow)
         {
             return keyRing != null
                 && !keyRing._expirationToken.IsCancellationRequested

+ 2 - 2
src/DataProtection/DataProtection/src/KeyManagement/Internal/DefaultKeyResolution.cs

@@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement.Internal
         /// If this property is non-null, its <see cref="IKey.CreateEncryptor()"/> method will succeed
         /// so is appropriate for use with deferred keys.
         /// </remarks>
-        public IKey DefaultKey;
+        public IKey? DefaultKey;
 
         /// <summary>
         /// The fallback key, which should be used only if the caller is configured not to
@@ -29,7 +29,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement.Internal
         /// If this property is non-null, its <see cref="IKey.CreateEncryptor()"/> method will succeed
         /// so is appropriate for use with deferred keys.
         /// </remarks>
-        public IKey FallbackKey;
+        public IKey? FallbackKey;
 
         /// <summary>
         /// 'true' if a new key should be persisted to the keyring, 'false' otherwise.

+ 1 - 1
src/DataProtection/DataProtection/src/KeyManagement/Internal/IInternalXmlKeyManager.cs

@@ -17,6 +17,6 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement.Internal
 
         IAuthenticatedEncryptorDescriptor DeserializeDescriptorFromKeyElement(XElement keyElement);
 
-        void RevokeSingleKey(Guid keyId, DateTimeOffset revocationDate, string reason);
+        void RevokeSingleKey(Guid keyId, DateTimeOffset revocationDate, string? reason);
     }
 }

+ 2 - 2
src/DataProtection/DataProtection/src/KeyManagement/Internal/IKeyRing.cs

@@ -17,7 +17,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement.Internal
         /// <remarks>
         /// Activation of the encryptor instance is deferred until first access.
         /// </remarks>
-        IAuthenticatedEncryptor DefaultAuthenticatedEncryptor { get; }
+        IAuthenticatedEncryptor? DefaultAuthenticatedEncryptor { get; }
 
         /// <summary>
         /// The id of the key associated with <see cref="DefaultAuthenticatedEncryptor"/>.
@@ -31,6 +31,6 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement.Internal
         /// <remarks>
         /// Activation of the encryptor instance is deferred until first access.
         /// </remarks>
-        IAuthenticatedEncryptor GetAuthenticatedEncryptorByKeyId(Guid keyId, out bool isRevoked);
+        IAuthenticatedEncryptor? GetAuthenticatedEncryptorByKeyId(Guid keyId, out bool isRevoked);
     }
 }

+ 2 - 2
src/DataProtection/DataProtection/src/KeyManagement/KeyBase.cs

@@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
         private readonly Lazy<IAuthenticatedEncryptorDescriptor> _lazyDescriptor;
         private readonly IEnumerable<IAuthenticatedEncryptorFactory> _encryptorFactories;
 
-        private IAuthenticatedEncryptor _encryptor;
+        private IAuthenticatedEncryptor? _encryptor;
 
         public KeyBase(
             Guid keyId,
@@ -52,7 +52,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
             }
         }
 
-        public IAuthenticatedEncryptor CreateEncryptor()
+        public IAuthenticatedEncryptor? CreateEncryptor()
         {
             if (_encryptor == null)
             {

+ 1 - 1
src/DataProtection/DataProtection/src/KeyManagement/KeyEscrowServiceProviderExtensions.cs

@@ -15,7 +15,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
         /// Gets an aggregate <see cref="IKeyEscrowSink"/> from the underlying <see cref="IServiceProvider"/>.
         /// This method may return null if no sinks are registered.
         /// </summary>
-        public static IKeyEscrowSink GetKeyEscrowSink(this IServiceProvider services)
+        public static IKeyEscrowSink? GetKeyEscrowSink(this IServiceProvider services)
         {
             var escrowSinks = services?.GetService<IEnumerable<IKeyEscrowSink>>()?.ToList();
             return (escrowSinks != null && escrowSinks.Count > 0) ? new AggregateKeyEscrowSink(escrowSinks) : null;

+ 3 - 3
src/DataProtection/DataProtection/src/KeyManagement/KeyManagementOptions.cs

@@ -142,7 +142,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
         /// The <see cref="AlgorithmConfiguration"/> instance that can be used to create
         /// the <see cref="IAuthenticatedEncryptorDescriptor"/> instance.
         /// </summary>
-        public AlgorithmConfiguration AuthenticatedEncryptorConfiguration { get; set; }
+        public AlgorithmConfiguration? AuthenticatedEncryptorConfiguration { get; set; }
 
         /// <summary>
         /// The list of <see cref="IKeyEscrowSink"/> to store the key material in.
@@ -152,12 +152,12 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
         /// <summary>
         /// The <see cref="IXmlRepository"/> to use for storing and retrieving XML elements.
         /// </summary>
-        public IXmlRepository XmlRepository { get; set; }
+        public IXmlRepository? XmlRepository { get; set; }
 
         /// <summary>
         /// The <see cref="IXmlEncryptor"/> to use for encrypting XML elements.
         /// </summary>
-        public IXmlEncryptor XmlEncryptor { get; set; }
+        public IXmlEncryptor? XmlEncryptor { get; set; }
 
         /// <summary>
         /// The list of <see cref="IAuthenticatedEncryptorFactory"/> that will be used for creating

+ 7 - 9
src/DataProtection/DataProtection/src/KeyManagement/KeyRing.cs

@@ -37,22 +37,20 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
             _defaultKeyHolder = _keyIdToKeyHolderMap[DefaultKeyId];
         }
         
-        public IAuthenticatedEncryptor DefaultAuthenticatedEncryptor
+        public IAuthenticatedEncryptor? DefaultAuthenticatedEncryptor
         {
             get
             {
-                bool unused;
-                return _defaultKeyHolder.GetEncryptorInstance(out unused);
+                return _defaultKeyHolder.GetEncryptorInstance(out _);
             }
         }
 
         public Guid DefaultKeyId { get; }
 
-        public IAuthenticatedEncryptor GetAuthenticatedEncryptorByKeyId(Guid keyId, out bool isRevoked)
+        public IAuthenticatedEncryptor? GetAuthenticatedEncryptorByKeyId(Guid keyId, out bool isRevoked)
         {
             isRevoked = false;
-            KeyHolder holder;
-            _keyIdToKeyHolderMap.TryGetValue(keyId, out holder);
+            _keyIdToKeyHolderMap.TryGetValue(keyId, out var holder);
             return holder?.GetEncryptorInstance(out isRevoked);
         }
 
@@ -60,18 +58,18 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
         private sealed class KeyHolder
         {
             private readonly IKey _key;
-            private IAuthenticatedEncryptor _encryptor;
+            private IAuthenticatedEncryptor? _encryptor;
 
             internal KeyHolder(IKey key)
             {
                 _key = key;
             }
 
-            internal IAuthenticatedEncryptor GetEncryptorInstance(out bool isRevoked)
+            internal IAuthenticatedEncryptor? GetEncryptorInstance(out bool isRevoked)
             {
                 // simple double-check lock pattern
                 // we can't use LazyInitializer<T> because we don't have a simple value factory
-                IAuthenticatedEncryptor encryptor = Volatile.Read(ref _encryptor);
+                IAuthenticatedEncryptor? encryptor = Volatile.Read(ref _encryptor);
                 if (encryptor == null)
                 {
                     lock (this)

+ 15 - 6
src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs

@@ -25,9 +25,9 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
 
         private AdditionalAuthenticatedDataTemplate _aadTemplate;
         private readonly IKeyRingProvider _keyRingProvider;
-        private readonly ILogger _logger;
+        private readonly ILogger? _logger;
 
-        public KeyRingBasedDataProtector(IKeyRingProvider keyRingProvider, ILogger logger, string[] originalPurposes, string newPurpose)
+        public KeyRingBasedDataProtector(IKeyRingProvider keyRingProvider, ILogger? logger, string[]? originalPurposes, string newPurpose)
         {
             Debug.Assert(keyRingProvider != null);
 
@@ -39,7 +39,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
 
         internal string[] Purposes { get; }
 
-        private static string[] ConcatPurposes(string[] originalPurposes, string newPurpose)
+        private static string[] ConcatPurposes(string[]? originalPurposes, string newPurpose)
         {
             if (originalPurposes != null && originalPurposes.Length > 0)
             {
@@ -248,7 +248,10 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
 
                     if (requestedEncryptor == null)
                     {
-                        _logger.KeyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed(keyIdFromPayload);
+                        if (_logger.IsTraceLevelEnabled())
+                        {
+                            _logger.KeyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed(keyIdFromPayload);
+                        }
                         throw Error.Common_KeyNotFound(keyIdFromPayload);
                     }
                 }
@@ -265,12 +268,18 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
                 {
                     if (allowOperationsOnRevokedKeys)
                     {
-                        _logger.KeyWasRevokedCallerRequestedUnprotectOperationProceedRegardless(keyIdFromPayload);
+                        if (_logger.IsDebugLevelEnabled())
+                        {
+                            _logger.KeyWasRevokedCallerRequestedUnprotectOperationProceedRegardless(keyIdFromPayload);
+                        }
                         status = UnprotectStatus.DecryptionKeyWasRevoked;
                     }
                     else
                     {
-                        _logger.KeyWasRevokedUnprotectOperationCannotProceed(keyIdFromPayload);
+                        if (_logger.IsDebugLevelEnabled())
+                        {
+                            _logger.KeyWasRevokedUnprotectOperationCannotProceed(keyIdFromPayload);
+                        }
                         throw Error.Common_KeyRevoked(keyIdFromPayload);
                     }
                 }

+ 3 - 3
src/DataProtection/DataProtection/src/KeyManagement/KeyRingProvider.cs

@@ -15,7 +15,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
 {
     internal sealed class KeyRingProvider : ICacheableKeyRingProvider, IKeyRingProvider
     {
-        private CacheableKeyRing _cacheableKeyRing;
+        private CacheableKeyRing? _cacheableKeyRing;
         private readonly object _cacheableKeyRingLockObj = new object();
         private readonly IDefaultKeyResolver _defaultKeyResolver;
         private readonly KeyManagementOptions _keyManagementOptions;
@@ -57,7 +57,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
 
         internal bool InAutoRefreshWindow() => DateTime.UtcNow < AutoRefreshWindowEnd;
 
-        private CacheableKeyRing CreateCacheableKeyRingCore(DateTimeOffset now, IKey keyJustAdded)
+        private CacheableKeyRing CreateCacheableKeyRingCore(DateTimeOffset now, IKey? keyJustAdded)
         {
             // Refresh the list of all keys
             var cacheExpirationToken = _keyManager.GetCacheExpirationToken();
@@ -159,7 +159,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
             Debug.Assert(utcNow.Kind == DateTimeKind.Utc);
 
             // Can we return the cached keyring to the caller?
-            CacheableKeyRing existingCacheableKeyRing = null;
+            CacheableKeyRing? existingCacheableKeyRing = null;
             if (!forceRefresh)
             {
                 existingCacheableKeyRing = Volatile.Read(ref _cacheableKeyRing);

+ 40 - 36
src/DataProtection/DataProtection/src/KeyManagement/XmlKeyManager.cs

@@ -49,14 +49,14 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
 
         private readonly IActivator _activator;
         private readonly AlgorithmConfiguration _authenticatedEncryptorConfiguration;
-        private readonly IKeyEscrowSink _keyEscrowSink;
+        private readonly IKeyEscrowSink? _keyEscrowSink;
         private readonly IInternalXmlKeyManager _internalKeyManager;
         private readonly ILoggerFactory _loggerFactory;
         private readonly ILogger _logger;
         private readonly IEnumerable<IAuthenticatedEncryptorFactory> _encryptorFactories;
         private readonly IDefaultKeyStorageDirectories _keyStorageDirectories;
 
-        private CancellationTokenSource _cacheExpirationTokenSource;
+        private CancellationTokenSource? _cacheExpirationTokenSource;
 
         /// <summary>
         /// Creates an <see cref="XmlKeyManager"/>.
@@ -91,11 +91,11 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
             _logger = _loggerFactory.CreateLogger<XmlKeyManager>();
             _keyStorageDirectories = keyStorageDirectories ?? throw new ArgumentNullException(nameof(keyStorageDirectories));
 
-            KeyRepository = keyManagementOptions.Value.XmlRepository;
-            KeyEncryptor = keyManagementOptions.Value.XmlEncryptor;
-            if (KeyRepository == null)
+            var keyRepository = keyManagementOptions.Value.XmlRepository;
+            var keyEncryptor = keyManagementOptions.Value.XmlEncryptor;
+            if (keyRepository == null)
             {
-                if (KeyEncryptor != null)
+                if (keyEncryptor != null)
                 {
                     throw new InvalidOperationException(
                         Resources.FormatXmlKeyManager_IXmlRepositoryNotFound(nameof(IXmlRepository), nameof(IXmlEncryptor)));
@@ -103,12 +103,15 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
                 else
                 {
                     var keyRepositoryEncryptorPair = GetFallbackKeyRepositoryEncryptorPair();
-                    KeyRepository = keyRepositoryEncryptorPair.Key;
-                    KeyEncryptor = keyRepositoryEncryptorPair.Value;
+                    keyRepository = keyRepositoryEncryptorPair.Key;
+                    keyEncryptor = keyRepositoryEncryptorPair.Value;
                 }
             }
 
-            _authenticatedEncryptorConfiguration = keyManagementOptions.Value.AuthenticatedEncryptorConfiguration;
+            KeyRepository = keyRepository;
+            KeyEncryptor = keyEncryptor;
+
+            _authenticatedEncryptorConfiguration = keyManagementOptions.Value.AuthenticatedEncryptorConfiguration!;
 
             var escrowSinks = keyManagementOptions.Value.KeyEscrowSinks;
             _keyEscrowSink = escrowSinks.Count > 0 ? new AggregateKeyEscrowSink(escrowSinks) : null;
@@ -129,7 +132,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
             _internalKeyManager = internalXmlKeyManager;
         }
 
-        internal IXmlEncryptor KeyEncryptor { get; }
+        internal IXmlEncryptor? KeyEncryptor { get; }
 
         internal IXmlRepository KeyRepository { get; }
 
@@ -154,7 +157,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
 
             // We aggregate all the information we read into three buckets
             Dictionary<Guid, KeyBase> keyIdToKeyMap = new Dictionary<Guid, KeyBase>();
-            HashSet<Guid> revokedKeyIds = null;
+            HashSet<Guid>? revokedKeyIds = null;
             DateTimeOffset? mostRecentMassRevocationDate = null;
 
             foreach (var element in allElements)
@@ -207,8 +210,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
             {
                 foreach (Guid revokedKeyId in revokedKeyIds)
                 {
-                    KeyBase key;
-                    keyIdToKeyMap.TryGetValue(revokedKeyId, out key);
+                    keyIdToKeyMap.TryGetValue(revokedKeyId, out var key);
                     if (key != null)
                     {
                         key.SetRevoked();
@@ -245,20 +247,22 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
 
         public CancellationToken GetCacheExpirationToken()
         {
-            return Interlocked.CompareExchange(ref _cacheExpirationTokenSource, null, null).Token;
+            Debug.Assert(_cacheExpirationTokenSource != null, $"{nameof(TriggerAndResetCacheExpirationToken)} must have been called first.");
+
+            return Interlocked.CompareExchange<CancellationTokenSource?>(ref _cacheExpirationTokenSource, null, null).Token;
         }
 
-        private KeyBase ProcessKeyElement(XElement keyElement)
+        private KeyBase? ProcessKeyElement(XElement keyElement)
         {
             Debug.Assert(keyElement.Name == KeyElementName);
 
             try
             {
                 // Read metadata and prepare the key for deferred instantiation
-                Guid keyId = (Guid)keyElement.Attribute(IdAttributeName);
-                DateTimeOffset creationDate = (DateTimeOffset)keyElement.Element(CreationDateElementName);
-                DateTimeOffset activationDate = (DateTimeOffset)keyElement.Element(ActivationDateElementName);
-                DateTimeOffset expirationDate = (DateTimeOffset)keyElement.Element(ExpirationDateElementName);
+                Guid keyId = (Guid)keyElement.Attribute(IdAttributeName)!;
+                DateTimeOffset creationDate = (DateTimeOffset)keyElement.Element(CreationDateElementName)!;
+                DateTimeOffset activationDate = (DateTimeOffset)keyElement.Element(ActivationDateElementName)!;
+                DateTimeOffset expirationDate = (DateTimeOffset)keyElement.Element(ExpirationDateElementName)!;
 
                 _logger.FoundKey(keyId);
 
@@ -287,11 +291,11 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
 
             try
             {
-                string keyIdAsString = (string)revocationElement.Element(KeyElementName).Attribute(IdAttributeName);
+                string keyIdAsString = (string)revocationElement.Element(KeyElementName)!.Attribute(IdAttributeName)!;
                 if (keyIdAsString == RevokeAllKeysValue)
                 {
                     // this is a mass revocation of all keys as of the specified revocation date
-                    DateTimeOffset massRevocationDate = (DateTimeOffset)revocationElement.Element(RevocationDateElementName);
+                    DateTimeOffset massRevocationDate = (DateTimeOffset)revocationElement.Element(RevocationDateElementName)!;
                     _logger.FoundRevocationOfAllKeysCreatedPriorTo(massRevocationDate);
                     return massRevocationDate;
                 }
@@ -312,7 +316,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
             }
         }
 
-        public void RevokeAllKeys(DateTimeOffset revocationDate, string reason = null)
+        public void RevokeAllKeys(DateTimeOffset revocationDate, string? reason = null)
         {
             // <revocation version="1">
             //   <revocationDate>...</revocationDate>
@@ -337,7 +341,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
             TriggerAndResetCacheExpirationToken();
         }
 
-        public void RevokeKey(Guid keyId, string reason = null)
+        public void RevokeKey(Guid keyId, string? reason = null)
         {
             _internalKeyManager.RevokeSingleKey(
                 keyId: keyId,
@@ -345,11 +349,11 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
                 reason: reason);
         }
 
-        private void TriggerAndResetCacheExpirationToken([CallerMemberName] string opName = null, bool suppressLogging = false)
+        private void TriggerAndResetCacheExpirationToken([CallerMemberName] string? opName = null, bool suppressLogging = false)
         {
             if (!suppressLogging)
             {
-                _logger.KeyCacheExpirationTokenTriggeredByOperation(opName);
+                _logger.KeyCacheExpirationTokenTriggeredByOperation(opName!);
             }
 
             Interlocked.Exchange(ref _cacheExpirationTokenSource, new CancellationTokenSource())?.Cancel();
@@ -387,7 +391,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
                 ?? CryptoUtil.Fail<IAuthenticatedEncryptorDescriptor>("CreateNewDescriptor returned null.");
             var descriptorXmlInfo = newDescriptor.ExportToXml();
 
-            _logger.DescriptorDeserializerTypeForKeyIs(keyId, descriptorXmlInfo.DeserializerType.AssemblyQualifiedName);
+            _logger.DescriptorDeserializerTypeForKeyIs(keyId, descriptorXmlInfo.DeserializerType.AssemblyQualifiedName!);
 
             // build the <key> element
             var keyElement = new XElement(KeyElementName,
@@ -397,7 +401,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
                 new XElement(ActivationDateElementName, activationDate),
                 new XElement(ExpirationDateElementName, expirationDate),
                 new XElement(DescriptorElementName,
-                    new XAttribute(DeserializerTypeAttributeName, descriptorXmlInfo.DeserializerType.AssemblyQualifiedName),
+                    new XAttribute(DeserializerTypeAttributeName, descriptorXmlInfo.DeserializerType.AssemblyQualifiedName!),
                     descriptorXmlInfo.SerializedDescriptorElement));
 
             // If key escrow policy is in effect, write the *unencrypted* key now.
@@ -439,7 +443,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
             {
                 // Figure out who will be deserializing this
                 var descriptorElement = keyElement.Element(DescriptorElementName);
-                string descriptorDeserializerTypeName = (string)descriptorElement.Attribute(DeserializerTypeAttributeName);
+                string descriptorDeserializerTypeName = (string)descriptorElement!.Attribute(DeserializerTypeAttributeName)!;
 
                 // Decrypt the descriptor element and pass it to the descriptor for consumption
                 var unencryptedInputToDeserializer = descriptorElement.Elements().Single().DecryptElement(_activator);
@@ -455,7 +459,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
             }
         }
 
-        void IInternalXmlKeyManager.RevokeSingleKey(Guid keyId, DateTimeOffset revocationDate, string reason)
+        void IInternalXmlKeyManager.RevokeSingleKey(Guid keyId, DateTimeOffset revocationDate, string? reason)
         {
             // <revocation version="1">
             //   <revocationDate>...</revocationDate>
@@ -478,10 +482,10 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
             TriggerAndResetCacheExpirationToken();
         }
 
-        internal KeyValuePair<IXmlRepository, IXmlEncryptor> GetFallbackKeyRepositoryEncryptorPair()
+        internal KeyValuePair<IXmlRepository, IXmlEncryptor?> GetFallbackKeyRepositoryEncryptorPair()
         {
-            IXmlRepository repository = null;
-            IXmlEncryptor encryptor = null;
+            IXmlRepository? repository = null;
+            IXmlEncryptor? encryptor = null;
 
             // If we're running in Azure Web Sites, the key repository goes in the %HOME% directory.
             var azureWebSitesKeysFolder = _keyStorageDirectories.GetKeyStorageDirectoryForAzureWebSites();
@@ -523,7 +527,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
                 else
                 {
                     // Use profile isn't available - can we use the HKLM registry?
-                    RegistryKey regKeyStorageKey = null;
+                    RegistryKey? regKeyStorageKey = null;
                     if (OSVersionUtil.IsWindows())
                     {
                         Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); // Hint for the platform compatibility analyzer.
@@ -536,9 +540,9 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
 
                         // If the user profile isn't available, we can protect using DPAPI (to machine).
                         encryptor = new DpapiXmlEncryptor(protectToLocalMachine: true, loggerFactory: _loggerFactory);
-                        repository = new RegistryXmlRepository(regKeyStorageKey, _loggerFactory);
+                        repository = new RegistryXmlRepository(regKeyStorageKey!, _loggerFactory);
 
-                        _logger.UsingRegistryAsKeyRepositoryWithDPAPI(regKeyStorageKey.Name);
+                        _logger.UsingRegistryAsKeyRepositoryWithDPAPI(regKeyStorageKey!.Name);
                     }
                     else
                     {
@@ -551,7 +555,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
                 }
             }
 
-            return new KeyValuePair<IXmlRepository, IXmlEncryptor>(repository, encryptor);
+            return new KeyValuePair<IXmlRepository, IXmlEncryptor?>(repository, encryptor);
         }
 
         private sealed class AggregateKeyEscrowSink : IKeyEscrowSink

+ 73 - 72
src/DataProtection/DataProtection/src/LoggingExtensions.cs

@@ -2,6 +2,7 @@
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 using System;
+using System.Diagnostics.CodeAnalysis;
 using System.Runtime.CompilerServices;
 using System.Xml.Linq;
 using Microsoft.AspNetCore.DataProtection;
@@ -14,137 +15,137 @@ namespace Microsoft.Extensions.Logging
     /// </summary>
     internal static class LoggingExtensions
     {
-        private static Action<ILogger, Guid, DateTimeOffset, Exception> _usingFallbackKeyWithExpirationAsDefaultKey;
+        private static Action<ILogger, Guid, DateTimeOffset, Exception?> _usingFallbackKeyWithExpirationAsDefaultKey;
 
-        private static Action<ILogger, Guid, Exception> _usingKeyAsDefaultKey;
+        private static Action<ILogger, Guid, Exception?> _usingKeyAsDefaultKey;
 
-        private static Action<ILogger, string, string, Exception> _openingCNGAlgorithmFromProviderWithHMAC;
+        private static Action<ILogger, string, string?, Exception?> _openingCNGAlgorithmFromProviderWithHMAC;
 
-        private static Action<ILogger, string, string, Exception> _openingCNGAlgorithmFromProviderWithChainingModeCBC;
+        private static Action<ILogger, string, string?, Exception?> _openingCNGAlgorithmFromProviderWithChainingModeCBC;
 
-        private static Action<ILogger, Guid, string, Exception> _performingUnprotectOperationToKeyWithPurposes;
+        private static Action<ILogger, Guid, string, Exception?> _performingUnprotectOperationToKeyWithPurposes;
 
-        private static Action<ILogger, Guid, Exception> _keyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed;
+        private static Action<ILogger, Guid, Exception?> _keyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed;
 
-        private static Action<ILogger, Guid, Exception> _keyWasRevokedCallerRequestedUnprotectOperationProceedRegardless;
+        private static Action<ILogger, Guid, Exception?> _keyWasRevokedCallerRequestedUnprotectOperationProceedRegardless;
 
-        private static Action<ILogger, Guid, Exception> _keyWasRevokedUnprotectOperationCannotProceed;
+        private static Action<ILogger, Guid, Exception?> _keyWasRevokedUnprotectOperationCannotProceed;
 
-        private static Action<ILogger, string, string, Exception> _openingCNGAlgorithmFromProviderWithChainingModeGCM;
+        private static Action<ILogger, string, string?, Exception?> _openingCNGAlgorithmFromProviderWithChainingModeGCM;
 
-        private static Action<ILogger, string, Exception> _usingManagedKeyedHashAlgorithm;
+        private static Action<ILogger, string, Exception?> _usingManagedKeyedHashAlgorithm;
 
-        private static Action<ILogger, string, Exception> _usingManagedSymmetricAlgorithm;
+        private static Action<ILogger, string, Exception?> _usingManagedSymmetricAlgorithm;
 
         private static Action<ILogger, Guid, string, Exception> _keyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed;
 
-        private static Action<ILogger, Guid, DateTimeOffset, Exception> _consideringKeyWithExpirationDateAsDefaultKey;
+        private static Action<ILogger, Guid, DateTimeOffset, Exception?> _consideringKeyWithExpirationDateAsDefaultKey;
 
-        private static Action<ILogger, Guid, Exception> _keyIsNoLongerUnderConsiderationAsDefault;
+        private static Action<ILogger, Guid, Exception?> _keyIsNoLongerUnderConsiderationAsDefault;
 
-        private static Action<ILogger, XName, Exception> _unknownElementWithNameFoundInKeyringSkipping;
+        private static Action<ILogger, XName, Exception?> _unknownElementWithNameFoundInKeyringSkipping;
 
-        private static Action<ILogger, Guid, Exception> _markedKeyAsRevokedInTheKeyring;
+        private static Action<ILogger, Guid, Exception?> _markedKeyAsRevokedInTheKeyring;
 
-        private static Action<ILogger, Guid, Exception> _triedToProcessRevocationOfKeyButNoSuchKeyWasFound;
+        private static Action<ILogger, Guid, Exception?> _triedToProcessRevocationOfKeyButNoSuchKeyWasFound;
 
-        private static Action<ILogger, Guid, Exception> _foundKey;
+        private static Action<ILogger, Guid, Exception?> _foundKey;
 
-        private static Action<ILogger, DateTimeOffset, Exception> _foundRevocationOfAllKeysCreatedPriorTo;
+        private static Action<ILogger, DateTimeOffset, Exception?> _foundRevocationOfAllKeysCreatedPriorTo;
 
-        private static Action<ILogger, Guid, Exception> _foundRevocationOfKey;
+        private static Action<ILogger, Guid, Exception?> _foundRevocationOfKey;
 
         private static Action<ILogger, XElement, Exception> _exceptionWhileProcessingRevocationElement;
 
-        private static Action<ILogger, DateTimeOffset, string, Exception> _revokingAllKeysAsOfForReason;
+        private static Action<ILogger, DateTimeOffset, string?, Exception?> _revokingAllKeysAsOfForReason;
 
-        private static Action<ILogger, string, Exception> _keyCacheExpirationTokenTriggeredByOperation;
+        private static Action<ILogger, string, Exception?> _keyCacheExpirationTokenTriggeredByOperation;
 
         private static Action<ILogger, XElement, Exception> _anExceptionOccurredWhileProcessingTheKeyElement;
 
         private static Action<ILogger, XElement, Exception> _anExceptionOccurredWhileProcessingTheKeyElementDebug;
 
-        private static Action<ILogger, string, Exception> _encryptingToWindowsDPAPIForCurrentUserAccount;
+        private static Action<ILogger, string, Exception?> _encryptingToWindowsDPAPIForCurrentUserAccount;
 
-        private static Action<ILogger, string, Exception> _encryptingToWindowsDPAPINGUsingProtectionDescriptorRule;
+        private static Action<ILogger, string, Exception?> _encryptingToWindowsDPAPINGUsingProtectionDescriptorRule;
 
         private static Action<ILogger, string, Exception> _anErrorOccurredWhileEncryptingToX509CertificateWithThumbprint;
 
-        private static Action<ILogger, string, Exception> _encryptingToX509CertificateWithThumbprint;
+        private static Action<ILogger, string, Exception?> _encryptingToX509CertificateWithThumbprint;
 
         private static Action<ILogger, string, Exception> _exceptionOccurredWhileTryingToResolveCertificateWithThumbprint;
 
-        private static Action<ILogger, Guid, string, Exception> _performingProtectOperationToKeyWithPurposes;
+        private static Action<ILogger, Guid, string, Exception?> _performingProtectOperationToKeyWithPurposes;
 
-        private static Action<ILogger, Guid, DateTimeOffset, DateTimeOffset, DateTimeOffset, Exception> _creatingKey;
+        private static Action<ILogger, Guid, DateTimeOffset, DateTimeOffset, DateTimeOffset, Exception?> _creatingKey;
 
-        private static Action<ILogger, Guid, string, Exception> _descriptorDeserializerTypeForKeyIs;
+        private static Action<ILogger, Guid, string, Exception?> _descriptorDeserializerTypeForKeyIs;
 
-        private static Action<ILogger, Guid, Exception> _keyEscrowSinkFoundWritingKeyToEscrow;
+        private static Action<ILogger, Guid, Exception?> _keyEscrowSinkFoundWritingKeyToEscrow;
 
-        private static Action<ILogger, Guid, Exception> _noKeyEscrowSinkFoundNotWritingKeyToEscrow;
+        private static Action<ILogger, Guid, Exception?> _noKeyEscrowSinkFoundNotWritingKeyToEscrow;
 
-        private static Action<ILogger, Guid, Exception> _noXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm;
+        private static Action<ILogger, Guid, Exception?> _noXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm;
 
-        private static Action<ILogger, Guid, DateTimeOffset, string, Exception> _revokingKeyForReason;
+        private static Action<ILogger, Guid, DateTimeOffset, string?, Exception?> _revokingKeyForReason;
 
-        private static Action<ILogger, string, Exception> _readingDataFromFile;
+        private static Action<ILogger, string, Exception?> _readingDataFromFile;
 
-        private static Action<ILogger, string, string, Exception> _nameIsNotSafeFileName;
+        private static Action<ILogger, string, string, Exception?> _nameIsNotSafeFileName;
 
-        private static Action<ILogger, string, Exception> _writingDataToFile;
+        private static Action<ILogger, string, Exception?> _writingDataToFile;
 
-        private static Action<ILogger, RegistryKey, string, Exception> _readingDataFromRegistryKeyValue;
+        private static Action<ILogger, RegistryKey, string, Exception?> _readingDataFromRegistryKeyValue;
 
-        private static Action<ILogger, string, string, Exception> _nameIsNotSafeRegistryValueName;
+        private static Action<ILogger, string, string, Exception?> _nameIsNotSafeRegistryValueName;
 
-        private static Action<ILogger, string, Exception> _decryptingSecretElementUsingWindowsDPAPING;
+        private static Action<ILogger, string?, Exception?> _decryptingSecretElementUsingWindowsDPAPING;
 
         private static Action<ILogger, Exception> _exceptionOccurredTryingToDecryptElement;
 
-        private static Action<ILogger, Exception> _encryptingUsingNullEncryptor;
+        private static Action<ILogger, Exception?> _encryptingUsingNullEncryptor;
 
-        private static Action<ILogger, Exception> _usingEphemeralDataProtectionProvider;
+        private static Action<ILogger, Exception?> _usingEphemeralDataProtectionProvider;
 
-        private static Action<ILogger, Exception> _existingCachedKeyRingIsExpiredRefreshing;
+        private static Action<ILogger, Exception?> _existingCachedKeyRingIsExpiredRefreshing;
 
         private static Action<ILogger, Exception> _errorOccurredWhileRefreshingKeyRing;
 
         private static Action<ILogger, Exception> _errorOccurredWhileReadingKeyRing;
 
-        private static Action<ILogger, Exception> _keyRingDoesNotContainValidDefaultKey;
+        private static Action<ILogger, Exception?> _keyRingDoesNotContainValidDefaultKey;
 
-        private static Action<ILogger, Exception> _usingInmemoryRepository;
+        private static Action<ILogger, Exception?> _usingInmemoryRepository;
 
-        private static Action<ILogger, Exception> _decryptingSecretElementUsingWindowsDPAPI;
+        private static Action<ILogger, Exception?> _decryptingSecretElementUsingWindowsDPAPI;
 
-        private static Action<ILogger, Exception> _defaultKeyExpirationImminentAndRepository;
+        private static Action<ILogger, Exception?> _defaultKeyExpirationImminentAndRepository;
 
-        private static Action<ILogger, Exception> _repositoryContainsNoViableDefaultKey;
+        private static Action<ILogger, Exception?> _repositoryContainsNoViableDefaultKey;
 
         private static Action<ILogger, Exception> _errorOccurredWhileEncryptingToWindowsDPAPI;
 
-        private static Action<ILogger, Exception> _encryptingToWindowsDPAPIForLocalMachineAccount;
+        private static Action<ILogger, Exception?> _encryptingToWindowsDPAPIForLocalMachineAccount;
 
         private static Action<ILogger, Exception> _errorOccurredWhileEncryptingToWindowsDPAPING;
 
-        private static Action<ILogger, Exception> _policyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing;
+        private static Action<ILogger, Exception?> _policyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing;
 
-        private static Action<ILogger, Guid, Exception> _keyRingWasLoadedOnStartup;
+        private static Action<ILogger, Guid, Exception?> _keyRingWasLoadedOnStartup;
 
         private static Action<ILogger, Exception> _keyRingFailedToLoadOnStartup;
 
-        private static Action<ILogger, Exception> _usingEphemeralKeyRepository;
+        private static Action<ILogger, Exception?> _usingEphemeralKeyRepository;
 
-        private static Action<ILogger, string, Exception> _usingRegistryAsKeyRepositoryWithDPAPI;
+        private static Action<ILogger, string, Exception?> _usingRegistryAsKeyRepositoryWithDPAPI;
 
-        private static Action<ILogger, string, Exception> _usingProfileAsKeyRepository;
+        private static Action<ILogger, string, Exception?> _usingProfileAsKeyRepository;
 
-        private static Action<ILogger, string, Exception> _usingProfileAsKeyRepositoryWithDPAPI;
+        private static Action<ILogger, string, Exception?> _usingProfileAsKeyRepositoryWithDPAPI;
 
-        private static Action<ILogger, string, Exception> _usingAzureAsKeyRepository;
+        private static Action<ILogger, string, Exception?> _usingAzureAsKeyRepository;
 
-        private static Action<ILogger, string, Exception> _usingEphemeralFileSystemLocationInContainer;
+        private static Action<ILogger, string, Exception?> _usingEphemeralFileSystemLocationInContainer;
 
         static LoggingExtensions()
         {
@@ -156,11 +157,11 @@ namespace Microsoft.Extensions.Logging
                 eventId: new EventId(2, "UsingKeyAsDefaultKey"),
                 logLevel: LogLevel.Debug,
                 formatString: "Using key {KeyId:B} as the default key.");
-            _openingCNGAlgorithmFromProviderWithHMAC = LoggerMessage.Define<string, string>(
+            _openingCNGAlgorithmFromProviderWithHMAC = LoggerMessage.Define<string, string?>(
                 eventId: new EventId(3, "OpeningCNGAlgorithmFromProviderWithHMAC"),
                 logLevel: LogLevel.Debug,
                 formatString: "Opening CNG algorithm '{HashAlgorithm}' from provider '{HashAlgorithmProvider}' with HMAC.");
-            _openingCNGAlgorithmFromProviderWithChainingModeCBC = LoggerMessage.Define<string, string>(
+            _openingCNGAlgorithmFromProviderWithChainingModeCBC = LoggerMessage.Define<string, string?>(
                 eventId: new EventId(4, "OpeningCNGAlgorithmFromProviderWithChainingModeCBC"),
                 logLevel: LogLevel.Debug,
                 formatString: "Opening CNG algorithm '{EncryptionAlgorithm}' from provider '{EncryptionAlgorithmProvider}' with chaining mode CBC.");
@@ -180,7 +181,7 @@ namespace Microsoft.Extensions.Logging
                 eventId: new EventId(8, "KeyWasRevokedUnprotectOperationCannotProceed"),
                 logLevel: LogLevel.Debug,
                 formatString: "Key {KeyId:B} was revoked. Unprotect operation cannot proceed.");
-            _openingCNGAlgorithmFromProviderWithChainingModeGCM = LoggerMessage.Define<string, string>(
+            _openingCNGAlgorithmFromProviderWithChainingModeGCM = LoggerMessage.Define<string, string?>(
                 eventId: new EventId(9, "OpeningCNGAlgorithmFromProviderWithChainingModeGCM"),
                 logLevel: LogLevel.Debug,
                 formatString: "Opening CNG algorithm '{EncryptionAlgorithm}' from provider '{EncryptionAlgorithmProvider}' with chaining mode GCM.");
@@ -232,7 +233,7 @@ namespace Microsoft.Extensions.Logging
                 eventId: new EventId(21, "ExceptionWhileProcessingRevocationElement"),
                 logLevel: LogLevel.Error,
                 formatString: "An exception occurred while processing the revocation element '{RevocationElement}'. Cannot continue keyring processing.");
-            _revokingAllKeysAsOfForReason = LoggerMessage.Define<DateTimeOffset, string>(
+            _revokingAllKeysAsOfForReason = LoggerMessage.Define<DateTimeOffset, string?>(
                 eventId: new EventId(22, "RevokingAllKeysAsOfForReason"),
                 logLevel: LogLevel.Information,
                 formatString: "Revoking all keys as of {RevocationDate:u} for reason '{Reason}'.");
@@ -288,7 +289,7 @@ namespace Microsoft.Extensions.Logging
                 eventId: new EventId(35, "NoXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm"),
                 logLevel: LogLevel.Warning,
                 formatString: "No XML encryptor configured. Key {KeyId:B} may be persisted to storage in unencrypted form.");
-            _revokingKeyForReason = LoggerMessage.Define<Guid, DateTimeOffset, string>(
+            _revokingKeyForReason = LoggerMessage.Define<Guid, DateTimeOffset, string?>(
                 eventId: new EventId(36, "RevokingKeyForReason"),
                 logLevel: LogLevel.Information,
                 formatString: "Revoking key {KeyId:B} at {RevocationDate:u} for reason '{Reason}'.");
@@ -312,7 +313,7 @@ namespace Microsoft.Extensions.Logging
                 eventId: new EventId(41, "NameIsNotSafeRegistryValueName"),
                 logLevel: LogLevel.Debug,
                 formatString: "The name '{FriendlyName}' is not a safe registry value name, using '{NewFriendlyName}' instead.");
-            _decryptingSecretElementUsingWindowsDPAPING = LoggerMessage.Define<string>(
+            _decryptingSecretElementUsingWindowsDPAPING = LoggerMessage.Define<string?>(
                 eventId: new EventId(42, "DecryptingSecretElementUsingWindowsDPAPING"),
                 logLevel: LogLevel.Debug,
                 formatString: "Decrypting secret element using Windows DPAPI-NG with protection descriptor rule '{DescriptorRule}'.");
@@ -420,7 +421,7 @@ namespace Microsoft.Extensions.Logging
         /// Returns false if the logger instance is null.
         /// </summary>
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public static bool IsDebugLevelEnabled(this ILogger logger)
+        public static bool IsDebugLevelEnabled([NotNullWhen(true)] this ILogger? logger)
         {
             return IsLogLevelEnabledCore(logger, LogLevel.Debug);
         }
@@ -430,7 +431,7 @@ namespace Microsoft.Extensions.Logging
         /// Returns false if the logger instance is null.
         /// </summary>
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public static bool IsErrorLevelEnabled(this ILogger logger)
+        public static bool IsErrorLevelEnabled([NotNullWhen(true)] this ILogger? logger)
         {
             return IsLogLevelEnabledCore(logger, LogLevel.Error);
         }
@@ -440,7 +441,7 @@ namespace Microsoft.Extensions.Logging
         /// Returns false if the logger instance is null.
         /// </summary>
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public static bool IsInformationLevelEnabled(this ILogger logger)
+        public static bool IsInformationLevelEnabled([NotNullWhen(true)] this ILogger? logger)
         {
             return IsLogLevelEnabledCore(logger, LogLevel.Information);
         }
@@ -450,7 +451,7 @@ namespace Microsoft.Extensions.Logging
         /// Returns false if the logger instance is null.
         /// </summary>
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public static bool IsTraceLevelEnabled(this ILogger logger)
+        public static bool IsTraceLevelEnabled([NotNullWhen(true)] this ILogger? logger)
         {
             return IsLogLevelEnabledCore(logger, LogLevel.Trace);
         }
@@ -460,13 +461,13 @@ namespace Microsoft.Extensions.Logging
         /// Returns false if the logger instance is null.
         /// </summary>
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public static bool IsWarningLevelEnabled(this ILogger logger)
+        public static bool IsWarningLevelEnabled([NotNullWhen(true)] this ILogger? logger)
         {
             return IsLogLevelEnabledCore(logger, LogLevel.Warning);
         }
 
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        private static bool IsLogLevelEnabledCore(ILogger logger, LogLevel level)
+        private static bool IsLogLevelEnabledCore([NotNullWhen(true)] ILogger? logger, LogLevel level)
         {
             return (logger != null && logger.IsEnabled(level));
         }
@@ -481,12 +482,12 @@ namespace Microsoft.Extensions.Logging
             _usingKeyAsDefaultKey(logger, keyId, null);
         }
 
-        public static void OpeningCNGAlgorithmFromProviderWithHMAC(this ILogger logger, string hashAlgorithm, string hashAlgorithmProvider)
+        public static void OpeningCNGAlgorithmFromProviderWithHMAC(this ILogger logger, string hashAlgorithm, string? hashAlgorithmProvider)
         {
             _openingCNGAlgorithmFromProviderWithHMAC(logger, hashAlgorithm, hashAlgorithmProvider, null);
         }
 
-        public static void OpeningCNGAlgorithmFromProviderWithChainingModeCBC(this ILogger logger, string encryptionAlgorithm, string encryptionAlgorithmProvider)
+        public static void OpeningCNGAlgorithmFromProviderWithChainingModeCBC(this ILogger logger, string encryptionAlgorithm, string? encryptionAlgorithmProvider)
         {
             _openingCNGAlgorithmFromProviderWithChainingModeCBC(logger, encryptionAlgorithm, encryptionAlgorithmProvider, null);
         }
@@ -511,7 +512,7 @@ namespace Microsoft.Extensions.Logging
             _keyWasRevokedUnprotectOperationCannotProceed(logger, keyIdFromPayload, null);
         }
 
-        public static void OpeningCNGAlgorithmFromProviderWithChainingModeGCM(this ILogger logger, string encryptionAlgorithm, string encryptionAlgorithmProvider)
+        public static void OpeningCNGAlgorithmFromProviderWithChainingModeGCM(this ILogger logger, string encryptionAlgorithm, string? encryptionAlgorithmProvider)
         {
             _openingCNGAlgorithmFromProviderWithChainingModeGCM(logger, encryptionAlgorithm, encryptionAlgorithmProvider, null);
         }
@@ -576,7 +577,7 @@ namespace Microsoft.Extensions.Logging
             _exceptionWhileProcessingRevocationElement(logger, revocationElement, exception);
         }
 
-        public static void RevokingAllKeysAsOfForReason(this ILogger logger, DateTimeOffset revocationDate, string reason)
+        public static void RevokingAllKeysAsOfForReason(this ILogger logger, DateTimeOffset revocationDate, string? reason)
         {
             _revokingAllKeysAsOfForReason(logger, revocationDate, reason, null);
         }
@@ -641,7 +642,7 @@ namespace Microsoft.Extensions.Logging
             _noXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm(logger, keyId, null);
         }
 
-        public static void RevokingKeyForReason(this ILogger logger, Guid keyId, DateTimeOffset revocationDate, string reason)
+        public static void RevokingKeyForReason(this ILogger logger, Guid keyId, DateTimeOffset revocationDate, string? reason)
         {
             _revokingKeyForReason(logger, keyId, revocationDate, reason, null);
         }
@@ -671,7 +672,7 @@ namespace Microsoft.Extensions.Logging
             _nameIsNotSafeRegistryValueName(logger, friendlyName, newFriendlyName, null);
         }
 
-        public static void DecryptingSecretElementUsingWindowsDPAPING(this ILogger logger, string protectionDescriptorRule)
+        public static void DecryptingSecretElementUsingWindowsDPAPING(this ILogger logger, string? protectionDescriptorRule)
         {
             _decryptingSecretElementUsingWindowsDPAPING(logger, protectionDescriptorRule, null);
         }

+ 3 - 3
src/DataProtection/DataProtection/src/LoggingServiceProviderExtensions.cs

@@ -21,7 +21,7 @@ namespace System
         /// An <see cref="ILogger"/> instance, or null if <paramref name="services"/> is null or the
         /// <see cref="IServiceProvider"/> cannot produce an <see cref="ILoggerFactory"/>.
         /// </returns>
-        public static ILogger GetLogger<T>(this IServiceProvider services)
+        public static ILogger GetLogger<T>(this IServiceProvider? services)
         {
             return GetLogger(services, typeof(T));
         }
@@ -34,11 +34,11 @@ namespace System
         /// An <see cref="ILogger"/> instance, or null if <paramref name="services"/> is null or the
         /// <see cref="IServiceProvider"/> cannot produce an <see cref="ILoggerFactory"/>.
         /// </returns>
-        public static ILogger GetLogger(this IServiceProvider services, Type type)
+        public static ILogger GetLogger(this IServiceProvider? services, Type type)
         {
             // Compiler won't allow us to use static types as the type parameter
             // for the call to CreateLogger<T>, so we'll duplicate its logic here.
-            return services?.GetService<ILoggerFactory>()?.CreateLogger(type.FullName) ?? NullLogger.Instance;
+            return services?.GetService<ILoggerFactory>()?.CreateLogger(type.FullName!) ?? NullLogger.Instance;
         }
     }
 }

+ 4 - 4
src/DataProtection/DataProtection/src/Managed/ManagedAuthenticatedEncryptor.cs

@@ -38,7 +38,7 @@ namespace Microsoft.AspNetCore.DataProtection.Managed
         private readonly int _validationAlgorithmSubkeyLengthInBytes;
         private readonly Func<KeyedHashAlgorithm> _validationAlgorithmFactory;
 
-        public ManagedAuthenticatedEncryptor(Secret keyDerivationKey, Func<SymmetricAlgorithm> symmetricAlgorithmFactory, int symmetricAlgorithmKeySizeInBytes, Func<KeyedHashAlgorithm> validationAlgorithmFactory, IManagedGenRandom genRandom = null)
+        public ManagedAuthenticatedEncryptor(Secret keyDerivationKey, Func<SymmetricAlgorithm> symmetricAlgorithmFactory, int symmetricAlgorithmKeySizeInBytes, Func<KeyedHashAlgorithm> validationAlgorithmFactory, IManagedGenRandom? genRandom = null)
         {
             _genRandom = genRandom ?? ManagedGenRandomImpl.Instance;
             _keyDerivationKey = keyDerivationKey;
@@ -186,9 +186,9 @@ namespace Microsoft.AspNetCore.DataProtection.Managed
                     ciphertextOffset = ivOffset + _symmetricAlgorithmBlockSizeInBytes;
                 }
 
-                ArraySegment<byte> keyModifier = new ArraySegment<byte>(protectedPayload.Array, keyModifierOffset, ivOffset - keyModifierOffset);
+                ArraySegment<byte> keyModifier = new ArraySegment<byte>(protectedPayload.Array!, keyModifierOffset, ivOffset - keyModifierOffset);
                 var iv = new byte[_symmetricAlgorithmBlockSizeInBytes];
-                Buffer.BlockCopy(protectedPayload.Array, ivOffset, iv, 0, iv.Length);
+                Buffer.BlockCopy(protectedPayload.Array!, ivOffset, iv, 0, iv.Length);
 
                 // Step 2: Decrypt the KDK and use it to restore the original encryption and MAC keys.
                 // We pin all unencrypted keys to limit their exposure via GC relocation.
@@ -332,7 +332,7 @@ namespace Microsoft.AspNetCore.DataProtection.Managed
                         using (var cryptoTransform = symmetricAlgorithm.CreateEncryptor(encryptionSubkey, iv))
                         using (var cryptoStream = new CryptoStream(outputStream, cryptoTransform, CryptoStreamMode.Write))
                         {
-                            cryptoStream.Write(plaintext.Array, plaintext.Offset, plaintext.Count);
+                            cryptoStream.Write(plaintext.Array!, plaintext.Offset, plaintext.Count);
                             cryptoStream.FlushFinalBlock();
 
                             // At this point, outputStream := { keyModifier || IV || ciphertext }

+ 3 - 1
src/DataProtection/DataProtection/src/Microsoft.AspNetCore.DataProtection.csproj

@@ -1,4 +1,4 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
 
   <PropertyGroup>
     <Description>ASP.NET Core logic to protect and unprotect data, similar to DPAPI.</Description>
@@ -9,7 +9,9 @@
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <GenerateDocumentationFile>true</GenerateDocumentationFile>
     <PackageTags>aspnetcore;dataprotection</PackageTags>
+    <SuppressNullableAttributesImport>true</SuppressNullableAttributesImport>
     <Nullable>annotations</Nullable>
+    <Nullable Condition="'$(TargetFramework)' == '$(DefaultNetCoreTargetFramework)'">enable</Nullable>
   </PropertyGroup>
 
   <ItemGroup>

+ 29 - 29
src/DataProtection/DataProtection/src/PublicAPI.Shipped.txt

@@ -1,13 +1,13 @@
 #nullable enable
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.AuthenticatedEncryptorFactory
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.AuthenticatedEncryptorFactory.AuthenticatedEncryptorFactory(Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> void
-Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.AuthenticatedEncryptorFactory.CreateEncryptorInstance(Microsoft.AspNetCore.DataProtection.KeyManagement.IKey! key) -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor!
+Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.AuthenticatedEncryptorFactory.CreateEncryptorInstance(Microsoft.AspNetCore.DataProtection.KeyManagement.IKey! key) -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor?
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngCbcAuthenticatedEncryptorFactory
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngCbcAuthenticatedEncryptorFactory.CngCbcAuthenticatedEncryptorFactory(Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> void
-Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngCbcAuthenticatedEncryptorFactory.CreateEncryptorInstance(Microsoft.AspNetCore.DataProtection.KeyManagement.IKey! key) -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor!
+Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngCbcAuthenticatedEncryptorFactory.CreateEncryptorInstance(Microsoft.AspNetCore.DataProtection.KeyManagement.IKey! key) -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor?
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngGcmAuthenticatedEncryptorFactory
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngGcmAuthenticatedEncryptorFactory.CngGcmAuthenticatedEncryptorFactory(Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> void
-Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngGcmAuthenticatedEncryptorFactory.CreateEncryptorInstance(Microsoft.AspNetCore.DataProtection.KeyManagement.IKey! key) -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor!
+Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.CngGcmAuthenticatedEncryptorFactory.CreateEncryptorInstance(Microsoft.AspNetCore.DataProtection.KeyManagement.IKey! key) -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor?
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AlgorithmConfiguration
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AlgorithmConfiguration.AlgorithmConfiguration() -> void
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorConfiguration
@@ -28,11 +28,11 @@ Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.C
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorConfiguration.EncryptionAlgorithm.set -> void
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorConfiguration.EncryptionAlgorithmKeySize.get -> int
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorConfiguration.EncryptionAlgorithmKeySize.set -> void
-Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorConfiguration.EncryptionAlgorithmProvider.get -> string!
+Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorConfiguration.EncryptionAlgorithmProvider.get -> string?
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorConfiguration.EncryptionAlgorithmProvider.set -> void
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorConfiguration.HashAlgorithm.get -> string!
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorConfiguration.HashAlgorithm.set -> void
-Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorConfiguration.HashAlgorithmProvider.get -> string!
+Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorConfiguration.HashAlgorithmProvider.get -> string?
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorConfiguration.HashAlgorithmProvider.set -> void
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorDescriptor
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorDescriptor.CngCbcAuthenticatedEncryptorDescriptor(Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngCbcAuthenticatedEncryptorConfiguration! configuration, Microsoft.AspNetCore.DataProtection.ISecret! masterKey) -> void
@@ -46,7 +46,7 @@ Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.C
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngGcmAuthenticatedEncryptorConfiguration.EncryptionAlgorithm.set -> void
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngGcmAuthenticatedEncryptorConfiguration.EncryptionAlgorithmKeySize.get -> int
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngGcmAuthenticatedEncryptorConfiguration.EncryptionAlgorithmKeySize.set -> void
-Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngGcmAuthenticatedEncryptorConfiguration.EncryptionAlgorithmProvider.get -> string!
+Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngGcmAuthenticatedEncryptorConfiguration.EncryptionAlgorithmProvider.get -> string?
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngGcmAuthenticatedEncryptorConfiguration.EncryptionAlgorithmProvider.set -> void
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngGcmAuthenticatedEncryptorDescriptor
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngGcmAuthenticatedEncryptorDescriptor.CngGcmAuthenticatedEncryptorDescriptor(Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngGcmAuthenticatedEncryptorConfiguration! configuration, Microsoft.AspNetCore.DataProtection.ISecret! masterKey) -> void
@@ -88,16 +88,16 @@ Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryp
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor.Decrypt(System.ArraySegment<byte> ciphertext, System.ArraySegment<byte> additionalAuthenticatedData) -> byte[]!
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor.Encrypt(System.ArraySegment<byte> plaintext, System.ArraySegment<byte> additionalAuthenticatedData) -> byte[]!
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptorFactory
-Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptorFactory.CreateEncryptorInstance(Microsoft.AspNetCore.DataProtection.KeyManagement.IKey! key) -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor!
+Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptorFactory.CreateEncryptorInstance(Microsoft.AspNetCore.DataProtection.KeyManagement.IKey! key) -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor?
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ManagedAuthenticatedEncryptorFactory
-Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ManagedAuthenticatedEncryptorFactory.CreateEncryptorInstance(Microsoft.AspNetCore.DataProtection.KeyManagement.IKey! key) -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor!
+Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ManagedAuthenticatedEncryptorFactory.CreateEncryptorInstance(Microsoft.AspNetCore.DataProtection.KeyManagement.IKey! key) -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor?
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ManagedAuthenticatedEncryptorFactory.ManagedAuthenticatedEncryptorFactory(Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> void
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ValidationAlgorithm
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ValidationAlgorithm.HMACSHA256 = 0 -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ValidationAlgorithm
 Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ValidationAlgorithm.HMACSHA512 = 1 -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ValidationAlgorithm
 Microsoft.AspNetCore.DataProtection.DataProtectionBuilderExtensions
 Microsoft.AspNetCore.DataProtection.DataProtectionOptions
-Microsoft.AspNetCore.DataProtection.DataProtectionOptions.ApplicationDiscriminator.get -> string!
+Microsoft.AspNetCore.DataProtection.DataProtectionOptions.ApplicationDiscriminator.get -> string?
 Microsoft.AspNetCore.DataProtection.DataProtectionOptions.ApplicationDiscriminator.set -> void
 Microsoft.AspNetCore.DataProtection.DataProtectionOptions.DataProtectionOptions() -> void
 Microsoft.AspNetCore.DataProtection.DataProtectionUtilityExtensions
@@ -116,7 +116,7 @@ Microsoft.AspNetCore.DataProtection.Internal.IActivator
 Microsoft.AspNetCore.DataProtection.Internal.IActivator.CreateInstance(System.Type! expectedBaseType, string! implementationTypeName) -> object!
 Microsoft.AspNetCore.DataProtection.KeyManagement.IKey
 Microsoft.AspNetCore.DataProtection.KeyManagement.IKey.ActivationDate.get -> System.DateTimeOffset
-Microsoft.AspNetCore.DataProtection.KeyManagement.IKey.CreateEncryptor() -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor!
+Microsoft.AspNetCore.DataProtection.KeyManagement.IKey.CreateEncryptor() -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor?
 Microsoft.AspNetCore.DataProtection.KeyManagement.IKey.CreationDate.get -> System.DateTimeOffset
 Microsoft.AspNetCore.DataProtection.KeyManagement.IKey.Descriptor.get -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.IAuthenticatedEncryptorDescriptor!
 Microsoft.AspNetCore.DataProtection.KeyManagement.IKey.ExpirationDate.get -> System.DateTimeOffset
@@ -132,9 +132,9 @@ Microsoft.AspNetCore.DataProtection.KeyManagement.IKeyManager.RevokeAllKeys(Syst
 Microsoft.AspNetCore.DataProtection.KeyManagement.IKeyManager.RevokeKey(System.Guid keyId, string! reason = null) -> void
 Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.CacheableKeyRing
 Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.DefaultKeyResolution
-Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.DefaultKeyResolution.DefaultKey -> Microsoft.AspNetCore.DataProtection.KeyManagement.IKey!
+Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.DefaultKeyResolution.DefaultKey -> Microsoft.AspNetCore.DataProtection.KeyManagement.IKey?
 Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.DefaultKeyResolution.DefaultKeyResolution() -> void
-Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.DefaultKeyResolution.FallbackKey -> Microsoft.AspNetCore.DataProtection.KeyManagement.IKey!
+Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.DefaultKeyResolution.FallbackKey -> Microsoft.AspNetCore.DataProtection.KeyManagement.IKey?
 Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.DefaultKeyResolution.ShouldGenerateNewKey -> bool
 Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.ICacheableKeyRingProvider
 Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.ICacheableKeyRingProvider.GetCacheableKeyRing(System.DateTimeOffset now) -> Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.CacheableKeyRing!
@@ -143,15 +143,15 @@ Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IDefaultKeyResolver.R
 Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IInternalXmlKeyManager
 Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IInternalXmlKeyManager.CreateNewKey(System.Guid keyId, System.DateTimeOffset creationDate, System.DateTimeOffset activationDate, System.DateTimeOffset expirationDate) -> Microsoft.AspNetCore.DataProtection.KeyManagement.IKey!
 Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IInternalXmlKeyManager.DeserializeDescriptorFromKeyElement(System.Xml.Linq.XElement! keyElement) -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.IAuthenticatedEncryptorDescriptor!
-Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IInternalXmlKeyManager.RevokeSingleKey(System.Guid keyId, System.DateTimeOffset revocationDate, string! reason) -> void
+Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IInternalXmlKeyManager.RevokeSingleKey(System.Guid keyId, System.DateTimeOffset revocationDate, string? reason) -> void
 Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IKeyRing
-Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IKeyRing.DefaultAuthenticatedEncryptor.get -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor!
+Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IKeyRing.DefaultAuthenticatedEncryptor.get -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor?
 Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IKeyRing.DefaultKeyId.get -> System.Guid
-Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IKeyRing.GetAuthenticatedEncryptorByKeyId(System.Guid keyId, out bool isRevoked) -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor!
+Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IKeyRing.GetAuthenticatedEncryptorByKeyId(System.Guid keyId, out bool isRevoked) -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptor?
 Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IKeyRingProvider
 Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IKeyRingProvider.GetCurrentKeyRing() -> Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IKeyRing!
 Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions
-Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.AuthenticatedEncryptorConfiguration.get -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AlgorithmConfiguration!
+Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.AuthenticatedEncryptorConfiguration.get -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AlgorithmConfiguration?
 Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.AuthenticatedEncryptorConfiguration.set -> void
 Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.AuthenticatedEncryptorFactories.get -> System.Collections.Generic.IList<Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.IAuthenticatedEncryptorFactory!>!
 Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.AutoGenerateKeys.get -> bool
@@ -160,16 +160,16 @@ Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.KeyEscrow
 Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.KeyManagementOptions() -> void
 Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.NewKeyLifetime.get -> System.TimeSpan
 Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.NewKeyLifetime.set -> void
-Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.XmlEncryptor.get -> Microsoft.AspNetCore.DataProtection.XmlEncryption.IXmlEncryptor!
+Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.XmlEncryptor.get -> Microsoft.AspNetCore.DataProtection.XmlEncryption.IXmlEncryptor?
 Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.XmlEncryptor.set -> void
-Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.XmlRepository.get -> Microsoft.AspNetCore.DataProtection.Repositories.IXmlRepository!
+Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.XmlRepository.get -> Microsoft.AspNetCore.DataProtection.Repositories.IXmlRepository?
 Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions.XmlRepository.set -> void
 Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager
 Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager.CreateNewKey(System.DateTimeOffset activationDate, System.DateTimeOffset expirationDate) -> Microsoft.AspNetCore.DataProtection.KeyManagement.IKey!
 Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager.GetAllKeys() -> System.Collections.Generic.IReadOnlyCollection<Microsoft.AspNetCore.DataProtection.KeyManagement.IKey!>!
 Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager.GetCacheExpirationToken() -> System.Threading.CancellationToken
-Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager.RevokeAllKeys(System.DateTimeOffset revocationDate, string! reason = null) -> void
-Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager.RevokeKey(System.Guid keyId, string! reason = null) -> void
+Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager.RevokeAllKeys(System.DateTimeOffset revocationDate, string? reason = null) -> void
+Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager.RevokeKey(System.Guid keyId, string? reason = null) -> void
 Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository
 Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository.Directory.get -> System.IO.DirectoryInfo!
 Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository.FileSystemXmlRepository(System.IO.DirectoryInfo! directory, Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> void
@@ -201,27 +201,27 @@ Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiNGProtectionDescriptorFla
 Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiNGXmlDecryptor
 Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiNGXmlDecryptor.Decrypt(System.Xml.Linq.XElement! encryptedElement) -> System.Xml.Linq.XElement!
 Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiNGXmlDecryptor.DpapiNGXmlDecryptor() -> void
-Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiNGXmlDecryptor.DpapiNGXmlDecryptor(System.IServiceProvider! services) -> void
+Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiNGXmlDecryptor.DpapiNGXmlDecryptor(System.IServiceProvider? services) -> void
 Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiNGXmlEncryptor
 Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiNGXmlEncryptor.DpapiNGXmlEncryptor(string! protectionDescriptorRule, Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiNGProtectionDescriptorFlags flags, Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> void
 Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiNGXmlEncryptor.Encrypt(System.Xml.Linq.XElement! plaintextElement) -> Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlInfo!
 Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor
 Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor.Decrypt(System.Xml.Linq.XElement! encryptedElement) -> System.Xml.Linq.XElement!
 Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor.DpapiXmlDecryptor() -> void
-Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor.DpapiXmlDecryptor(System.IServiceProvider! services) -> void
+Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor.DpapiXmlDecryptor(System.IServiceProvider? services) -> void
 Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlEncryptor
 Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlEncryptor.DpapiXmlEncryptor(bool protectToLocalMachine, Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> void
 Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlEncryptor.Encrypt(System.Xml.Linq.XElement! plaintextElement) -> Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlInfo!
 Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlDecryptor
 Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlDecryptor.Decrypt(System.Xml.Linq.XElement! encryptedElement) -> System.Xml.Linq.XElement!
 Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlDecryptor.EncryptedXmlDecryptor() -> void
-Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlDecryptor.EncryptedXmlDecryptor(System.IServiceProvider! services) -> void
+Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlDecryptor.EncryptedXmlDecryptor(System.IServiceProvider? services) -> void
 Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlInfo
 Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlInfo.DecryptorType.get -> System.Type!
 Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlInfo.EncryptedElement.get -> System.Xml.Linq.XElement!
 Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlInfo.EncryptedXmlInfo(System.Xml.Linq.XElement! encryptedElement, System.Type! decryptorType) -> void
 Microsoft.AspNetCore.DataProtection.XmlEncryption.ICertificateResolver
-Microsoft.AspNetCore.DataProtection.XmlEncryption.ICertificateResolver.ResolveCertificate(string! thumbprint) -> System.Security.Cryptography.X509Certificates.X509Certificate2!
+Microsoft.AspNetCore.DataProtection.XmlEncryption.ICertificateResolver.ResolveCertificate(string! thumbprint) -> System.Security.Cryptography.X509Certificates.X509Certificate2?
 Microsoft.AspNetCore.DataProtection.XmlEncryption.IXmlDecryptor
 Microsoft.AspNetCore.DataProtection.XmlEncryption.IXmlDecryptor.Decrypt(System.Xml.Linq.XElement! encryptedElement) -> System.Xml.Linq.XElement!
 Microsoft.AspNetCore.DataProtection.XmlEncryption.IXmlEncryptor
@@ -232,7 +232,7 @@ Microsoft.AspNetCore.DataProtection.XmlEncryption.NullXmlDecryptor.NullXmlDecryp
 Microsoft.AspNetCore.DataProtection.XmlEncryption.NullXmlEncryptor
 Microsoft.AspNetCore.DataProtection.XmlEncryption.NullXmlEncryptor.Encrypt(System.Xml.Linq.XElement! plaintextElement) -> Microsoft.AspNetCore.DataProtection.XmlEncryption.EncryptedXmlInfo!
 Microsoft.AspNetCore.DataProtection.XmlEncryption.NullXmlEncryptor.NullXmlEncryptor() -> void
-Microsoft.AspNetCore.DataProtection.XmlEncryption.NullXmlEncryptor.NullXmlEncryptor(System.IServiceProvider! services) -> void
+Microsoft.AspNetCore.DataProtection.XmlEncryption.NullXmlEncryptor.NullXmlEncryptor(System.IServiceProvider? services) -> void
 Microsoft.Extensions.DependencyInjection.DataProtectionServiceCollectionExtensions
 abstract Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AlgorithmConfiguration.CreateNewDescriptor() -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.IAuthenticatedEncryptorDescriptor!
 override Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorConfiguration.CreateNewDescriptor() -> Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.IAuthenticatedEncryptorDescriptor!
@@ -261,9 +261,9 @@ static Microsoft.AspNetCore.DataProtection.DataProtectionBuilderExtensions.UseCu
 static Microsoft.AspNetCore.DataProtection.DataProtectionBuilderExtensions.UseCustomCryptographicAlgorithms(this Microsoft.AspNetCore.DataProtection.IDataProtectionBuilder! builder, Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.CngGcmAuthenticatedEncryptorConfiguration! configuration) -> Microsoft.AspNetCore.DataProtection.IDataProtectionBuilder!
 static Microsoft.AspNetCore.DataProtection.DataProtectionBuilderExtensions.UseCustomCryptographicAlgorithms(this Microsoft.AspNetCore.DataProtection.IDataProtectionBuilder! builder, Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.ManagedAuthenticatedEncryptorConfiguration! configuration) -> Microsoft.AspNetCore.DataProtection.IDataProtectionBuilder!
 static Microsoft.AspNetCore.DataProtection.DataProtectionBuilderExtensions.UseEphemeralDataProtectionProvider(this Microsoft.AspNetCore.DataProtection.IDataProtectionBuilder! builder) -> Microsoft.AspNetCore.DataProtection.IDataProtectionBuilder!
-static Microsoft.AspNetCore.DataProtection.DataProtectionUtilityExtensions.GetApplicationUniqueIdentifier(this System.IServiceProvider! services) -> string!
-static Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository.DefaultKeyStorageDirectory.get -> System.IO.DirectoryInfo!
-static Microsoft.AspNetCore.DataProtection.Repositories.RegistryXmlRepository.DefaultRegistryKey.get -> Microsoft.Win32.RegistryKey!
+static Microsoft.AspNetCore.DataProtection.DataProtectionUtilityExtensions.GetApplicationUniqueIdentifier(this System.IServiceProvider! services) -> string?
+static Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository.DefaultKeyStorageDirectory.get -> System.IO.DirectoryInfo?
+static Microsoft.AspNetCore.DataProtection.Repositories.RegistryXmlRepository.DefaultRegistryKey.get -> Microsoft.Win32.RegistryKey?
 static Microsoft.AspNetCore.DataProtection.Secret.Random(int numBytes) -> Microsoft.AspNetCore.DataProtection.Secret!
 static Microsoft.Extensions.DependencyInjection.DataProtectionServiceCollectionExtensions.AddDataProtection(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.AspNetCore.DataProtection.IDataProtectionBuilder!
 static Microsoft.Extensions.DependencyInjection.DataProtectionServiceCollectionExtensions.AddDataProtection(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action<Microsoft.AspNetCore.DataProtection.DataProtectionOptions!>! setupAction) -> Microsoft.AspNetCore.DataProtection.IDataProtectionBuilder!
@@ -271,6 +271,6 @@ virtual Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository
 virtual Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository.StoreElement(System.Xml.Linq.XElement! element, string! friendlyName) -> void
 virtual Microsoft.AspNetCore.DataProtection.Repositories.RegistryXmlRepository.GetAllElements() -> System.Collections.Generic.IReadOnlyCollection<System.Xml.Linq.XElement!>!
 virtual Microsoft.AspNetCore.DataProtection.Repositories.RegistryXmlRepository.StoreElement(System.Xml.Linq.XElement! element, string! friendlyName) -> void
-virtual Microsoft.AspNetCore.DataProtection.XmlEncryption.CertificateResolver.ResolveCertificate(string! thumbprint) -> System.Security.Cryptography.X509Certificates.X509Certificate2!
+virtual Microsoft.AspNetCore.DataProtection.XmlEncryption.CertificateResolver.ResolveCertificate(string! thumbprint) -> System.Security.Cryptography.X509Certificates.X509Certificate2?
 ~Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager.XmlKeyManager(Microsoft.Extensions.Options.IOptions<Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions!>! keyManagementOptions, Microsoft.AspNetCore.DataProtection.Internal.IActivator! activator) -> void
 ~Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager.XmlKeyManager(Microsoft.Extensions.Options.IOptions<Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions!>! keyManagementOptions, Microsoft.AspNetCore.DataProtection.Internal.IActivator! activator, Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> void

+ 3 - 3
src/DataProtection/DataProtection/src/RegistryPolicy.cs

@@ -1,4 +1,4 @@
-// Copyright (c) .NET Foundation. All rights reserved.
+// Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 using System.Collections.Generic;
@@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.DataProtection
     internal class RegistryPolicy
     {
         public RegistryPolicy(
-            AlgorithmConfiguration configuration,
+            AlgorithmConfiguration? configuration,
             IEnumerable<IKeyEscrowSink> keyEscrowSinks,
             int? defaultKeyLifetime)
         {
@@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.DataProtection
             DefaultKeyLifetime = defaultKeyLifetime;
         }
 
-        public AlgorithmConfiguration EncryptorConfiguration { get; }
+        public AlgorithmConfiguration? EncryptorConfiguration { get; }
 
         public IEnumerable<IKeyEscrowSink> KeyEscrowSinks { get; }
 

+ 8 - 8
src/DataProtection/DataProtection/src/RegistryPolicyResolver.cs

@@ -21,7 +21,7 @@ namespace Microsoft.AspNetCore.DataProtection
     [SupportedOSPlatform("windows")]
     internal sealed class RegistryPolicyResolver: IRegistryPolicyResolver
     {
-        private readonly Func<RegistryKey> _getPolicyRegKey;
+        private readonly Func<RegistryKey?> _getPolicyRegKey;
         private readonly IActivator _activator;
 
         public RegistryPolicyResolver(IActivator activator)
@@ -56,7 +56,7 @@ namespace Microsoft.AspNetCore.DataProtection
                         }
                         else if (propInfo.PropertyType == typeof(Type))
                         {
-                            propInfo.SetValue(options, Type.GetType(Convert.ToString(valueFromRegistry, CultureInfo.InvariantCulture), throwOnError: true));
+                            propInfo.SetValue(options, Type.GetType(Convert.ToString(valueFromRegistry, CultureInfo.InvariantCulture)!, throwOnError: true));
                         }
                         else
                         {
@@ -73,7 +73,7 @@ namespace Microsoft.AspNetCore.DataProtection
 
             // The format of this key is "type1; type2; ...".
             // We call Type.GetType to perform an eager check that the type exists.
-            var sinksFromRegistry = (string)key.GetValue("KeyEscrowSinks");
+            var sinksFromRegistry = (string?)key.GetValue("KeyEscrowSinks");
             if (sinksFromRegistry != null)
             {
                 foreach (string sinkFromRegistry in sinksFromRegistry.Split(';'))
@@ -81,7 +81,7 @@ namespace Microsoft.AspNetCore.DataProtection
                     var candidate = sinkFromRegistry.Trim();
                     if (!String.IsNullOrEmpty(candidate))
                     {
-                        typeof(IKeyEscrowSink).AssertIsAssignableFrom(Type.GetType(candidate, throwOnError: true));
+                        typeof(IKeyEscrowSink).AssertIsAssignableFrom(Type.GetType(candidate, throwOnError: true)!);
                         sinks.Add(candidate);
                     }
                 }
@@ -90,7 +90,7 @@ namespace Microsoft.AspNetCore.DataProtection
             return sinks;
         }
 
-        public RegistryPolicy ResolvePolicy()
+        public RegistryPolicy? ResolvePolicy()
         {
             using (var registryKey = _getPolicyRegKey())
             {
@@ -98,7 +98,7 @@ namespace Microsoft.AspNetCore.DataProtection
             }
         }
 
-        private RegistryPolicy ResolvePolicyCore(RegistryKey policyRegKey)
+        private RegistryPolicy? ResolvePolicyCore(RegistryKey? policyRegKey)
         {
             if (policyRegKey == null)
             {
@@ -106,9 +106,9 @@ namespace Microsoft.AspNetCore.DataProtection
             }
 
             // Read the encryption options type: CNG-CBC, CNG-GCM, Managed
-            AlgorithmConfiguration configuration = null;
+            AlgorithmConfiguration? configuration = null;
 
-            var encryptionType = (string)policyRegKey.GetValue("EncryptionType");
+            var encryptionType = (string?)policyRegKey.GetValue("EncryptionType");
             if (String.Equals(encryptionType, "CNG-CBC", StringComparison.OrdinalIgnoreCase))
             {
                 configuration = new CngCbcAuthenticatedEncryptorConfiguration();

+ 5 - 5
src/DataProtection/DataProtection/src/Repositories/DefaultKeyStorageDirectories.cs

@@ -1,4 +1,4 @@
-// Copyright (c) .NET Foundation. All rights reserved.
+// Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 using System;
@@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.DataProtection.Repositories
 {
     internal sealed class DefaultKeyStorageDirectories : IDefaultKeyStorageDirectories
     {
-        private static readonly Lazy<DirectoryInfo> _defaultDirectoryLazy = new Lazy<DirectoryInfo>(GetKeyStorageDirectoryImpl);
+        private static readonly Lazy<DirectoryInfo?> _defaultDirectoryLazy = new Lazy<DirectoryInfo?>(GetKeyStorageDirectoryImpl);
 
         private DefaultKeyStorageDirectories()
         {
@@ -27,9 +27,9 @@ namespace Microsoft.AspNetCore.DataProtection.Repositories
         /// This property can return null if no suitable default key storage directory can
         /// be found, such as the case when the user profile is unavailable.
         /// </remarks>
-        public DirectoryInfo GetKeyStorageDirectory() => _defaultDirectoryLazy.Value;
+        public DirectoryInfo? GetKeyStorageDirectory() => _defaultDirectoryLazy.Value;
 
-        private static DirectoryInfo GetKeyStorageDirectoryImpl()
+        private static DirectoryInfo? GetKeyStorageDirectoryImpl()
         {
             DirectoryInfo retVal;
 
@@ -83,7 +83,7 @@ namespace Microsoft.AspNetCore.DataProtection.Repositories
             }
         }
 
-        public DirectoryInfo GetKeyStorageDirectoryForAzureWebSites()
+        public DirectoryInfo? GetKeyStorageDirectoryForAzureWebSites()
         {
             // Azure Web Sites needs to be treated specially, as we need to store the keys in a
             // correct persisted location. We use the existence of the %WEBSITE_INSTANCE_ID% env

+ 1 - 1
src/DataProtection/DataProtection/src/Repositories/FileSystemXmlRepository.cs

@@ -55,7 +55,7 @@ namespace Microsoft.AspNetCore.DataProtection.Repositories
         /// This property can return null if no suitable default key storage directory can
         /// be found, such as the case when the user profile is unavailable.
         /// </remarks>
-        public static DirectoryInfo DefaultKeyStorageDirectory => DefaultKeyStorageDirectories.Instance.GetKeyStorageDirectory();
+        public static DirectoryInfo? DefaultKeyStorageDirectory => DefaultKeyStorageDirectories.Instance.GetKeyStorageDirectory();
 
         /// <summary>
         /// The directory into which key material will be written.

+ 3 - 3
src/DataProtection/DataProtection/src/Repositories/IDefaultKeyStorageDirectory.cs

@@ -1,4 +1,4 @@
-// Copyright (c) .NET Foundation. All rights reserved.
+// Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 using System.IO;
@@ -10,8 +10,8 @@ namespace Microsoft.AspNetCore.DataProtection.Repositories
     /// </summary>
     internal interface IDefaultKeyStorageDirectories
     {
-        DirectoryInfo GetKeyStorageDirectory();
+        DirectoryInfo? GetKeyStorageDirectory();
 
-        DirectoryInfo GetKeyStorageDirectoryForAzureWebSites();
+        DirectoryInfo? GetKeyStorageDirectoryForAzureWebSites();
     }
 }

+ 6 - 6
src/DataProtection/DataProtection/src/Repositories/RegistryXmlRepository.cs

@@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.DataProtection.Repositories
     [SupportedOSPlatform("windows")]
     public class RegistryXmlRepository : IXmlRepository
     {
-        private static readonly Lazy<RegistryKey> _defaultRegistryKeyLazy = new Lazy<RegistryKey>(GetDefaultHklmStorageKey);
+        private static readonly Lazy<RegistryKey?> _defaultRegistryKeyLazy = new Lazy<RegistryKey?>(GetDefaultHklmStorageKey);
 
         private readonly ILogger _logger;
 
@@ -47,7 +47,7 @@ namespace Microsoft.AspNetCore.DataProtection.Repositories
         /// This property can return null if no suitable default registry key can
         /// be found, such as the case when this application is not hosted inside IIS.
         /// </remarks>
-        public static RegistryKey DefaultRegistryKey => _defaultRegistryKeyLazy.Value;
+        public static RegistryKey? DefaultRegistryKey => _defaultRegistryKeyLazy.Value;
 
         /// <summary>
         /// The registry key into which key material will be written.
@@ -78,7 +78,7 @@ namespace Microsoft.AspNetCore.DataProtection.Repositories
             }
         }
 
-        private static RegistryKey GetDefaultHklmStorageKey()
+        private static RegistryKey? GetDefaultHklmStorageKey()
         {
             try
             {
@@ -92,7 +92,7 @@ namespace Microsoft.AspNetCore.DataProtection.Repositories
                     var aspnetAutoGenKeysBaseKeyName = string.Format(
                         CultureInfo.InvariantCulture,
                         @"SOFTWARE\Microsoft\ASP.NET\4.0.30319.0\AutoGenKeys\{0}",
-                        WindowsIdentity.GetCurrent().User.Value);
+                        WindowsIdentity.GetCurrent()!.User!.Value);
 
                     var aspnetBaseKey = hklmBaseKey.OpenSubKey(aspnetAutoGenKeysBaseKeyName, writable: true);
                     if (aspnetBaseKey != null)
@@ -125,12 +125,12 @@ namespace Microsoft.AspNetCore.DataProtection.Repositories
                 || ('a' <= c && c <= 'z')));
         }
 
-        private XElement ReadElementFromRegKey(RegistryKey regKey, string valueName)
+        private XElement? ReadElementFromRegKey(RegistryKey regKey, string valueName)
         {
             _logger.ReadingDataFromRegistryKeyValue(regKey, valueName);
 
             var data = regKey.GetValue(valueName) as string;
-            return (!String.IsNullOrEmpty(data)) ? XElement.Parse(data) : null;
+            return (!string.IsNullOrEmpty(data)) ? XElement.Parse(data) : null;
         }
 
         public virtual void StoreElement(XElement element, string friendlyName)

+ 4 - 4
src/DataProtection/DataProtection/src/SP800_108/ManagedSP800_108_CTR_HMACSHA512.cs

@@ -29,8 +29,8 @@ namespace Microsoft.AspNetCore.DataProtection.SP800_108
                 prfInput[prfInput.Length - 1] = (byte)(outputSizeInBits);
 
                 // Copy label and context to prfInput since they're stable over all iterations
-                Buffer.BlockCopy(label.Array, label.Offset, prfInput, sizeof(uint), label.Count);
-                Buffer.BlockCopy(context.Array, context.Offset, prfInput, sizeof(int) + label.Count + 1, context.Count);
+                Buffer.BlockCopy(label.Array!, label.Offset, prfInput, sizeof(uint), label.Count);
+                Buffer.BlockCopy(context.Array!, context.Offset, prfInput, sizeof(int) + label.Count + 1, context.Count);
 
                 var prfOutputSizeInBytes = prf.GetDigestSizeInBytes();
                 for (uint i = 1; outputCount > 0; i++)
@@ -45,7 +45,7 @@ namespace Microsoft.AspNetCore.DataProtection.SP800_108
                     var prfOutput = prf.ComputeHash(prfInput);
                     CryptoUtil.Assert(prfOutputSizeInBytes == prfOutput.Length, "prfOutputSizeInBytes == prfOutput.Length");
                     var numBytesToCopyThisIteration = Math.Min(prfOutputSizeInBytes, outputCount);
-                    Buffer.BlockCopy(prfOutput, 0, output.Array, outputOffset, numBytesToCopyThisIteration);
+                    Buffer.BlockCopy(prfOutput, 0, output.Array!, outputOffset, numBytesToCopyThisIteration);
                     Array.Clear(prfOutput, 0, prfOutput.Length); // contains key material, so delete it
 
                     // adjust offsets
@@ -59,7 +59,7 @@ namespace Microsoft.AspNetCore.DataProtection.SP800_108
         {
             var combinedContext = new byte[checked(contextHeader.Length + context.Count)];
             Buffer.BlockCopy(contextHeader, 0, combinedContext, 0, contextHeader.Length);
-            Buffer.BlockCopy(context.Array, context.Offset, combinedContext, contextHeader.Length, context.Count);
+            Buffer.BlockCopy(context.Array!, context.Offset, combinedContext, contextHeader.Length, context.Count);
             DeriveKeys(kdk, label, new ArraySegment<byte>(combinedContext), prfFactory, output);
         }
     }

+ 1 - 1
src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Extensions.cs

@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.DataProtection.SP800_108
             var cbCombinedContext = checked((uint)contextHeader.Length + cbContext);
 
             // Try allocating the combined context on the stack to avoid temporary managed objects; only fall back to heap if buffers are too large.
-            byte[] heapAllocatedCombinedContext = (cbCombinedContext > Constants.MAX_STACKALLOC_BYTES) ? new byte[cbCombinedContext] : null;
+            byte[]? heapAllocatedCombinedContext = (cbCombinedContext > Constants.MAX_STACKALLOC_BYTES) ? new byte[cbCombinedContext] : null;
             fixed (byte* pbHeapAllocatedCombinedContext = heapAllocatedCombinedContext)
             {
                 byte* pbCombinedContext = pbHeapAllocatedCombinedContext;

+ 6 - 6
src/DataProtection/DataProtection/src/SimpleActivator.cs

@@ -18,9 +18,9 @@ namespace Microsoft.AspNetCore.DataProtection
         /// </summary>
         internal static readonly SimpleActivator DefaultWithoutServices = new SimpleActivator(null);
 
-        private readonly IServiceProvider _services;
+        private readonly IServiceProvider? _services;
 
-        public SimpleActivator(IServiceProvider services)
+        public SimpleActivator(IServiceProvider? services)
         {
             _services = services;
         }
@@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.DataProtection
         public virtual object CreateInstance(Type expectedBaseType, string implementationTypeName)
         {
             // Would the assignment even work?
-            var implementationType = Type.GetType(implementationTypeName, throwOnError: true);
+            var implementationType = Type.GetType(implementationTypeName, throwOnError: true)!;
             expectedBaseType.AssertIsAssignableFrom(implementationType);
 
             // If no IServiceProvider was specified, prefer .ctor() [if it exists]
@@ -37,7 +37,7 @@ namespace Microsoft.AspNetCore.DataProtection
                 var ctorParameterless = implementationType.GetConstructor(Type.EmptyTypes);
                 if (ctorParameterless != null)
                 {
-                    return Activator.CreateInstance(implementationType);
+                    return Activator.CreateInstance(implementationType)!;
                 }
             }
 
@@ -50,7 +50,7 @@ namespace Microsoft.AspNetCore.DataProtection
 
             // Finally, prefer .ctor() as an ultimate fallback.
             // This will throw if the ctor cannot be called.
-            return Activator.CreateInstance(implementationType);
+            return Activator.CreateInstance(implementationType)!;
         }
     }
-}
+}

+ 2 - 2
src/DataProtection/DataProtection/src/XmlEncryption/CertificateResolver.cs

@@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
         /// </summary>
         /// <param name="thumbprint">The thumbprint (as a hex string) of the certificate to resolve.</param>
         /// <returns>The resolved <see cref="X509Certificate2"/>, or null if the certificate cannot be found.</returns>
-        public virtual X509Certificate2 ResolveCertificate(string thumbprint)
+        public virtual X509Certificate2? ResolveCertificate(string thumbprint)
         {
             if (thumbprint == null)
             {
@@ -34,7 +34,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
                 ?? GetCertificateFromStore(StoreLocation.LocalMachine, thumbprint);
         }
 
-        private static X509Certificate2 GetCertificateFromStore(StoreLocation location, string thumbprint)
+        private static X509Certificate2? GetCertificateFromStore(StoreLocation location, string thumbprint)
         {
             var store = new X509Store(location);
             try

+ 4 - 3
src/DataProtection/DataProtection/src/XmlEncryption/CertificateXmlEncryptor.cs

@@ -56,10 +56,11 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
             _certFactory = () => certificate;
         }
 
-        internal CertificateXmlEncryptor(ILoggerFactory loggerFactory, IInternalCertificateXmlEncryptor encryptor)
+        internal CertificateXmlEncryptor(ILoggerFactory loggerFactory, IInternalCertificateXmlEncryptor? encryptor)
         {
             _encryptor = encryptor ?? this;
             _logger = loggerFactory.CreateLogger<CertificateXmlEncryptor>();
+            _certFactory = default!; // Set by calling ctors
         }
 
         /// <summary>
@@ -93,7 +94,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
             // doesn't handle encrypting the root element all that well.
             var xmlDocument = new XmlDocument();
             xmlDocument.Load(new XElement("root", plaintextElement).CreateReader());
-            var elementToEncrypt = (XmlElement)xmlDocument.DocumentElement.FirstChild;
+            var elementToEncrypt = (XmlElement)xmlDocument.DocumentElement!.FirstChild!;
 
             // Perform the encryption and update the document in-place.
             var encryptedXml = new EncryptedXml(xmlDocument);
@@ -101,7 +102,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
             EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, content: false);
 
             // Strip the <root /> element back off and convert the XmlDocument to an XElement.
-            return XElement.Load(xmlDocument.DocumentElement.FirstChild.CreateNavigator().ReadSubtree());
+            return XElement.Load(xmlDocument.DocumentElement.FirstChild!.CreateNavigator()!.ReadSubtree());
         }
 
         private Func<X509Certificate2> CreateCertFactory(string thumbprint, ICertificateResolver resolver)

+ 3 - 3
src/DataProtection/DataProtection/src/XmlEncryption/DpapiNGXmlDecryptor.cs

@@ -31,7 +31,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
         /// Creates a new instance of a <see cref="DpapiNGXmlDecryptor"/>.
         /// </summary>
         /// <param name="services">An optional <see cref="IServiceProvider"/> to provide ancillary services.</param>
-        public DpapiNGXmlDecryptor(IServiceProvider services)
+        public DpapiNGXmlDecryptor(IServiceProvider? services)
         {
             CryptoUtil.AssertPlatformIsWindows8OrLater();
 
@@ -58,10 +58,10 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
                 //   <value>{base64}</value>
                 // </encryptedKey>
 
-                var protectedSecret = Convert.FromBase64String((string)encryptedElement.Element("value"));
+                var protectedSecret = Convert.FromBase64String((string)encryptedElement.Element("value")!);
                 if (_logger.IsDebugLevelEnabled())
                 {
-                    string protectionDescriptorRule;
+                    string? protectionDescriptorRule;
                     try
                     {
                         protectionDescriptorRule = DpapiSecretSerializerHelper.GetRuleFromDpapiNGProtectedPayload(protectedSecret);

+ 1 - 1
src/DataProtection/DataProtection/src/XmlEncryption/DpapiNGXmlEncryptor.cs

@@ -109,7 +109,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
             using (var currentIdentity = WindowsIdentity.GetCurrent())
             {
                 // use the SID to create an SDDL string
-                return string.Format(CultureInfo.InvariantCulture, "SID={0}", currentIdentity.User.Value);
+                return string.Format(CultureInfo.InvariantCulture, "SID={0}", currentIdentity?.User?.Value);
             }
         }
     }

+ 2 - 2
src/DataProtection/DataProtection/src/XmlEncryption/DpapiXmlDecryptor.cs

@@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
         /// Creates a new instance of a <see cref="DpapiXmlDecryptor"/>.
         /// </summary>
         /// <param name="services">An optional <see cref="IServiceProvider"/> to provide ancillary services.</param>
-        public DpapiXmlDecryptor(IServiceProvider services)
+        public DpapiXmlDecryptor(IServiceProvider? services)
         {
             CryptoUtil.AssertPlatformIsWindows();
 
@@ -56,7 +56,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
                 //   <value>{base64}</value>
                 // </encryptedKey>
 
-                var protectedSecret = Convert.FromBase64String((string)encryptedElement.Element("value"));
+                var protectedSecret = Convert.FromBase64String((string)encryptedElement.Element("value")!);
                 using (var secret = DpapiSecretSerializerHelper.UnprotectWithDpapi(protectedSecret))
                 {
                     return secret.ToXElement();

+ 11 - 11
src/DataProtection/DataProtection/src/XmlEncryption/EncryptedXmlDecryptor.cs

@@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
     public sealed class EncryptedXmlDecryptor : IInternalEncryptedXmlDecryptor, IXmlDecryptor
     {
         private readonly IInternalEncryptedXmlDecryptor _decryptor;
-        private readonly XmlKeyDecryptionOptions _options;
+        private readonly XmlKeyDecryptionOptions? _options;
 
         /// <summary>
         /// Creates a new instance of an <see cref="EncryptedXmlDecryptor"/>.
@@ -32,7 +32,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
         /// Creates a new instance of an <see cref="EncryptedXmlDecryptor"/>.
         /// </summary>
         /// <param name="services">An optional <see cref="IServiceProvider"/> to provide ancillary services.</param>
-        public EncryptedXmlDecryptor(IServiceProvider services)
+        public EncryptedXmlDecryptor(IServiceProvider? services)
         {
             _decryptor = services?.GetService<IInternalEncryptedXmlDecryptor>() ?? this;
             _options = services?.GetService<IOptions<XmlKeyDecryptionOptions>>()?.Value;
@@ -59,7 +59,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
             // doesn't handle encrypting the root element all that well.
             var xmlDocument = new XmlDocument();
             xmlDocument.Load(new XElement("root", encryptedElement).CreateReader());
-            var elementToDecrypt = (XmlElement)xmlDocument.DocumentElement.FirstChild;
+            var elementToDecrypt = (XmlElement)xmlDocument.DocumentElement!.FirstChild!;
 
             // Perform the decryption and update the document in-place.
             var encryptedXml = new EncryptedXmlWithCertificateKeys(_options, xmlDocument);
@@ -68,7 +68,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
             encryptedXml.DecryptDocument();
 
             // Strip the <root /> element back off and convert the XmlDocument to an XElement.
-            return XElement.Load(xmlDocument.DocumentElement.FirstChild.CreateNavigator().ReadSubtree());
+            return XElement.Load(xmlDocument.DocumentElement.FirstChild!.CreateNavigator()!.ReadSubtree());
         }
 
         void IInternalEncryptedXmlDecryptor.PerformPreDecryptionSetup(EncryptedXml encryptedXml)
@@ -81,15 +81,15 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
         /// </summary>
         private class EncryptedXmlWithCertificateKeys : EncryptedXml
         {
-            private readonly XmlKeyDecryptionOptions _options;
+            private readonly XmlKeyDecryptionOptions? _options;
 
-            public EncryptedXmlWithCertificateKeys(XmlKeyDecryptionOptions options, XmlDocument document)
+            public EncryptedXmlWithCertificateKeys(XmlKeyDecryptionOptions? options, XmlDocument document)
                 : base(document)
             {
                 _options = options;
             }
 
-            public override byte[] DecryptEncryptedKey(EncryptedKey encryptedKey)
+            public override byte[]? DecryptEncryptedKey(EncryptedKey encryptedKey)
             {
                 if (_options != null && _options.KeyDecryptionCertificateCount > 0)
                 {
@@ -106,7 +106,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
                             continue;
                         }
 
-                        byte[] key = GetKeyFromCert(encryptedKey, kiX509Data);
+                        var key = GetKeyFromCert(encryptedKey, kiX509Data);
                         if (key != null)
                         {
                             return key;
@@ -117,7 +117,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
                 return base.DecryptEncryptedKey(encryptedKey);
             }
 
-            private byte[] GetKeyFromCert(EncryptedKey encryptedKey, KeyInfoX509Data keyInfo)
+            private byte[]? GetKeyFromCert(EncryptedKey encryptedKey, KeyInfoX509Data keyInfo)
             {
                 var certEnum = keyInfo.Certificates?.GetEnumerator();
                 if (certEnum == null)
@@ -132,7 +132,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
                         continue;
                     }
 
-                    if (!_options.TryGetKeyDecryptionCertificates(certInfo, out var keyDecryptionCerts))
+                    if (_options == null || !_options.TryGetKeyDecryptionCertificates(certInfo, out var keyDecryptionCerts))
                     {
                         continue;
                     }
@@ -144,7 +144,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
                             continue;
                         }
 
-                        using (RSA privateKey = keyDecryptionCert.GetRSAPrivateKey())
+                        using (var privateKey = keyDecryptionCert.GetRSAPrivateKey())
                         {
                             if (privateKey != null)
                             {

+ 1 - 1
src/DataProtection/DataProtection/src/XmlEncryption/ICertificateResolver.cs

@@ -15,6 +15,6 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
         /// </summary>
         /// <param name="thumbprint">The thumbprint (as a hex string) of the certificate to resolve.</param>
         /// <returns>The resolved <see cref="X509Certificate2"/>, or null if the certificate cannot be found.</returns>
-        X509Certificate2 ResolveCertificate(string thumbprint);
+        X509Certificate2? ResolveCertificate(string thumbprint);
     }
 }

+ 1 - 1
src/DataProtection/DataProtection/src/XmlEncryption/NullXmlEncryptor.cs

@@ -26,7 +26,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
         /// Creates a new instance of <see cref="NullXmlEncryptor"/>.
         /// </summary>
         /// <param name="services">An optional <see cref="IServiceProvider"/> to provide ancillary services.</param>
-        public NullXmlEncryptor(IServiceProvider services)
+        public NullXmlEncryptor(IServiceProvider? services)
         {
             _logger = services.GetLogger<NullXmlEncryptor>();
         }

+ 4 - 4
src/DataProtection/DataProtection/src/XmlEncryption/XmlEncryptionExtensions.cs

@@ -46,7 +46,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
                 // the original document or other data structures. The element we pass to
                 // the decryptor should be the child of the 'encryptedSecret' element.
                 var clonedElementWhichRequiresDecryption = new XElement(elementWhichRequiresDecryption);
-                string decryptorTypeName = (string)clonedElementWhichRequiresDecryption.Attribute(XmlConstants.DecryptorTypeAttributeName);
+                string decryptorTypeName = (string)clonedElementWhichRequiresDecryption.Attribute(XmlConstants.DecryptorTypeAttributeName)!;
                 var decryptorInstance = activator.CreateInstance<IXmlDecryptor>(decryptorTypeName);
                 var decryptedElement = decryptorInstance.Decrypt(clonedElementWhichRequiresDecryption.Elements().Single());
 
@@ -63,10 +63,10 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
             {
                 entry.Key.ReplaceWith(entry.Value);
             }
-            return doc.Root;
+            return doc.Root!;
         }
 
-        public static XElement EncryptIfNecessary(this IXmlEncryptor encryptor, XElement element)
+        public static XElement? EncryptIfNecessary(this IXmlEncryptor encryptor, XElement element)
         {
             // If no encryption is necessary, return null.
             if (!DoesElementOrDescendentRequireEncryption(element))
@@ -116,7 +116,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
                 // </enc:encryptedSecret>
                 entry.Key.ReplaceWith(
                     new XElement(XmlConstants.EncryptedSecretElementName,
-                        new XAttribute(XmlConstants.DecryptorTypeAttributeName, entry.Value.DecryptorType.AssemblyQualifiedName),
+                        new XAttribute(XmlConstants.DecryptorTypeAttributeName, entry.Value.DecryptorType.AssemblyQualifiedName!),
                         entry.Value.EncryptedElement));
             }
             return doc.Root;

+ 2 - 1
src/DataProtection/DataProtection/src/XmlEncryption/XmlKeyDecryptionOptions.cs

@@ -3,6 +3,7 @@
 
 using System;
 using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
 using System.Security.Cryptography.X509Certificates;
 
 namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
@@ -16,7 +17,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
 
         public int KeyDecryptionCertificateCount => _certs.Count;
 
-        public bool TryGetKeyDecryptionCertificates(X509Certificate2 certInfo, out IReadOnlyList<X509Certificate2> keyDecryptionCerts)
+        public bool TryGetKeyDecryptionCertificates(X509Certificate2 certInfo, [NotNullWhen(true)] out IReadOnlyList<X509Certificate2>? keyDecryptionCerts)
         {
             var key = GetKey(certInfo);
             var retVal = _certs.TryGetValue(key, out var keyDecryptionCertsRetVal);