Annotate System.Security.Cryptography.Pkcs for nullable (#32571)
authorbuyaa-n <bunamnan@microsoft.com>
Thu, 20 Feb 2020 18:03:32 +0000 (10:03 -0800)
committerGitHub <noreply@github.com>
Thu, 20 Feb 2020 18:03:32 +0000 (10:03 -0800)
* Annotate System.Security.Cryptography.Pkcs

66 files changed:
src/libraries/Common/src/Interop/Windows/Crypt32/Interop.CertGetCertificateContextProperty.cs
src/libraries/Common/src/Interop/Windows/Crypt32/Interop.CryptEncodeObject.cs
src/libraries/Common/src/Interop/Windows/Crypt32/Interop.CryptMsgGetParam.cs
src/libraries/Common/src/System/Security/Cryptography/Asn1/Pkcs12/PfxAsn.manual.cs
src/libraries/System.Security.Cryptography.Pkcs/ref/System.Security.Cryptography.Pkcs.cs
src/libraries/System.Security.Cryptography.Pkcs/ref/System.Security.Cryptography.Pkcs.csproj
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/DecryptorPal.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/KeyAgreeRecipientInfoPal.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/AsnHelpers.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Decrypt.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Encrypt.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.KeyAgree.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.KeyTrans.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.Decrypt.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/DecryptorPalWindows.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HeapBlockRetainer.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HelpersWindows.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/KeyAgreeRecipientInfoPalWindows.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.Encrypt.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/PkcsHelpers.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/PkcsPal.cs
src/libraries/System.Security.Cryptography.Pkcs/src/Microsoft/Win32/SafeHandles/SafeProvOrNCryptKeyHandleUwp.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System.Security.Cryptography.Pkcs.csproj
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/CryptographicAttributeObject.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/CryptographicAttributeObjectCollection.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/CertificateChoiceAsn.xml.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/KeyAgreeRecipientIdentifierAsn.xml.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/OriginatorIdentifierOrKeyAsn.xml.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/RecipientIdentifierAsn.xml.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/RecipientInfoAsn.xml.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/Rfc3161TimeStampReq.xml.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignedAttributesSet.xml.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignerIdentifierAsn.xml.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/SignerInfoAsn.xml.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipient.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.DSA.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.ECDsa.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.RSA.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSigner.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/KeyAgreeRecipientInfo.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/KeyTransRecipientInfo.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Info.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeBag.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContentsBag.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SecretBag.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs8PrivateKeyInfo.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9ContentType.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentDescription.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentName.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9LocalKeyId.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9MessageDigest.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9SigningTime.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampRequest.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampToken.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampTokenInfo.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoEnumerator.cs
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SubjectIdentifier.cs

index 6696c19..bd3b3b0 100644 (file)
@@ -14,7 +14,7 @@ internal static partial class Interop
         internal static extern bool CertGetCertificateContextProperty(
             SafeCertContextHandle pCertContext,
             CertContextPropId dwPropId,
-            [Out] byte[] pvData,
+            [Out] byte[]? pvData,
             [In, Out] ref int pcbData);
 
         [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
index 902fa0c..f8b9cc7 100644 (file)
@@ -9,7 +9,7 @@ internal static partial class Interop
 {
     internal static partial class Crypt32
     {
-        internal static unsafe bool CryptEncodeObject(MsgEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, void* pvStructInfo, byte[] pbEncoded, ref int pcbEncoded)
+        internal static unsafe bool CryptEncodeObject(MsgEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, void* pvStructInfo, byte[]? pbEncoded, ref int pcbEncoded)
         {
             return CryptEncodeObject(dwCertEncodingType, (IntPtr)lpszStructType, pvStructInfo, pbEncoded, ref pcbEncoded);
         }
@@ -19,7 +19,7 @@ internal static partial class Interop
             MsgEncodingType dwCertEncodingType,
             IntPtr lpszStructType,
             void* pvStructInfo,
-            [Out] byte[] pbEncoded,
+            [Out] byte[]? pbEncoded,
             [In, Out] ref int pcbEncoded);
     }
 }
index 63fdff1..10dca5a 100644 (file)
@@ -31,7 +31,7 @@ internal static partial class Interop
             SafeCryptMsgHandle hCryptMsg,
             CryptMsgParamType dwParamType,
             int dwIndex,
-            [Out] byte[] pvData,
+            [Out] byte[]? pvData,
             [In, Out] ref int pcbData);
 
         [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
index 42d9eda..4c7dd5a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Security.Cryptography.Pkcs;
 
index 644861e..8c3a693 100644 (file)
@@ -10,7 +10,7 @@ namespace System.Security.Cryptography
     public sealed partial class CryptographicAttributeObject
     {
         public CryptographicAttributeObject(System.Security.Cryptography.Oid oid) { }
-        public CryptographicAttributeObject(System.Security.Cryptography.Oid oid, System.Security.Cryptography.AsnEncodedDataCollection values) { }
+        public CryptographicAttributeObject(System.Security.Cryptography.Oid oid, System.Security.Cryptography.AsnEncodedDataCollection? values) { }
         public System.Security.Cryptography.Oid Oid { get { throw null; } }
         public System.Security.Cryptography.AsnEncodedDataCollection Values { get { throw null; } }
     }
@@ -87,9 +87,9 @@ namespace System.Security.Cryptography.Pkcs
         [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
         public CmsSigner(System.Security.Cryptography.CspParameters parameters) { }
         public CmsSigner(System.Security.Cryptography.Pkcs.SubjectIdentifierType signerIdentifierType) { }
-        public CmsSigner(System.Security.Cryptography.Pkcs.SubjectIdentifierType signerIdentifierType, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
-        public CmsSigner(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
-        public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { throw null; } set { } }
+        public CmsSigner(System.Security.Cryptography.Pkcs.SubjectIdentifierType signerIdentifierType, System.Security.Cryptography.X509Certificates.X509Certificate2? certificate) { }
+        public CmsSigner(System.Security.Cryptography.X509Certificates.X509Certificate2? certificate) { }
+        public System.Security.Cryptography.X509Certificates.X509Certificate2? Certificate { get { throw null; } set { } }
         public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { get { throw null; } }
         public System.Security.Cryptography.Oid DigestAlgorithm { get { throw null; } set { } }
         public System.Security.Cryptography.X509Certificates.X509IncludeOption IncludeOption { get { throw null; } set { } }
@@ -132,7 +132,7 @@ namespace System.Security.Cryptography.Pkcs
         public override byte[] EncryptedKey { get { throw null; } }
         public override System.Security.Cryptography.Pkcs.AlgorithmIdentifier KeyEncryptionAlgorithm { get { throw null; } }
         public System.Security.Cryptography.Pkcs.SubjectIdentifierOrKey OriginatorIdentifierOrKey { get { throw null; } }
-        public System.Security.Cryptography.CryptographicAttributeObject OtherKeyAttribute { get { throw null; } }
+        public System.Security.Cryptography.CryptographicAttributeObject? OtherKeyAttribute { get { throw null; } }
         public override System.Security.Cryptography.Pkcs.SubjectIdentifier RecipientIdentifier { get { throw null; } }
         public override int Version { get { throw null; } }
     }
@@ -150,7 +150,7 @@ namespace System.Security.Cryptography.Pkcs
         public Pkcs9AttributeObject(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
         public Pkcs9AttributeObject(System.Security.Cryptography.Oid oid, byte[] encodedData) { }
         public Pkcs9AttributeObject(string oid, byte[] encodedData) { }
-        public new System.Security.Cryptography.Oid Oid { get { throw null; } }
+        public new System.Security.Cryptography.Oid? Oid { get { throw null; } }
         public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
     }
     public sealed partial class Pkcs9ContentType : System.Security.Cryptography.Pkcs.Pkcs9AttributeObject
@@ -258,7 +258,7 @@ namespace System.Security.Cryptography.Pkcs
     public sealed partial class SignerInfo
     {
         internal SignerInfo() { }
-        public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { throw null; } }
+        public System.Security.Cryptography.X509Certificates.X509Certificate2? Certificate { get { throw null; } }
         public System.Security.Cryptography.Pkcs.SignerInfoCollection CounterSignerInfos { get { throw null; } }
         public System.Security.Cryptography.Oid DigestAlgorithm { get { throw null; } }
         public System.Security.Cryptography.CryptographicAttributeObjectCollection SignedAttributes { get { throw null; } }
@@ -298,7 +298,7 @@ namespace System.Security.Cryptography.Pkcs
     {
         internal SubjectIdentifier() { }
         public System.Security.Cryptography.Pkcs.SubjectIdentifierType Type { get { throw null; } }
-        public object Value { get { throw null; } }
+        public object? Value { get { throw null; } }
     }
     public sealed partial class SubjectIdentifierOrKey
     {
index bc41c33..3755542 100644 (file)
@@ -4,6 +4,7 @@
     <TargetFrameworks>netcoreapp3.0;netstandard2.1;net461;$(NetFrameworkCurrent);$(NetCoreAppCurrent)</TargetFrameworks>
     <ExcludeCurrentNetCoreAppFromPackage>true</ExcludeCurrentNetCoreAppFromPackage>
     <ExcludeCurrentFullFrameworkFromPackage>true</ExcludeCurrentFullFrameworkFromPackage>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="System.Security.Cryptography.Pkcs.cs" />
index 92a48aa..1250b6f 100644 (file)
@@ -31,13 +31,13 @@ namespace Internal.Cryptography
         /// to a valid Exception object. Do not throw the exception as EnvelopedCms will want to continue decryption attempts against other recipients. Only if all the recipients fail to
         /// decrypt will then EnvelopedCms throw the exception from the last failed attempt.
         /// </summary>
-        public abstract ContentInfo TryDecrypt(
+        public abstract ContentInfo? TryDecrypt(
             RecipientInfo recipientInfo,
-            X509Certificate2 cert,
-            AsymmetricAlgorithm privateKey,
+            X509Certificate2? cert,
+            AsymmetricAlgorithm? privateKey,
             X509Certificate2Collection originatorCerts,
             X509Certificate2Collection extraStore,
-            out Exception exception);
+            out Exception? exception);
 
         public abstract void Dispose();
     }
index db321ac..bcceb2f 100644 (file)
@@ -19,6 +19,6 @@ namespace Internal.Cryptography
 
         public abstract DateTime Date { get; }
         public abstract SubjectIdentifierOrKey OriginatorIdentifierOrKey { get; }
-        public abstract CryptographicAttributeObject OtherKeyAttribute { get; }
+        public abstract CryptographicAttributeObject? OtherKeyAttribute { get; }
     }
 }
index 37e4a5d..64329c0 100644 (file)
@@ -130,6 +130,7 @@ namespace Internal.Cryptography.Pal.AnyOS
                     break;
                 case Oids.RsaOaep when !asn.HasNullEquivalentParameters():
                     keyLength = 0;
+                    Debug.Assert(asn.Parameters != null);
                     parameters = asn.Parameters.Value.ToArray();
                     break;
                 default:
index 548d9fc..58ec6b7 100644 (file)
@@ -29,13 +29,13 @@ namespace Internal.Cryptography.Pal.AnyOS
                 _envelopedData = envelopedDataAsn;
             }
 
-            public override unsafe ContentInfo TryDecrypt(
+            public override unsafe ContentInfo? TryDecrypt(
                 RecipientInfo recipientInfo,
-                X509Certificate2 cert,
-                AsymmetricAlgorithm privateKey,
+                X509Certificate2? cert,
+                AsymmetricAlgorithm? privateKey,
                 X509Certificate2Collection originatorCerts,
                 X509Certificate2Collection extraStore,
-                out Exception exception)
+                out Exception? exception)
             {
                 // When encryptedContent is null Windows seems to decrypt the CEK first,
                 // then return a 0 byte answer.
@@ -44,7 +44,7 @@ namespace Internal.Cryptography.Pal.AnyOS
 
                 if (recipientInfo.Pal is ManagedKeyTransPal ktri)
                 {
-                    RSA key = privateKey as RSA;
+                    RSA? key = privateKey as RSA;
 
                     if (privateKey != null && key == null)
                     {
@@ -52,7 +52,7 @@ namespace Internal.Cryptography.Pal.AnyOS
                         return null;
                     }
 
-                    byte[] cek = ktri.DecryptCek(cert, key, out exception);
+                    byte[]? cek = ktri.DecryptCek(cert, key, out exception);
                     // Pin CEK to prevent it from getting copied during heap compaction.
                     fixed (byte* pinnedCek = cek)
                     {
@@ -64,7 +64,7 @@ namespace Internal.Cryptography.Pal.AnyOS
                             }
 
                             return TryDecryptCore(
-                                cek,
+                                cek!,
                                 _envelopedData.EncryptedContentInfo.ContentType,
                                 _envelopedData.EncryptedContentInfo.EncryptedContent,
                                 _envelopedData.EncryptedContentInfo.ContentEncryptionAlgorithm,
@@ -89,12 +89,12 @@ namespace Internal.Cryptography.Pal.AnyOS
                 }
             }
 
-            public static unsafe ContentInfo TryDecryptCore(
+            public static unsafe ContentInfo? TryDecryptCore(
                 byte[] cek,
                 string contentType,
                 ReadOnlyMemory<byte>? content,
                 AlgorithmIdentifierAsn contentEncryptionAlgorithm,
-                out Exception exception)
+                out Exception? exception)
             {
                 if (content == null)
                 {
@@ -105,7 +105,7 @@ namespace Internal.Cryptography.Pal.AnyOS
                         Array.Empty<byte>());
                 }
 
-                byte[] decrypted = DecryptContent(content.Value, cek, contentEncryptionAlgorithm, out exception);
+                byte[]? decrypted = DecryptContent(content.Value, cek, contentEncryptionAlgorithm, out exception);
 
                 if (exception != null)
                 {
@@ -117,7 +117,7 @@ namespace Internal.Cryptography.Pal.AnyOS
                 // existing CMS that have the incorrect wrapping, we attempt to remove it.
                 if (contentType == Oids.Pkcs7Data)
                 {
-                    byte[] tmp = null;
+                    byte[]? tmp = null;
 
                     try
                     {
@@ -129,7 +129,7 @@ namespace Internal.Cryptography.Pal.AnyOS
                         }
                         else
                         {
-                            tmp = CryptoPool.Rent(decrypted.Length);
+                            tmp = CryptoPool.Rent(decrypted!.Length);
 
                             if (reader.TryCopyOctetStringBytes(tmp, out int written))
                             {
@@ -165,7 +165,7 @@ namespace Internal.Cryptography.Pal.AnyOS
                 exception = null;
                 return new ContentInfo(
                     new Oid(contentType),
-                    decrypted);
+                    decrypted!);
             }
 
             private static byte[] GetAsnSequenceWithContentNoValidation(ReadOnlySpan<byte> content)
@@ -185,15 +185,15 @@ namespace Internal.Cryptography.Pal.AnyOS
                 }
             }
 
-            private static byte[] DecryptContent(
+            private static byte[]? DecryptContent(
                 ReadOnlyMemory<byte> encryptedContent,
                 byte[] cek,
                 AlgorithmIdentifierAsn contentEncryptionAlgorithm,
-                out Exception exception)
+                out Exception? exception)
             {
                 exception = null;
                 int encryptedContentLength = encryptedContent.Length;
-                byte[] encryptedContentArray = CryptoPool.Rent(encryptedContentLength);
+                byte[]? encryptedContentArray = CryptoPool.Rent(encryptedContentLength);
 
                 try
                 {
index 1e592b2..4691380 100644 (file)
@@ -64,7 +64,7 @@ namespace Internal.Cryptography.Pal.AnyOS
             {
                 EncryptedContentInfo =
                 {
-                    ContentType = contentInfo.ContentType.Value,
+                    ContentType = contentInfo.ContentType.Value!,
 
                     ContentEncryptionAlgorithm =
                     {
index 7a1d63b..ed523c5 100644 (file)
@@ -59,7 +59,7 @@ namespace Internal.Cryptography.Pal.AnyOS
             public override SubjectIdentifierOrKey OriginatorIdentifierOrKey =>
                 _asn.Originator.ToSubjectIdentifierOrKey();
 
-            public override CryptographicAttributeObject OtherKeyAttribute
+            public override CryptographicAttributeObject? OtherKeyAttribute
             {
                 get
                 {
@@ -81,7 +81,7 @@ namespace Internal.Cryptography.Pal.AnyOS
 
                     if (rid.RKeyId.Value.Other.Value.KeyAttr != null)
                     {
-                        rawData = rid.RKeyId.Value.Other.Value.KeyAttr.Value.ToArray();
+                        rawData = rid.RKeyId.Value.Other.Value.KeyAttr!.Value.ToArray();
                     }
 
                     Pkcs9AttributeObject pkcs9AttributeObject = new Pkcs9AttributeObject(oid, rawData);
index b31bd55..ee2f549 100644 (file)
@@ -33,10 +33,10 @@ namespace Internal.Cryptography.Pal.AnyOS
 
             public override int Version => _asn.Version;
 
-            internal byte[] DecryptCek(X509Certificate2 cert, RSA privateKey, out Exception exception)
+            internal byte[]? DecryptCek(X509Certificate2? cert, RSA? privateKey, out Exception? exception)
             {
                 ReadOnlyMemory<byte>? parameters = _asn.KeyEncryptionAlgorithm.Parameters;
-                string keyEncryptionAlgorithm = _asn.KeyEncryptionAlgorithm.Algorithm.Value;
+                string? keyEncryptionAlgorithm = _asn.KeyEncryptionAlgorithm.Algorithm.Value;
 
                 switch (keyEncryptionAlgorithm)
                 {
@@ -61,15 +61,15 @@ namespace Internal.Cryptography.Pal.AnyOS
                 return DecryptCekCore(cert, privateKey, _asn.EncryptedKey.Span, keyEncryptionAlgorithm, parameters, out exception);
             }
 
-            internal static byte[] DecryptCekCore(
-                X509Certificate2 cert,
-                RSA privateKey,
+            internal static byte[]? DecryptCekCore(
+                X509Certificate2? cert,
+                RSA? privateKey,
                 ReadOnlySpan<byte> encryptedKey,
-                string keyEncryptionAlgorithm,
+                string? keyEncryptionAlgorithm,
                 ReadOnlyMemory<byte>? algorithmParameters,
-                out Exception exception)
+                out Exception? exception)
             {
-                RSAEncryptionPadding encryptionPadding;
+                RSAEncryptionPadding? encryptionPadding;
 
                 switch (keyEncryptionAlgorithm)
                 {
@@ -177,11 +177,11 @@ namespace Internal.Cryptography.Pal.AnyOS
             return ktri;
         }
 
-        private static byte[] DecryptKey(
+        private static byte[]? DecryptKey(
             RSA privateKey,
             RSAEncryptionPadding encryptionPadding,
             ReadOnlySpan<byte> encryptedKey,
-            out Exception exception)
+            out Exception? exception)
         {
             if (privateKey == null)
             {
@@ -190,7 +190,7 @@ namespace Internal.Cryptography.Pal.AnyOS
             }
 
 #if NETCOREAPP || NETSTANDARD2_1
-            byte[] cek = null;
+            byte[]? cek = null;
             int cekLength = 0;
 
             try
index f9bf227..1d42307 100644 (file)
@@ -17,19 +17,19 @@ namespace Internal.Cryptography.Pal.Windows
 {
     internal sealed partial class DecryptorPalWindows : DecryptorPal
     {
-        public unsafe sealed override ContentInfo TryDecrypt(
+        public unsafe sealed override ContentInfo? TryDecrypt(
             RecipientInfo recipientInfo,
-            X509Certificate2 cert,
-            AsymmetricAlgorithm privateKey,
+            X509Certificate2? cert,
+            AsymmetricAlgorithm? privateKey,
             X509Certificate2Collection originatorCerts,
             X509Certificate2Collection extraStore,
-            out Exception exception)
+            out Exception? exception)
         {
             Debug.Assert((cert != null) ^ (privateKey != null));
 
             if (privateKey != null)
             {
-                RSA key = privateKey as RSA;
+                RSA? key = privateKey as RSA;
 
                 if (key == null)
                 {
@@ -38,7 +38,7 @@ namespace Internal.Cryptography.Pal.Windows
                 }
 
                 ContentInfo contentInfo = _hCryptMsg.GetContentInfo();
-                byte[] cek = AnyOS.ManagedPkcsPal.ManagedKeyTransPal.DecryptCekCore(
+                byte[]? cek = AnyOS.ManagedPkcsPal.ManagedKeyTransPal.DecryptCekCore(
                     cert,
                     key,
                     recipientInfo.EncryptedKey,
@@ -57,8 +57,8 @@ namespace Internal.Cryptography.Pal.Windows
                         }
 
                         return AnyOS.ManagedPkcsPal.ManagedDecryptorPal.TryDecryptCore(
-                            cek,
-                            contentInfo.ContentType.Value,
+                            cek!,
+                            contentInfo.ContentType.Value!,
                             contentInfo.Content,
                             _contentEncryptionAlgorithm,
                             out exception);
@@ -89,7 +89,7 @@ namespace Internal.Cryptography.Pal.Windows
             // because wrapping an NCrypt wrapper over CAPI keys unconditionally causes some legacy features
             // (such as RC4 support) to break.
             const bool PreferNCrypt = false;
-            using (SafeProvOrNCryptKeyHandle hKey = PkcsPalWindows.GetCertificatePrivateKey(cert, Silent, PreferNCrypt, out _, out exception))
+            using (SafeProvOrNCryptKeyHandle? hKey = PkcsPalWindows.GetCertificatePrivateKey(cert, Silent, PreferNCrypt, out _, out exception))
             {
                 if (hKey == null)
                     return null;
@@ -120,7 +120,7 @@ namespace Internal.Cryptography.Pal.Windows
             }
         }
 
-        private static Exception TryGetKeySpecForCertificate(X509Certificate2 cert, out CryptKeySpec keySpec)
+        private static Exception? TryGetKeySpecForCertificate(X509Certificate2 cert, out CryptKeySpec keySpec)
         {
             using (SafeCertContextHandle hCertContext = cert.CreateCertContextHandle())
             {
@@ -163,7 +163,7 @@ namespace Internal.Cryptography.Pal.Windows
             }
         }
 
-        private Exception TryDecryptTrans(KeyTransRecipientInfo recipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec)
+        private Exception? TryDecryptTrans(KeyTransRecipientInfo recipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec)
         {
             KeyTransRecipientInfoPalWindows pal = (KeyTransRecipientInfoPalWindows)(recipientInfo.Pal);
 
@@ -180,12 +180,12 @@ namespace Internal.Cryptography.Pal.Windows
             return null;
         }
 
-        private Exception TryDecryptAgree(KeyAgreeRecipientInfo keyAgreeRecipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore)
+        private Exception? TryDecryptAgree(KeyAgreeRecipientInfo keyAgreeRecipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore)
         {
             unsafe
             {
                 KeyAgreeRecipientInfoPalWindows pal = (KeyAgreeRecipientInfoPalWindows)(keyAgreeRecipientInfo.Pal);
-                return pal.WithCmsgCmsRecipientInfo<Exception>(
+                return pal.WithCmsgCmsRecipientInfo<Exception?>(
                     delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* pKeyAgreeRecipientInfo)
                     {
                         CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara = default(CMSG_CTRL_KEY_AGREE_DECRYPT_PARA);
@@ -206,7 +206,7 @@ namespace Internal.Cryptography.Pal.Windows
                                     candidateCerts.AddRange(originatorCerts);
                                     candidateCerts.AddRange(extraStore);
                                     SubjectIdentifier originatorId = pKeyAgreeRecipientInfo->OriginatorCertId.ToSubjectIdentifier();
-                                    X509Certificate2 originatorCert = candidateCerts.TryFindMatchingCertificate(originatorId);
+                                    X509Certificate2? originatorCert = candidateCerts.TryFindMatchingCertificate(originatorId);
                                     if (originatorCert == null)
                                         return ErrorCode.CRYPT_E_NOT_FOUND.ToCryptographicException();
                                     using (SafeCertContextHandle hCertContext = originatorCert.CreateCertContextHandle())
@@ -233,7 +233,7 @@ namespace Internal.Cryptography.Pal.Windows
             }
         }
 
-        private Exception TryExecuteDecryptAgree(ref CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara)
+        private Exception? TryExecuteDecryptAgree(ref CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara)
         {
             if (!Interop.Crypt32.CryptMsgControl(_hCryptMsg, 0, MsgControlType.CMSG_CTRL_KEY_AGREE_DECRYPT, ref decryptPara))
             {
index 0989706..d1a7bd5 100644 (file)
@@ -25,7 +25,7 @@ namespace Internal.Cryptography.Pal.Windows
             if (_hCryptMsg != null && !_hCryptMsg.IsInvalid)
             {
                 _hCryptMsg.Dispose();
-                _hCryptMsg = null;
+                _hCryptMsg = null!;
             }
         }
 
index 66cb58e..753ee90 100644 (file)
@@ -76,7 +76,7 @@ namespace Internal.Cryptography.Pal.Windows
                     h.Dispose();
                 }
             }
-            _blocks = null;
+            _blocks = null!;
         }
 
         private readonly List<object> _mustLive;
index 1462961..2088692 100644 (file)
@@ -29,7 +29,7 @@ namespace Internal.Cryptography.Pal.Windows
 
         public static string ToStringAnsi(this IntPtr psz)
         {
-            return Marshal.PtrToStringAnsi(psz);
+            return Marshal.PtrToStringAnsi(psz)!;
         }
 
         // Used for binary blobs without internal pointers.
@@ -221,10 +221,10 @@ namespace Internal.Cryptography.Pal.Windows
             switch (subjectIdentifierType)
             {
                 case SubjectIdentifierType.IssuerAndSerialNumber:
-                    return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.IssuerAndSerialNumber, subjectIdentifier.Value);
+                    return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.IssuerAndSerialNumber, subjectIdentifier.Value!);
 
                 case SubjectIdentifierType.SubjectKeyIdentifier:
-                    return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.SubjectKeyIdentifier, subjectIdentifier.Value);
+                    return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.SubjectKeyIdentifier, subjectIdentifier.Value!);
 
                 default:
                     Debug.Fail("Only the framework can construct SubjectIdentifier's so if we got a bad value here, that's our fault.");
@@ -400,7 +400,7 @@ namespace Internal.Cryptography.Pal.Windows
                 ((CspProviderFlags)keysetType & CspProviderFlags.UseMachineKeyStore) |
                 CspProviderFlags.UseExistingKey;
 
-            byte[] rented = null;
+            byte[]? rented = null;
             Span<byte> asciiStringBuf = stackSpan;
 
             string provName = GetStringProvParam(handle, CryptProvParam.PP_NAME, ref asciiStringBuf, ref rented, 0);
@@ -425,7 +425,7 @@ namespace Internal.Cryptography.Pal.Windows
             SafeProvOrNCryptKeyHandle handle,
             CryptProvParam dwParam,
             ref Span<byte> buf,
-            ref byte[] rented,
+            ref byte[]? rented,
             int clearLen)
         {
             int len = buf.Length;
index fa8a165..655e575 100644 (file)
@@ -132,7 +132,7 @@ namespace Internal.Cryptography.Pal.Windows
             }
         }
 
-        public sealed override CryptographicAttributeObject OtherKeyAttribute
+        public sealed override CryptographicAttributeObject? OtherKeyAttribute
         {
             get
             {
@@ -141,7 +141,7 @@ namespace Internal.Cryptography.Pal.Windows
 
                 unsafe
                 {
-                    return WithCmsgCmsRecipientInfo<CryptographicAttributeObject>(
+                    return WithCmsgCmsRecipientInfo<CryptographicAttributeObject?>(
                         delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient)
                         {
                             CMSG_RECIPIENT_ENCRYPTED_KEY_INFO* pEncryptedKeyInfo = recipient->rgpRecipientEncryptedKeys[SubIndex];
index 0f622ab..539dd52 100644 (file)
@@ -26,7 +26,7 @@ namespace Internal.Cryptography.Pal.Windows
             using (SafeCryptMsgHandle hCryptMsg = EncodeHelpers.CreateCryptMsgHandleToEncode(recipients, contentInfo.ContentType, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes))
             {
                 byte[] encodedContent;
-                if (contentInfo.ContentType.Value.Equals(Oids.Pkcs7Data, StringComparison.OrdinalIgnoreCase))
+                if (contentInfo.ContentType.Value!.Equals(Oids.Pkcs7Data, StringComparison.OrdinalIgnoreCase))
                 {
                     encodedContent = PkcsHelpers.EncodeOctetString(contentInfo.Content);
                 }
@@ -106,7 +106,7 @@ namespace Internal.Cryptography.Pal.Windows
                     unsafe
                     {
                         CMSG_ENVELOPED_ENCODE_INFO* pEnvelopedEncodeInfo = CreateCmsEnvelopedEncodeInfo(recipients, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes, hb);
-                        SafeCryptMsgHandle hCryptMsg = Interop.Crypt32.CryptMsgOpenToEncode(MsgEncodingType.All, 0, CryptMsgType.CMSG_ENVELOPED, pEnvelopedEncodeInfo, innerContentType.Value, IntPtr.Zero);
+                        SafeCryptMsgHandle hCryptMsg = Interop.Crypt32.CryptMsgOpenToEncode(MsgEncodingType.All, 0, CryptMsgType.CMSG_ENVELOPED, pEnvelopedEncodeInfo, innerContentType.Value!, IntPtr.Zero);
                         if (hCryptMsg == null || hCryptMsg.IsInvalid)
                             throw Marshal.GetLastWin32Error().ToCryptographicException();
 
@@ -124,7 +124,7 @@ namespace Internal.Cryptography.Pal.Windows
                 pEnvelopedEncodeInfo->cbSize = sizeof(CMSG_ENVELOPED_ENCODE_INFO);
                 pEnvelopedEncodeInfo->hCryptProv = IntPtr.Zero;
 
-                string algorithmOidValue = contentEncryptionAlgorithm.Oid.Value;
+                string algorithmOidValue = contentEncryptionAlgorithm.Oid.Value!;
                 pEnvelopedEncodeInfo->ContentEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(algorithmOidValue);
 
                 // .NET Framework compat: Though it seems like we could copy over the contents of contentEncryptionAlgorithm.Parameters, that property is for retrieving information from decoded Cms's only, and it
@@ -175,7 +175,7 @@ namespace Internal.Cryptography.Pal.Windows
                     for (int i = 0; i < numUnprotectedAttributes; i++)
                     {
                         CryptographicAttributeObject attribute = unprotectedAttributes[i];
-                        pCryptAttribute[i].pszObjId = hb.AllocAsciiString(attribute.Oid.Value);
+                        pCryptAttribute[i].pszObjId = hb.AllocAsciiString(attribute.Oid.Value!);
                         AsnEncodedDataCollection values = attribute.Values;
                         int numValues = values.Count;
                         pCryptAttribute[i].cValue = numValues;
@@ -244,7 +244,7 @@ namespace Internal.Cryptography.Pal.Windows
 
                     pEncodeInfo->cbSize = sizeof(CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO);
 
-                    RSAEncryptionPadding padding = recipient.RSAEncryptionPadding;
+                    RSAEncryptionPadding? padding = recipient.RSAEncryptionPadding;
 
                     if (padding is null)
                     {
@@ -336,7 +336,7 @@ namespace Internal.Cryptography.Pal.Windows
                     pEncodeInfo->pvKeyEncryptionAuxInfo = null;
 
                     string oidValue;
-                    AlgId algId = contentEncryptionAlgorithm.Oid.Value.ToAlgId();
+                    AlgId algId = contentEncryptionAlgorithm.Oid.Value!.ToAlgId();
                     if (algId == AlgId.CALG_RC2)
                         oidValue = Oids.CmsRc2Wrap;
                     else
@@ -417,7 +417,7 @@ namespace Internal.Cryptography.Pal.Windows
             //
             private static IntPtr GenerateEncryptionAuxInfoIfNeeded(AlgorithmIdentifier contentEncryptionAlgorithm, HeapBlockRetainer hb)
             {
-                string algorithmOidValue = contentEncryptionAlgorithm.Oid.Value;
+                string algorithmOidValue = contentEncryptionAlgorithm.Oid.Value!;
                 AlgId algId = algorithmOidValue.ToAlgId();
                 if (!(algId == AlgId.CALG_RC2 || algId == AlgId.CALG_RC4))
                     return IntPtr.Zero;
index 06cf8c7..81c9706 100644 (file)
@@ -14,6 +14,7 @@ using System.Security.Cryptography.X509Certificates;
 using Microsoft.Win32.SafeHandles;
 
 using static Interop.Crypt32;
+using System.Diagnostics.CodeAnalysis;
 
 namespace Internal.Cryptography.Pal.Windows
 {
@@ -91,29 +92,31 @@ namespace Internal.Cryptography.Pal.Windows
             }
         }
 
+        [return: MaybeNull]
         public override T GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent)
         {
             return GetPrivateKey<T>(certificate, silent, preferNCrypt: true);
         }
 
+        [return: MaybeNull]
         public override T GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent)
         {
             return GetPrivateKey<T>(certificate, silent, preferNCrypt: false);
         }
 
-        private T GetPrivateKey<T>(X509Certificate2 certificate, bool silent, bool preferNCrypt) where T : AsymmetricAlgorithm
+        private T? GetPrivateKey<T>(X509Certificate2 certificate, bool silent, bool preferNCrypt) where T : AsymmetricAlgorithm
         {
             if (!certificate.HasPrivateKey)
             {
                 return null;
             }
 
-            SafeProvOrNCryptKeyHandle handle = GetCertificatePrivateKey(
+            SafeProvOrNCryptKeyHandle? handle = GetCertificatePrivateKey(
                 certificate,
                 silent,
                 preferNCrypt,
                 out CryptKeySpec keySpec,
-                out Exception exception);
+                out Exception? exception);
 
             using (handle)
             {
@@ -180,12 +183,12 @@ namespace Internal.Cryptography.Pal.Windows
             }
         }
 
-        internal static SafeProvOrNCryptKeyHandle GetCertificatePrivateKey(
+        internal static SafeProvOrNCryptKeyHandle? GetCertificatePrivateKey(
             X509Certificate2 cert,
             bool silent,
             bool preferNCrypt,
             out CryptKeySpec keySpec,
-            out Exception exception)
+            out Exception? exception)
         {
             CryptAcquireCertificatePrivateKeyFlags flags =
                 CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_USE_PROV_INFO_FLAG
index c696db2..4521098 100644 (file)
@@ -15,6 +15,7 @@ using System.Security.Cryptography.Asn1.Pkcs7;
 using System.Security.Cryptography.Pkcs;
 using System.Security.Cryptography.X509Certificates;
 using X509IssuerSerial = System.Security.Cryptography.Xml.X509IssuerSerial;
+using System.Diagnostics.CodeAnalysis;
 
 namespace Internal.Cryptography
 {
@@ -36,7 +37,7 @@ namespace Internal.Cryptography
             return GetDigestAlgorithm(oid.Value);
         }
 
-        internal static HashAlgorithmName GetDigestAlgorithm(string oidValue, bool forVerification = false)
+        internal static HashAlgorithmName GetDigestAlgorithm(string? oidValue, bool forVerification = false)
         {
             switch (oidValue)
             {
@@ -120,7 +121,7 @@ namespace Internal.Cryptography
 
         public static AttributeAsn[] NormalizeAttributeSet(
             AttributeAsn[] setItems,
-            Action<byte[]> encodedValueProcessor = null)
+            Action<byte[]>? encodedValueProcessor = null)
         {
             byte[] normalizedValue;
 
@@ -227,7 +228,7 @@ namespace Internal.Cryptography
         /// <summary>
         /// .NET Framework compat: We do not complain about multiple matches. Just take the first one and ignore the rest.
         /// </summary>
-        public static X509Certificate2 TryFindMatchingCertificate(this X509Certificate2Collection certs, SubjectIdentifier recipientIdentifier)
+        public static X509Certificate2? TryFindMatchingCertificate(this X509Certificate2Collection certs, SubjectIdentifier recipientIdentifier)
         {
             //
             // Note: SubjectIdentifier has no public constructor so the only one that can construct this type is this assembly.
@@ -239,7 +240,7 @@ namespace Internal.Cryptography
             {
                 case SubjectIdentifierType.IssuerAndSerialNumber:
                     {
-                        X509IssuerSerial issuerSerial = (X509IssuerSerial)(recipientIdentifier.Value);
+                        X509IssuerSerial issuerSerial = (X509IssuerSerial)(recipientIdentifier.Value!);
                         byte[] serialNumber = issuerSerial.SerialNumber.ToSerialBytes();
                         string issuer = issuerSerial.IssuerName;
                         foreach (X509Certificate2 candidate in certs)
@@ -253,7 +254,7 @@ namespace Internal.Cryptography
 
                 case SubjectIdentifierType.SubjectKeyIdentifier:
                     {
-                        string skiString = (string)(recipientIdentifier.Value);
+                        string skiString = (string)(recipientIdentifier.Value!);
                         byte[] ski = skiString.ToSkiBytes();
                         foreach (X509Certificate2 cert in certs)
                         {
@@ -480,7 +481,7 @@ namespace Internal.Cryptography
             Span<byte> tmp = stackalloc byte[ArbitraryStackLimit];
             // Use stackalloc 0 so data can later hold a slice of tmp.
             ReadOnlySpan<byte> data = stackalloc byte[0];
-            byte[] poolBytes = null;
+            byte[]? poolBytes = null;
 
             try
             {
@@ -589,8 +590,8 @@ namespace Internal.Cryptography
 
         public static bool TryGetRsaOaepEncryptionPadding(
             ReadOnlyMemory<byte>? parameters,
-            out RSAEncryptionPadding rsaEncryptionPadding,
-            out Exception exception)
+            [NotNullWhen(true)] out RSAEncryptionPadding? rsaEncryptionPadding,
+            [NotNullWhen(false)] out Exception? exception)
         {
             exception = null;
             rsaEncryptionPadding = null;
index 1899df0..a19ec05 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System;
+using System.Diagnostics.CodeAnalysis;
 using System.Security.Cryptography;
 using System.Security.Cryptography.Pkcs;
 using System.Security.Cryptography.X509Certificates;
@@ -76,12 +77,12 @@ namespace Internal.Cryptography
         /// <summary>
         /// Retrieve a private key object for the certificate to use with signing.
         /// </summary>
-        public abstract T GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent) where T : AsymmetricAlgorithm;
+        public abstract T? GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent) where T : AsymmetricAlgorithm;
 
         /// <summary>
         /// Retrieve a private key object for the certificate to use with decryption.
         /// </summary>
-        public abstract T GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent) where T : AsymmetricAlgorithm;
+        public abstract T? GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent) where T : AsymmetricAlgorithm;
 
         /// <summary>
         /// Get the one instance of PkcsPal.
index c397d7f..8f3d580 100644 (file)
@@ -6,7 +6,7 @@
     <UsePackageTargetRuntimeDefaults Condition="'$(IsPartialFacadeAssembly)' != 'true'">true</UsePackageTargetRuntimeDefaults>
     <IncludeDllSafeSearchPathAttribute>true</IncludeDllSafeSearchPathAttribute>
     <NoWarn>$(NoWarn);CS1574;CS3016;CA5379;CA5384</NoWarn>
-    <Nullable>annotations</Nullable>
+    <Nullable>enable</Nullable>
     <TargetFrameworks>$(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent);netstandard2.0;netstandard2.0-Windows_NT;netstandard2.1;netstandard2.1-Windows_NT;netcoreapp3.0-Windows_NT;netcoreapp3.0;net461-Windows_NT;$(NetFrameworkCurrent)-Windows_NT</TargetFrameworks>
     <ExcludeCurrentNetCoreAppFromPackage>true</ExcludeCurrentNetCoreAppFromPackage>
     <ExcludeCurrentFullFrameworkFromPackage>true</ExcludeCurrentFullFrameworkFromPackage>
index 4f282ee..d147a37 100644 (file)
@@ -17,7 +17,7 @@ namespace System.Security.Cryptography
         {
         }
 
-        public CryptographicAttributeObject(Oid oid, AsnEncodedDataCollection values)
+        public CryptographicAttributeObject(Oid oid, AsnEncodedDataCollection? values)
         {
             _oid = new Oid(oid);
             if (values == null)
@@ -28,7 +28,7 @@ namespace System.Security.Cryptography
             {
                 foreach (AsnEncodedData asn in values)
                 {
-                    if (!string.Equals(asn.Oid.Value, oid.Value, StringComparison.Ordinal))
+                    if (!string.Equals(asn.Oid!.Value, oid.Value, StringComparison.Ordinal))
                         throw new InvalidOperationException(SR.Format(SR.InvalidOperation_WrongOidInAsnCollection, oid.Value, asn.Oid.Value));
                 }
                 Values = values;
index 94bda3c..6b8eeb8 100644 (file)
@@ -29,7 +29,7 @@ namespace System.Security.Cryptography
             if (asnEncodedData == null)
                 throw new ArgumentNullException(nameof(asnEncodedData));
 
-            return Add(new CryptographicAttributeObject(asnEncodedData.Oid, new AsnEncodedDataCollection(asnEncodedData)));
+            return Add(new CryptographicAttributeObject(asnEncodedData.Oid!, new AsnEncodedDataCollection(asnEncodedData)));
         }
 
         public int Add(CryptographicAttributeObject attribute)
@@ -40,7 +40,7 @@ namespace System.Security.Cryptography
             //
             // Merge with existing attribute, if already existed, else add as new.
             //
-            string szOid1 = attribute.Oid.Value;
+            string? szOid1 = attribute.Oid.Value;
             for (int index = 0; index < _list.Count; index++)
             {
                 CryptographicAttributeObject existing = _list[index];
@@ -50,7 +50,7 @@ namespace System.Security.Cryptography
                 if (object.ReferenceEquals(existing.Values, attribute.Values))
                     throw new InvalidOperationException(SR.InvalidOperation_DuplicateItemNotAllowed);
 
-                string szOid2 = existing.Oid.Value;
+                string? szOid2 = existing.Oid.Value;
                 if (string.Equals(szOid1, szOid2, StringComparison.OrdinalIgnoreCase))
                 {
                     //
index 3c6c362..f0efb33 100644 (file)
@@ -2,13 +2,13 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #pragma warning disable SA1028 // ignore whitespace warnings for generated code
 using System;
 using System.Runtime.InteropServices;
 using System.Security.Cryptography;
 using System.Security.Cryptography.Asn1;
 
-#nullable enable
 namespace System.Security.Cryptography.Pkcs.Asn1
 {
     [StructLayout(LayoutKind.Sequential)]
index 35b70d8..8ccaea7 100644 (file)
@@ -2,13 +2,13 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #pragma warning disable SA1028 // ignore whitespace warnings for generated code
 using System;
 using System.Runtime.InteropServices;
 using System.Security.Cryptography;
 using System.Security.Cryptography.Asn1;
 
-#nullable enable
 namespace System.Security.Cryptography.Pkcs.Asn1
 {
     [StructLayout(LayoutKind.Sequential)]
index 8f4b39f..82acb18 100644 (file)
@@ -2,13 +2,13 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #pragma warning disable SA1028 // ignore whitespace warnings for generated code
 using System;
 using System.Runtime.InteropServices;
 using System.Security.Cryptography;
 using System.Security.Cryptography.Asn1;
 
-#nullable enable
 namespace System.Security.Cryptography.Pkcs.Asn1
 {
     [StructLayout(LayoutKind.Sequential)]
index f00d35c..b8e3f7c 100644 (file)
@@ -2,13 +2,13 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #pragma warning disable SA1028 // ignore whitespace warnings for generated code
 using System;
 using System.Runtime.InteropServices;
 using System.Security.Cryptography;
 using System.Security.Cryptography.Asn1;
 
-#nullable enable
 namespace System.Security.Cryptography.Pkcs.Asn1
 {
     [StructLayout(LayoutKind.Sequential)]
index f2d365d..8f4a41a 100644 (file)
@@ -2,13 +2,13 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #pragma warning disable SA1028 // ignore whitespace warnings for generated code
 using System;
 using System.Runtime.InteropServices;
 using System.Security.Cryptography;
 using System.Security.Cryptography.Asn1;
 
-#nullable enable
 namespace System.Security.Cryptography.Pkcs.Asn1
 {
     [StructLayout(LayoutKind.Sequential)]
index 530d1f3..d31c8fc 100644 (file)
@@ -18,7 +18,7 @@ namespace System.Security.Cryptography.Pkcs.Asn1
 
         internal int Version;
         internal System.Security.Cryptography.Pkcs.Asn1.MessageImprint MessageImprint;
-        internal Oid ReqPolicy;
+        internal Oid? ReqPolicy;
         internal ReadOnlyMemory<byte>? Nonce;
         internal bool CertReq;
         internal System.Security.Cryptography.Asn1.X509ExtensionAsn[] Extensions;
index 4feba0c..8b2e7a1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #pragma warning disable SA1028 // ignore whitespace warnings for generated code
 using System;
 using System.Collections.Generic;
@@ -9,7 +10,6 @@ using System.Runtime.InteropServices;
 using System.Security.Cryptography;
 using System.Security.Cryptography.Asn1;
 
-#nullable enable
 namespace System.Security.Cryptography.Pkcs
 {
     [StructLayout(LayoutKind.Sequential)]
index 276a55e..2a0a97b 100644 (file)
@@ -2,13 +2,13 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #pragma warning disable SA1028 // ignore whitespace warnings for generated code
 using System;
 using System.Runtime.InteropServices;
 using System.Security.Cryptography;
 using System.Security.Cryptography.Asn1;
 
-#nullable enable
 namespace System.Security.Cryptography.Pkcs.Asn1
 {
     [StructLayout(LayoutKind.Sequential)]
index e381bbf..dc22672 100644 (file)
@@ -20,7 +20,7 @@ namespace System.Security.Cryptography.Pkcs.Asn1
         internal ReadOnlyMemory<byte>? SignedAttributes;
         internal System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn SignatureAlgorithm;
         internal ReadOnlyMemory<byte> SignatureValue;
-        internal System.Security.Cryptography.Asn1.AttributeAsn[] UnsignedAttributes;
+        internal System.Security.Cryptography.Asn1.AttributeAsn[]? UnsignedAttributes;
 
         internal void Encode(AsnWriter writer)
         {
index 56c2f81..b2f4a38 100644 (file)
@@ -66,7 +66,7 @@ namespace System.Security.Cryptography.Pkcs
 #else
         public
 #endif
-        RSAEncryptionPadding RSAEncryptionPadding { get; }
+        RSAEncryptionPadding? RSAEncryptionPadding { get; }
         public SubjectIdentifierType RecipientIdentifierType { get; }
         public X509Certificate2 Certificate { get; }
 
index e4b23c1..8ecb47c 100644 (file)
@@ -6,6 +6,7 @@ using System.Buffers;
 using System.Collections.Generic;
 using System.Security.Cryptography.X509Certificates;
 using Internal.Cryptography;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Security.Cryptography.Pkcs
 {
@@ -23,9 +24,9 @@ namespace System.Security.Cryptography.Pkcs
         private class DSACmsSignature : CmsSignature
         {
             private readonly HashAlgorithmName _expectedDigest;
-            private readonly string _signatureAlgorithm;
+            private readonly string? _signatureAlgorithm;
 
-            internal DSACmsSignature(string signatureAlgorithm, HashAlgorithmName expectedDigest)
+            internal DSACmsSignature(string? signatureAlgorithm, HashAlgorithmName expectedDigest)
             {
                 _signatureAlgorithm = signatureAlgorithm;
                 _expectedDigest = expectedDigest;
@@ -44,7 +45,7 @@ namespace System.Security.Cryptography.Pkcs
                 byte[] valueHash,
                 byte[] signature,
 #endif
-                string digestAlgorithmOid,
+                string? digestAlgorithmOid,
                 HashAlgorithmName digestAlgorithmName,
                 ReadOnlyMemory<byte>? signatureParameters,
                 X509Certificate2 certificate)
@@ -100,10 +101,10 @@ namespace System.Security.Cryptography.Pkcs
 #endif
                 HashAlgorithmName hashAlgorithmName,
                 X509Certificate2 certificate,
-                AsymmetricAlgorithm key,
+                AsymmetricAlgorithm? key,
                 bool silent,
-                out Oid signatureAlgorithm,
-                out byte[] signatureValue)
+                [NotNullWhen(true)] out Oid? signatureAlgorithm,
+                [NotNullWhen(true)] out byte[]? signatureValue)
             {
                 // If there's no private key, fall back to the public key for a "no private key" exception.
                 DSA dsa = key as DSA ??
@@ -117,7 +118,7 @@ namespace System.Security.Cryptography.Pkcs
                     return false;
                 }
 
-                string oidValue =
+                string? oidValue =
                     hashAlgorithmName == HashAlgorithmName.SHA1 ? Oids.DsaWithSha1 :
                     hashAlgorithmName == HashAlgorithmName.SHA256 ? Oids.DsaWithSha256 :
                     hashAlgorithmName == HashAlgorithmName.SHA384 ? Oids.DsaWithSha384 :
index 7ba8e50..f1c9707 100644 (file)
@@ -4,6 +4,7 @@
 
 using System.Buffers;
 using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
 using System.Security.Cryptography.X509Certificates;
 using Internal.Cryptography;
 
@@ -23,9 +24,9 @@ namespace System.Security.Cryptography.Pkcs
         private partial class ECDsaCmsSignature : CmsSignature
         {
             private readonly HashAlgorithmName _expectedDigest;
-            private readonly string _signatureAlgorithm;
+            private readonly string? _signatureAlgorithm;
 
-            internal ECDsaCmsSignature(string signatureAlgorithm, HashAlgorithmName expectedDigest)
+            internal ECDsaCmsSignature(string? signatureAlgorithm, HashAlgorithmName expectedDigest)
             {
                 _signatureAlgorithm = signatureAlgorithm;
                 _expectedDigest = expectedDigest;
@@ -44,7 +45,7 @@ namespace System.Security.Cryptography.Pkcs
                 byte[] valueHash,
                 byte[] signature,
 #endif
-                string digestAlgorithmOid,
+                string? digestAlgorithmOid,
                 HashAlgorithmName digestAlgorithmName,
                 ReadOnlyMemory<byte>? signatureParameters,
                 X509Certificate2 certificate)
@@ -105,10 +106,10 @@ namespace System.Security.Cryptography.Pkcs
 #endif
                 HashAlgorithmName hashAlgorithmName,
                 X509Certificate2 certificate,
-                AsymmetricAlgorithm certKey,
+                AsymmetricAlgorithm? certKey,
                 bool silent,
-                out Oid signatureAlgorithm,
-                out byte[] signatureValue)
+                [NotNullWhen(true)] out Oid? signatureAlgorithm,
+                [NotNullWhen(true)] out byte[]? signatureValue)
             {
                 // If there's no private key, fall back to the public key for a "no private key" exception.
                 ECDsa key = certKey as ECDsa ??
@@ -122,7 +123,7 @@ namespace System.Security.Cryptography.Pkcs
                     return false;
                 }
 
-                string oidValue =
+                string? oidValue =
                     hashAlgorithmName == HashAlgorithmName.SHA1 ? Oids.ECDsaWithSha1 :
                     hashAlgorithmName == HashAlgorithmName.SHA256 ? Oids.ECDsaWithSha256 :
                     hashAlgorithmName == HashAlgorithmName.SHA384 ? Oids.ECDsaWithSha384 :
index 59cf00c..cd65a88 100644 (file)
@@ -4,6 +4,7 @@
 
 using System.Collections.Generic;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Security.Cryptography.Asn1;
 using System.Security.Cryptography.Pkcs.Asn1;
 using System.Security.Cryptography.X509Certificates;
@@ -25,10 +26,10 @@ namespace System.Security.Cryptography.Pkcs
 
         private abstract class RSACmsSignature : CmsSignature
         {
-            private readonly string _signatureAlgorithm;
+            private readonly string? _signatureAlgorithm;
             private readonly HashAlgorithmName? _expectedDigest;
 
-            protected RSACmsSignature(string signatureAlgorithm, HashAlgorithmName? expectedDigest)
+            protected RSACmsSignature(string? signatureAlgorithm, HashAlgorithmName? expectedDigest)
             {
                 _signatureAlgorithm = signatureAlgorithm;
                 _expectedDigest = expectedDigest;
@@ -47,7 +48,7 @@ namespace System.Security.Cryptography.Pkcs
                 byte[] valueHash,
                 byte[] signature,
 #endif
-                string digestAlgorithmOid,
+                string? digestAlgorithmOid,
                 HashAlgorithmName digestAlgorithmName,
                 ReadOnlyMemory<byte>? signatureParameters,
                 X509Certificate2 certificate)
@@ -87,21 +88,21 @@ namespace System.Security.Cryptography.Pkcs
 
             protected abstract RSASignaturePadding GetSignaturePadding(
                 ReadOnlyMemory<byte>? signatureParameters,
-                string digestAlgorithmOid,
+                string? digestAlgorithmOid,
                 HashAlgorithmName digestAlgorithmName,
                 int digestValueLength);
         }
 
         private sealed class RSAPkcs1CmsSignature : RSACmsSignature
         {
-            public RSAPkcs1CmsSignature(string signatureAlgorithm, HashAlgorithmName? expectedDigest)
+            public RSAPkcs1CmsSignature(string? signatureAlgorithm, HashAlgorithmName? expectedDigest)
                 : base(signatureAlgorithm, expectedDigest)
             {
             }
 
             protected override RSASignaturePadding GetSignaturePadding(
                 ReadOnlyMemory<byte>? signatureParameters,
-                string digestAlgorithmOid,
+                string? digestAlgorithmOid,
                 HashAlgorithmName digestAlgorithmName,
                 int digestValueLength)
             {
@@ -130,10 +131,10 @@ namespace System.Security.Cryptography.Pkcs
 #endif
                 HashAlgorithmName hashAlgorithmName,
                 X509Certificate2 certificate,
-                AsymmetricAlgorithm key,
+                AsymmetricAlgorithm? key,
                 bool silent,
-                out Oid signatureAlgorithm,
-                out byte[] signatureValue)
+                [NotNullWhen(true)] out Oid? signatureAlgorithm,
+                [NotNullWhen(true)] out byte[]? signatureValue)
             {
                 RSA certPublicKey = certificate.GetRSAPublicKey();
 
@@ -203,7 +204,7 @@ namespace System.Security.Cryptography.Pkcs
 
             protected override RSASignaturePadding GetSignaturePadding(
                 ReadOnlyMemory<byte>? signatureParameters,
-                string digestAlgorithmOid,
+                string? digestAlgorithmOid,
                 HashAlgorithmName digestAlgorithmName,
                 int digestValueLength)
             {
@@ -274,7 +275,7 @@ namespace System.Security.Cryptography.Pkcs
 #endif
                 HashAlgorithmName hashAlgorithmName,
                 X509Certificate2 certificate,
-                AsymmetricAlgorithm key,
+                AsymmetricAlgorithm? key,
                 bool silent,
                 out Oid signatureAlgorithm,
                 out byte[] signatureValue)
index 4bec2a4..2ae38f7 100644 (file)
@@ -4,6 +4,7 @@
 
 using System.Collections.Generic;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Numerics;
 using System.Security.Cryptography.Asn1;
 using System.Security.Cryptography.X509Certificates;
@@ -36,7 +37,7 @@ namespace System.Security.Cryptography.Pkcs
             byte[] valueHash,
             byte[] signature,
 #endif
-            string digestAlgorithmOid,
+            string? digestAlgorithmOid,
             HashAlgorithmName digestAlgorithmName,
             ReadOnlyMemory<byte>? signatureParameters,
             X509Certificate2 certificate);
@@ -49,14 +50,14 @@ namespace System.Security.Cryptography.Pkcs
 #endif
             HashAlgorithmName hashAlgorithmName,
             X509Certificate2 certificate,
-            AsymmetricAlgorithm key,
+            AsymmetricAlgorithm? key,
             bool silent,
-            out Oid signatureAlgorithm,
-            out byte[] signatureValue);
+            [NotNullWhen(true)] out Oid? signatureAlgorithm,
+            [NotNullWhen(true)] out byte[]? signatureValue);
 
-        internal static CmsSignature ResolveAndVerifyKeyType(string signatureAlgorithmOid, AsymmetricAlgorithm key)
+        internal static CmsSignature? ResolveAndVerifyKeyType(string signatureAlgorithmOid, AsymmetricAlgorithm? key)
         {
-            if (s_lookup.TryGetValue(signatureAlgorithmOid, out CmsSignature processor))
+            if (s_lookup.TryGetValue(signatureAlgorithmOid, out CmsSignature? processor))
             {
                 if (key != null && !processor.VerifyKeyType(key))
                 {
@@ -77,12 +78,12 @@ namespace System.Security.Cryptography.Pkcs
 #endif
             HashAlgorithmName hashAlgorithmName,
             X509Certificate2 certificate,
-            AsymmetricAlgorithm key,
+            AsymmetricAlgorithm? key,
             bool silent,
-            out Oid oid,
+            out Oid? oid,
             out ReadOnlyMemory<byte> signatureValue)
         {
-            CmsSignature processor = ResolveAndVerifyKeyType(certificate.GetKeyAlgorithm(), key);
+            CmsSignature? processor = ResolveAndVerifyKeyType(certificate.GetKeyAlgorithm(), key);
 
             if (processor == null)
             {
@@ -91,8 +92,7 @@ namespace System.Security.Cryptography.Pkcs
                 return false;
             }
 
-            byte[] signature;
-            bool signed = processor.Sign(dataHash, hashAlgorithmName, certificate, key, silent, out oid, out signature);
+            bool signed = processor.Sign(dataHash, hashAlgorithmName, certificate, key, silent, out oid, out byte[]? signature);
 
             signatureValue = signature;
             return signed;
index a5a2ddc..d515b1d 100644 (file)
@@ -17,8 +17,8 @@ namespace System.Security.Cryptography.Pkcs
 
         private SubjectIdentifierType _signerIdentifierType;
 
-        public X509Certificate2 Certificate { get; set; }
-        public AsymmetricAlgorithm PrivateKey { get; set; }
+        public X509Certificate2? Certificate { get; set; }
+        public AsymmetricAlgorithm? PrivateKey { get; set; }
         public X509Certificate2Collection Certificates { get; private set; } = new X509Certificate2Collection();
         public Oid DigestAlgorithm { get; set; }
         public X509IncludeOption IncludeOption { get; set; }
@@ -46,7 +46,7 @@ namespace System.Security.Cryptography.Pkcs
         {
         }
 
-        public CmsSigner(X509Certificate2 certificate)
+        public CmsSigner(X509Certificate2? certificate)
             : this(SubjectIdentifierType.IssuerAndSerialNumber, certificate)
         {
         }
@@ -62,11 +62,11 @@ namespace System.Security.Cryptography.Pkcs
         // CertCreateSelfSignedCertificate on a split Windows/netstandard implementation.
         public CmsSigner(CspParameters parameters) => throw new PlatformNotSupportedException();
 
-        public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2 certificate) : this(signerIdentifierType, certificate, null)
+        public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2? certificate) : this(signerIdentifierType, certificate, null)
         {
         }
 
-        public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2 certificate, AsymmetricAlgorithm privateKey)
+        public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2? certificate, AsymmetricAlgorithm? privateKey)
         {
             switch (signerIdentifierType)
             {
@@ -117,7 +117,7 @@ namespace System.Security.Cryptography.Pkcs
 
         internal SignerInfoAsn Sign(
             ReadOnlyMemory<byte> data,
-            string contentTypeOid,
+            string? contentTypeOid,
             bool silent,
             out X509Certificate2Collection chainCerts)
         {
@@ -183,7 +183,7 @@ namespace System.Security.Cryptography.Pkcs
             switch (SignerIdentifierType)
             {
                 case SubjectIdentifierType.IssuerAndSerialNumber:
-                    byte[] serial = Certificate.GetSerialNumber();
+                    byte[] serial = Certificate!.GetSerialNumber();
                     Array.Reverse(serial);
 
                     newSignerInfo.Sid.IssuerAndSerialNumber = new IssuerAndSerialNumberAsn
@@ -195,7 +195,7 @@ namespace System.Security.Cryptography.Pkcs
                     newSignerInfo.Version = 1;
                     break;
                 case SubjectIdentifierType.SubjectKeyIdentifier:
-                    newSignerInfo.Sid.SubjectKeyIdentifier = PkcsPal.Instance.GetSubjectKeyIdentifier(Certificate);
+                    newSignerInfo.Sid.SubjectKeyIdentifier = PkcsPal.Instance.GetSubjectKeyIdentifier(Certificate!);
                     newSignerInfo.Version = 3;
                     break;
                 case SubjectIdentifierType.NoSignature:
@@ -219,7 +219,7 @@ namespace System.Security.Cryptography.Pkcs
             }
 
             bool signed;
-            Oid signatureAlgorithm;
+            Oid? signatureAlgorithm;
             ReadOnlyMemory<byte> signatureValue;
 
             if (SignerIdentifierType == SubjectIdentifierType.NoSignature)
@@ -233,7 +233,7 @@ namespace System.Security.Cryptography.Pkcs
                 signed = CmsSignature.Sign(
                     dataHash,
                     hashAlgorithmName,
-                    Certificate,
+                    Certificate!,
                     PrivateKey,
                     silent,
                     out signatureAlgorithm,
@@ -246,7 +246,7 @@ namespace System.Security.Cryptography.Pkcs
             }
 
             newSignerInfo.SignatureValue = signatureValue;
-            newSignerInfo.SignatureAlgorithm.Algorithm = signatureAlgorithm;
+            newSignerInfo.SignatureAlgorithm.Algorithm = signatureAlgorithm!;
 
             X509Certificate2Collection certs = new X509Certificate2Collection();
             certs.AddRange(Certificates);
@@ -304,7 +304,7 @@ namespace System.Security.Cryptography.Pkcs
             return newSignerInfo;
         }
 
-        internal static List<AttributeAsn> BuildAttributes(CryptographicAttributeObjectCollection attributes)
+        internal static List<AttributeAsn> BuildAttributes(CryptographicAttributeObjectCollection? attributes)
         {
             List<AttributeAsn> signedAttrs = new List<AttributeAsn>();
 
index c45626c..177baa1 100644 (file)
@@ -72,6 +72,7 @@ namespace System.Security.Cryptography.Pkcs
 
                     case LastCall.Decode:
                     case LastCall.Decrypt:
+                        Debug.Assert(_decryptorPal != null);
                         return _decryptorPal.RecipientInfos;
 
                     default:
@@ -188,7 +189,7 @@ namespace System.Security.Cryptography.Pkcs
             DecryptContent(RecipientInfos, extraStore);
         }
 
-        public void Decrypt(RecipientInfo recipientInfo, AsymmetricAlgorithm privateKey)
+        public void Decrypt(RecipientInfo recipientInfo, AsymmetricAlgorithm? privateKey)
         {
             if (recipientInfo == null)
                 throw new ArgumentNullException(nameof(recipientInfo));
@@ -196,21 +197,21 @@ namespace System.Security.Cryptography.Pkcs
             CheckStateForDecryption();
 
             X509Certificate2Collection extraStore = new X509Certificate2Collection();
-            ContentInfo contentInfo = _decryptorPal.TryDecrypt(
+            ContentInfo? contentInfo = _decryptorPal!.TryDecrypt(
                 recipientInfo,
                 null,
                 privateKey,
                 Certificates,
                 extraStore,
-                out Exception exception);
+                out Exception? exception);
 
             if (exception != null)
                 throw exception;
 
-            SetContentInfo(contentInfo);
+            SetContentInfo(contentInfo!);
         }
 
-        private void DecryptContent(RecipientInfoCollection recipientInfos, X509Certificate2Collection extraStore)
+        private void DecryptContent(RecipientInfoCollection recipientInfos, X509Certificate2Collection? extraStore)
         {
             CheckStateForDecryption();
             extraStore = extraStore ?? new X509Certificate2Collection();
@@ -221,18 +222,18 @@ namespace System.Security.Cryptography.Pkcs
 
             X509Certificate2Collection originatorCerts = Certificates;
 
-            ContentInfo newContentInfo = null;
-            Exception exception = PkcsPal.Instance.CreateRecipientsNotFoundException();
+            ContentInfo? newContentInfo = null;
+            Exception? exception = PkcsPal.Instance.CreateRecipientsNotFoundException();
             foreach (RecipientInfo recipientInfo in recipientInfos)
             {
-                X509Certificate2 cert = certs.TryFindMatchingCertificate(recipientInfo.RecipientIdentifier);
+                X509Certificate2? cert = certs.TryFindMatchingCertificate(recipientInfo.RecipientIdentifier);
                 if (cert == null)
                 {
                     exception = PkcsPal.Instance.CreateRecipientsNotFoundException();
                     continue;
                 }
 
-                newContentInfo = _decryptorPal.TryDecrypt(
+                newContentInfo = _decryptorPal!.TryDecrypt(
                     recipientInfo,
                     cert,
                     null,
@@ -249,7 +250,7 @@ namespace System.Security.Cryptography.Pkcs
             if (exception != null)
                 throw exception;
 
-            SetContentInfo(newContentInfo);
+            SetContentInfo(newContentInfo!);
         }
 
         private void CheckStateForDecryption()
@@ -288,8 +289,8 @@ namespace System.Security.Cryptography.Pkcs
         // Instance fields
         //
 
-        private DecryptorPal _decryptorPal;
-        private byte[] _encodedMessage;
+        private DecryptorPal? _decryptorPal;
+        private byte[]? _encodedMessage;
         private LastCall _lastCall;
 
         private enum LastCall
index 7ec8f09..701dfdc 100644 (file)
@@ -70,7 +70,7 @@ namespace System.Security.Cryptography.Pkcs
             }
         }
 
-        public CryptographicAttributeObject OtherKeyAttribute
+        public CryptographicAttributeObject? OtherKeyAttribute
         {
             get
             {
@@ -86,11 +86,11 @@ namespace System.Security.Cryptography.Pkcs
             }
         }
 
-        private volatile SubjectIdentifier _lazyRecipientIdentifier = null;
-        private volatile AlgorithmIdentifier _lazyKeyEncryptionAlgorithm = null;
-        private volatile byte[] _lazyEncryptedKey = null;
-        private volatile SubjectIdentifierOrKey _lazyOriginatorIdentifierKey = null;
+        private volatile SubjectIdentifier? _lazyRecipientIdentifier = null;
+        private volatile AlgorithmIdentifier? _lazyKeyEncryptionAlgorithm = null;
+        private volatile byte[]? _lazyEncryptedKey = null;
+        private volatile SubjectIdentifierOrKey? _lazyOriginatorIdentifierKey = null;
         private DateTime? _lazyDate = default(DateTime?);
-        private volatile CryptographicAttributeObject _lazyOtherKeyAttribute = null;
+        private volatile CryptographicAttributeObject? _lazyOtherKeyAttribute = null;
     }
 }
index 95897e8..bf8c133 100644 (file)
@@ -56,8 +56,8 @@ namespace System.Security.Cryptography.Pkcs
             }
         }
 
-        private volatile SubjectIdentifier _lazyRecipientIdentifier = null;
-        private volatile AlgorithmIdentifier _lazyKeyEncryptionAlgorithm = null;
-        private volatile byte[] _lazyEncryptedKey = null;
+        private volatile SubjectIdentifier? _lazyRecipientIdentifier = null;
+        private volatile AlgorithmIdentifier? _lazyKeyEncryptionAlgorithm = null;
+        private volatile byte[]? _lazyEncryptedKey = null;
     }
 }
index 6cc9858..4290deb 100644 (file)
@@ -15,13 +15,13 @@ namespace System.Security.Cryptography.Pkcs
     public sealed class Pkcs12Builder
     {
         private ReadOnlyMemory<byte> _sealedData;
-        private List<ContentInfoAsn> _contents;
+        private List<ContentInfoAsn>? _contents;
 
         public bool IsSealed => !_sealedData.IsEmpty;
 
         public void AddSafeContentsEncrypted(
             Pkcs12SafeContents safeContents,
-            byte[] passwordBytes,
+            byte[]? passwordBytes,
             PbeParameters pbeParameters)
         {
             AddSafeContentsEncrypted(
@@ -69,7 +69,7 @@ namespace System.Security.Cryptography.Pkcs
 
         public void AddSafeContentsEncrypted(
             Pkcs12SafeContents safeContents,
-            string password,
+            string? password,
             PbeParameters pbeParameters)
         {
             AddSafeContentsEncrypted(
@@ -141,7 +141,7 @@ namespace System.Security.Cryptography.Pkcs
         }
 
         public void SealWithMac(
-            string password,
+            string? password,
             HashAlgorithmName hashAlgorithm,
             int iterationCount)
         {
@@ -162,9 +162,9 @@ namespace System.Security.Cryptography.Pkcs
             if (IsSealed)
                 throw new InvalidOperationException(SR.Cryptography_Pkcs12_PfxIsSealed);
 
-            byte[] rentedAuthSafe = null;
+            byte[]? rentedAuthSafe = null;
             Span<byte> authSafeSpan = default;
-            byte[] rentedMac = null;
+            byte[]? rentedMac = null;
             Span<byte> macSpan = default;
             Span<byte> salt = stackalloc byte[0];
 
index b9967b5..7496e00 100644 (file)
@@ -11,7 +11,7 @@ namespace System.Security.Cryptography.Pkcs
 {
     public sealed class Pkcs12CertBag : Pkcs12SafeBag
     {
-        private Oid _certTypeOid;
+        private Oid? _certTypeOid;
         private readonly CertBagAsn _decoded;
 
         public bool IsX509Certificate { get; }
index 82d07ca..d101234 100644 (file)
@@ -17,14 +17,14 @@ namespace System.Security.Cryptography.Pkcs
         private PfxAsn _decoded;
         private ReadOnlyMemory<byte> _authSafeContents;
 
-        public ReadOnlyCollection<Pkcs12SafeContents> AuthenticatedSafe { get; private set; }
+        public ReadOnlyCollection<Pkcs12SafeContents> AuthenticatedSafe { get; private set; } = null!; // Initialized using object initializer
         public Pkcs12IntegrityMode IntegrityMode { get; private set; }
 
         private Pkcs12Info()
         {
         }
 
-        public bool VerifyMac(string password)
+        public bool VerifyMac(string? password)
         {
             // This extension-method call allows null.
             return VerifyMac(password.AsSpan());
index 1d2c719..054c9c9 100644 (file)
@@ -11,8 +11,8 @@ namespace System.Security.Cryptography.Pkcs
     public abstract class Pkcs12SafeBag
     {
         private readonly string _bagIdValue;
-        private Oid _bagOid;
-        private CryptographicAttributeObjectCollection _attributes;
+        private Oid? _bagOid;
+        private CryptographicAttributeObjectCollection? _attributes;
 
         public ReadOnlyMemory<byte> EncodedBagValue { get; }
 
index 4435318..49a4a24 100644 (file)
@@ -16,7 +16,7 @@ namespace System.Security.Cryptography.Pkcs
     public sealed class Pkcs12SafeContents
     {
         private ReadOnlyMemory<byte> _encrypted;
-        private List<Pkcs12SafeBag> _bags;
+        private List<Pkcs12SafeBag>? _bags;
 
         public Pkcs12ConfidentialityMode ConfidentialityMode { get; private set; }
         public bool IsReadOnly { get; }
@@ -112,7 +112,7 @@ namespace System.Security.Cryptography.Pkcs
 
         public Pkcs12ShroudedKeyBag AddShroudedKey(
             AsymmetricAlgorithm key,
-            byte[] passwordBytes,
+            byte[]? passwordBytes,
             PbeParameters pbeParameters)
         {
             return AddShroudedKey(
@@ -140,7 +140,7 @@ namespace System.Security.Cryptography.Pkcs
 
         public Pkcs12ShroudedKeyBag AddShroudedKey(
             AsymmetricAlgorithm key,
-            string password,
+            string? password,
             PbeParameters pbeParameters)
         {
             return AddShroudedKey(
@@ -181,7 +181,7 @@ namespace System.Security.Cryptography.Pkcs
             return bag;
         }
 
-        public void Decrypt(byte[] passwordBytes)
+        public void Decrypt(byte[]? passwordBytes)
         {
             // Null is permitted
             Decrypt(new ReadOnlySpan<byte>(passwordBytes));
@@ -192,7 +192,7 @@ namespace System.Security.Cryptography.Pkcs
             Decrypt(ReadOnlySpan<char>.Empty, passwordBytes);
         }
 
-        public void Decrypt(string password)
+        public void Decrypt(string? password)
         {
             // The string.AsSpan extension method allows null.
             Decrypt(password.AsSpan());
@@ -302,7 +302,7 @@ namespace System.Security.Cryptography.Pkcs
             for (int i = 0; i < serializedBags.Count; i++)
             {
                 ReadOnlyMemory<byte> bagValue = serializedBags[i].BagValue;
-                Pkcs12SafeBag bag = null;
+                Pkcs12SafeBag? bag = null;
 
                 try
                 {
@@ -352,7 +352,7 @@ namespace System.Security.Cryptography.Pkcs
             Debug.Assert(pbeParameters != null);
             Debug.Assert(pbeParameters.IterationCount >= 1);
 
-            AsnWriter writer = null;
+            AsnWriter? writer = null;
 
             using (AsnWriter contentsWriter = Encode())
             {
index 3249985..cda6344 100644 (file)
@@ -9,7 +9,7 @@ namespace System.Security.Cryptography.Pkcs
 {
     public sealed class Pkcs12SafeContentsBag : Pkcs12SafeBag
     {
-        public Pkcs12SafeContents SafeContents { get; private set; }
+        public Pkcs12SafeContents? SafeContents { get; private set; }
 
         private Pkcs12SafeContentsBag(ReadOnlyMemory<byte> encoded)
             : base(Oids.Pkcs12SafeContentsBag, encoded)
index 0be591f..e275fca 100644 (file)
@@ -10,7 +10,7 @@ namespace System.Security.Cryptography.Pkcs
 {
     public sealed class Pkcs12SecretBag : Pkcs12SafeBag
     {
-        private Oid _secretTypeOid;
+        private Oid? _secretTypeOid;
         private readonly SecretBagAsn _decoded;
 
         public ReadOnlyMemory<byte> SecretValue => _decoded.SecretValue;
@@ -46,7 +46,7 @@ namespace System.Security.Cryptography.Pkcs
 
         private static byte[] EncodeBagValue(Oid secretTypeOid, in ReadOnlyMemory<byte> secretValue)
         {
-            Debug.Assert(secretTypeOid != null);
+            Debug.Assert(secretTypeOid != null && secretTypeOid.Value != null);
 
             SecretBagAsn secretBagAsn = new SecretBagAsn
             {
index 48a9638..97bc53b 100644 (file)
@@ -203,7 +203,7 @@ namespace System.Security.Cryptography.Pkcs
             finally
             {
                 CryptographicOperations.ZeroMemory(decryptedMemory.Span);
-                CryptoPool.Return(decrypted.Array, clearSize: 0);
+                CryptoPool.Return(decrypted.Array!, clearSize: 0);
             }
         }
 
@@ -235,7 +235,7 @@ namespace System.Security.Cryptography.Pkcs
             finally
             {
                 CryptographicOperations.ZeroMemory(decryptedMemory.Span);
-                CryptoPool.Return(decrypted.Array, clearSize: 0);
+                CryptoPool.Return(decrypted.Array!, clearSize: 0);
             }
         }
 
index 4322404..11bb644 100644 (file)
@@ -33,7 +33,7 @@ namespace System.Security.Cryptography.Pkcs
         {
             if (asnEncodedData.Oid == null)
                 throw new ArgumentNullException(nameof(asnEncodedData.Oid));
-            string szOid = base.Oid.Value;
+            string? szOid = base.Oid!.Value;
             if (szOid == null)
                 throw new ArgumentNullException("oid.Value");
             if (szOid.Length == 0)
@@ -49,7 +49,7 @@ namespace System.Security.Cryptography.Pkcs
         // Public properties.
         //
 
-        public new Oid Oid
+        public new Oid? Oid
         {
             get
             {
index 0d26ded..56f55b0 100644 (file)
@@ -4,7 +4,7 @@
 
 using System;
 using System.Diagnostics;
-
+using System.Diagnostics.CodeAnalysis;
 using Internal.Cryptography;
 
 namespace System.Security.Cryptography.Pkcs
@@ -42,7 +42,8 @@ namespace System.Security.Cryptography.Pkcs
         // Private methods.
         //
 
-        private static Oid Decode(byte[] rawData)
+        [return: NotNullIfNotNull("rawData")]
+        private static Oid? Decode(byte[]? rawData)
         {
             if (rawData == null)
                 return null;
@@ -51,6 +52,6 @@ namespace System.Security.Cryptography.Pkcs
             return new Oid(contentTypeValue);
         }
 
-        private volatile Oid _lazyContentType = null;
+        private volatile Oid? _lazyContentType = null;
     }
 }
index 4ba41c3..8104f83 100644 (file)
@@ -4,7 +4,7 @@
 
 using System;
 using System.Diagnostics;
-
+using System.Diagnostics.CodeAnalysis;
 using Internal.Cryptography;
 
 namespace System.Security.Cryptography.Pkcs
@@ -55,7 +55,8 @@ namespace System.Security.Cryptography.Pkcs
         // Private methods.
         //
 
-        private static string Decode(byte[] rawData)
+        [return: NotNullIfNotNull("rawData")]
+        private static string? Decode(byte[]? rawData)
         {
             if (rawData == null)
                 return null;
@@ -73,6 +74,6 @@ namespace System.Security.Cryptography.Pkcs
             return PkcsHelpers.EncodeOctetString(octets);
         }
 
-        private volatile string _lazyDocumentDescription = null;
+        private volatile string? _lazyDocumentDescription = null;
     }
 }
index 9d48573..340a320 100644 (file)
@@ -4,7 +4,7 @@
 
 using System;
 using System.Diagnostics;
-
+using System.Diagnostics.CodeAnalysis;
 using Internal.Cryptography;
 
 namespace System.Security.Cryptography.Pkcs
@@ -55,7 +55,8 @@ namespace System.Security.Cryptography.Pkcs
         // Private methods.
         //
 
-        private static string Decode(byte[] rawData)
+        [return: NotNullIfNotNull("rawData")]
+        private static string? Decode(byte[]? rawData)
         {
             if (rawData == null)
                 return null;
@@ -73,6 +74,6 @@ namespace System.Security.Cryptography.Pkcs
             return PkcsHelpers.EncodeOctetString(octets);
         }
 
-        private volatile string _lazyDocumentName = null;
+        private volatile string? _lazyDocumentName = null;
     }
 }
index 64228cd..92584dd 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+using System.Diagnostics.CodeAnalysis;
 using System.Security.Cryptography.Asn1;
 using Internal.Cryptography;
 
@@ -9,7 +10,7 @@ namespace System.Security.Cryptography.Pkcs
 {
     public sealed class Pkcs9LocalKeyId : Pkcs9AttributeObject
     {
-        private byte[] _lazyKeyId;
+        private byte[]? _lazyKeyId;
 
         public Pkcs9LocalKeyId() :
             base(new Oid(Oids.LocalKeyId))
@@ -41,7 +42,8 @@ namespace System.Security.Cryptography.Pkcs
             _lazyKeyId = null;
         }
 
-        private static byte[] Decode(byte[] rawData)
+        [return: NotNullIfNotNull("rawData")]
+        private static byte[]? Decode(byte[]? rawData)
         {
             if (rawData == null)
             {
index b5c26bb..7361976 100644 (file)
@@ -4,6 +4,7 @@
 
 using System;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Security.Cryptography.Asn1;
 using Internal.Cryptography;
 
@@ -51,7 +52,8 @@ namespace System.Security.Cryptography.Pkcs
         // Private methods.
         //
 
-        private static byte[] Decode(byte[] rawData)
+        [return: NotNullIfNotNull("rawData")]
+        private static byte[]? Decode(byte[]? rawData)
         {
             if (rawData == null)
                 return null;
@@ -59,6 +61,6 @@ namespace System.Security.Cryptography.Pkcs
             return PkcsHelpers.DecodeOctetString(rawData);
         }
 
-        private volatile byte[] _lazyMessageDigest = null;
+        private volatile byte[]? _lazyMessageDigest = null;
     }
 }
index 630c529..24d398c 100644 (file)
@@ -59,7 +59,7 @@ namespace System.Security.Cryptography.Pkcs
         // Private methods.
         //
 
-        private static DateTime Decode(byte[] rawData)
+        private static DateTime Decode(byte[]? rawData)
         {
             if (rawData == null)
                 return default(DateTime);
index d53cf06..15e9076 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Linq;
 using System.Security.Cryptography.Asn1;
 using System.Security.Cryptography.Pkcs.Asn1;
@@ -13,7 +14,7 @@ namespace System.Security.Cryptography.Pkcs
 {
     public sealed class Rfc3161TimestampRequest
     {
-        private byte[] _encodedBytes;
+        private byte[] _encodedBytes = null!; // Initided using object initializer
         private Rfc3161TimeStampReq _parsedData;
 
         private Rfc3161TimestampRequest()
@@ -23,7 +24,7 @@ namespace System.Security.Cryptography.Pkcs
         public int Version => _parsedData.Version;
         public ReadOnlyMemory<byte> GetMessageHash() => _parsedData.MessageImprint.HashedMessage;
         public Oid HashAlgorithmId => _parsedData.MessageImprint.HashAlgorithm.Algorithm;
-        public Oid RequestedPolicyId => _parsedData.ReqPolicy;
+        public Oid? RequestedPolicyId => _parsedData.ReqPolicy;
         public bool RequestSignerCertificate => _parsedData.CertReq;
         public ReadOnlyMemory<byte>? GetNonce() => _parsedData.Nonce;
         public bool HasExtensions => _parsedData.Extensions?.Length > 0;
@@ -57,10 +58,7 @@ namespace System.Security.Cryptography.Pkcs
 
         public Rfc3161TimestampToken ProcessResponse(ReadOnlyMemory<byte> source, out int bytesConsumed)
         {
-            Rfc3161RequestResponseStatus status;
-            Rfc3161TimestampToken token;
-
-            if (ProcessResponse(source, out token, out status, out int localBytesRead, shouldThrow: true))
+            if (ProcessResponse(source, out Rfc3161TimestampToken? token, out Rfc3161RequestResponseStatus status, out int localBytesRead, shouldThrow: true))
             {
                 Debug.Assert(status == Rfc3161RequestResponseStatus.Accepted);
                 bytesConsumed = localBytesRead;
@@ -73,7 +71,7 @@ namespace System.Security.Cryptography.Pkcs
 
         private bool ProcessResponse(
             ReadOnlyMemory<byte> source,
-            out Rfc3161TimestampToken token,
+            [NotNullWhen(true)] out Rfc3161TimestampToken? token,
             out Rfc3161RequestResponseStatus status,
             out int bytesConsumed,
             bool shouldThrow)
@@ -155,10 +153,10 @@ namespace System.Security.Cryptography.Pkcs
         public static Rfc3161TimestampRequest CreateFromSignerInfo(
             SignerInfo signerInfo,
             HashAlgorithmName hashAlgorithm,
-            Oid requestedPolicyId = null,
+            Oid? requestedPolicyId = null,
             ReadOnlyMemory<byte>? nonce = null,
             bool requestSignerCertificates = false,
-            X509ExtensionCollection extensions = null)
+            X509ExtensionCollection? extensions = null)
         {
             if (signerInfo == null)
             {
@@ -182,10 +180,10 @@ namespace System.Security.Cryptography.Pkcs
         public static Rfc3161TimestampRequest CreateFromData(
             ReadOnlySpan<byte> data,
             HashAlgorithmName hashAlgorithm,
-            Oid requestedPolicyId = null,
+            Oid? requestedPolicyId = null,
             ReadOnlyMemory<byte>? nonce = null,
             bool requestSignerCertificates = false,
-            X509ExtensionCollection extensions = null)
+            X509ExtensionCollection? extensions = null)
         {
             using (IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithm))
             {
@@ -205,10 +203,10 @@ namespace System.Security.Cryptography.Pkcs
         public static Rfc3161TimestampRequest CreateFromHash(
             ReadOnlyMemory<byte> hash,
             HashAlgorithmName hashAlgorithm,
-            Oid requestedPolicyId = null,
+            Oid? requestedPolicyId = null,
             ReadOnlyMemory<byte>? nonce = null,
             bool requestSignerCertificates = false,
-            X509ExtensionCollection extensions = null)
+            X509ExtensionCollection? extensions = null)
         {
             string oidStr = PkcsHelpers.GetOidFromHashAlgorithm(hashAlgorithm);
 
@@ -249,10 +247,10 @@ namespace System.Security.Cryptography.Pkcs
         public static Rfc3161TimestampRequest CreateFromHash(
             ReadOnlyMemory<byte> hash,
             Oid hashAlgorithmId,
-            Oid requestedPolicyId = null,
+            Oid? requestedPolicyId = null,
             ReadOnlyMemory<byte>? nonce = null,
             bool requestSignerCertificates = false,
-            X509ExtensionCollection extensions = null)
+            X509ExtensionCollection? extensions = null)
         {
             // Normalize the nonce:
             if (nonce.HasValue)
@@ -333,7 +331,7 @@ namespace System.Security.Cryptography.Pkcs
 
         public static bool TryDecode(
             ReadOnlyMemory<byte> encodedBytes,
-            out Rfc3161TimestampRequest request,
+            [NotNullWhen(true)] out Rfc3161TimestampRequest? request,
             out int bytesConsumed)
         {
             try
index 0fca6f4..d431a2b 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Linq;
 using System.Security.Cryptography.Asn1;
 using System.Security.Cryptography.Asn1.Pkcs7;
@@ -15,12 +16,12 @@ namespace System.Security.Cryptography.Pkcs
 {
     public sealed class Rfc3161TimestampToken
     {
-        private SignedCms _parsedDocument;
-        private SignerInfo _signerInfo;
+        private SignedCms _parsedDocument = null!; // Initialized by object initializer
+        private SignerInfo? _signerInfo;
         private EssCertId? _essCertId;
         private EssCertIdV2? _essCertIdV2;
 
-        public Rfc3161TimestampTokenInfo TokenInfo { get; private set; }
+        public Rfc3161TimestampTokenInfo TokenInfo { get; private set; } = null!;
 
         private Rfc3161TimestampToken()
         {
@@ -39,10 +40,10 @@ namespace System.Security.Cryptography.Pkcs
         /// </remarks>
         public SignedCms AsSignedCms() => _parsedDocument;
 
-        private X509Certificate2 GetSignerCertificate(X509Certificate2Collection extraCandidates)
+        private X509Certificate2? GetSignerCertificate(X509Certificate2Collection? extraCandidates)
         {
             Debug.Assert(_signerInfo != null, "_signerInfo != null");
-            X509Certificate2 signerCert = _signerInfo.Certificate;
+            X509Certificate2? signerCert = _signerInfo.Certificate;
 
             if (signerCert != null)
             {
@@ -73,12 +74,12 @@ namespace System.Security.Cryptography.Pkcs
 
         public bool VerifySignatureForData(
             ReadOnlySpan<byte> data,
-            out X509Certificate2 signerCertificate,
-            X509Certificate2Collection extraCandidates = null)
+            [NotNullWhen(true)] out X509Certificate2? signerCertificate,
+            X509Certificate2Collection? extraCandidates = null)
         {
             signerCertificate = null;
 
-            X509Certificate2 cert = GetSignerCertificate(extraCandidates);
+            X509Certificate2? cert = GetSignerCertificate(extraCandidates);
 
             if (cert == null)
             {
@@ -98,12 +99,12 @@ namespace System.Security.Cryptography.Pkcs
         public bool VerifySignatureForHash(
             ReadOnlySpan<byte> hash,
             HashAlgorithmName hashAlgorithm,
-            out X509Certificate2 signerCertificate,
-            X509Certificate2Collection extraCandidates = null)
+            [NotNullWhen(true)] out X509Certificate2? signerCertificate,
+            X509Certificate2Collection? extraCandidates = null)
         {
             signerCertificate = null;
 
-            X509Certificate2 cert = GetSignerCertificate(extraCandidates);
+            X509Certificate2? cert = GetSignerCertificate(extraCandidates);
 
             if (cert == null)
             {
@@ -123,8 +124,8 @@ namespace System.Security.Cryptography.Pkcs
         public bool VerifySignatureForHash(
             ReadOnlySpan<byte> hash,
             Oid hashAlgorithmId,
-            out X509Certificate2 signerCertificate,
-            X509Certificate2Collection extraCandidates = null)
+            [NotNullWhen(true)] out X509Certificate2? signerCertificate,
+            X509Certificate2Collection? extraCandidates = null)
         {
             if (hashAlgorithmId == null)
             {
@@ -133,7 +134,7 @@ namespace System.Security.Cryptography.Pkcs
 
             signerCertificate = null;
 
-            X509Certificate2 cert = GetSignerCertificate(extraCandidates);
+            X509Certificate2? cert = GetSignerCertificate(extraCandidates);
 
             if (cert == null)
             {
@@ -156,8 +157,8 @@ namespace System.Security.Cryptography.Pkcs
 
         public bool VerifySignatureForSignerInfo(
             SignerInfo signerInfo,
-            out X509Certificate2 signerCertificate,
-            X509Certificate2Collection extraCandidates = null)
+            [NotNullWhen(true)] out X509Certificate2? signerCertificate,
+            X509Certificate2Collection? extraCandidates = null)
         {
             if (signerInfo == null)
             {
@@ -170,7 +171,7 @@ namespace System.Security.Cryptography.Pkcs
                 extraCandidates);
         }
 
-        internal bool VerifyHash(ReadOnlySpan<byte> hash, string hashAlgorithmId)
+        internal bool VerifyHash(ReadOnlySpan<byte> hash, string? hashAlgorithmId)
         {
             return
                 hash.SequenceEqual(TokenInfo.GetMessageHash().Span) &&
@@ -290,7 +291,7 @@ namespace System.Security.Cryptography.Pkcs
             }
         }
 
-        public static bool TryDecode(ReadOnlyMemory<byte> source, out Rfc3161TimestampToken token, out int bytesConsumed)
+        public static bool TryDecode(ReadOnlyMemory<byte> source, [NotNullWhen(true)] out Rfc3161TimestampToken? token, out int bytesConsumed)
         {
             bytesConsumed = 0;
             token = null;
@@ -361,14 +362,14 @@ namespace System.Security.Cryptography.Pkcs
                     return false;
                 }
 
-                X509Certificate2 signerCert = signer.Certificate;
+                X509Certificate2? signerCert = signer.Certificate;
 
                 if (signerCert == null &&
                     signer.SignerIdentifier.Type == SubjectIdentifierType.IssuerAndSerialNumber)
                 {
                     // If the cert wasn't provided, but the identifier was IssuerAndSerialNumber,
                     // and the ESSCertId(V2) has specified an issuerSerial value, ensure it's a match.
-                    X509IssuerSerial issuerSerial = (X509IssuerSerial)signer.SignerIdentifier.Value;
+                    X509IssuerSerial issuerSerial = (X509IssuerSerial)signer.SignerIdentifier.Value!;
 
                     if (certId.HasValue && certId.Value.IssuerSerial != null)
                     {
@@ -393,9 +394,7 @@ namespace System.Security.Cryptography.Pkcs
                     }
                 }
 
-                Rfc3161TimestampTokenInfo tokenInfo;
-
-                if (Rfc3161TimestampTokenInfo.TryDecode(cms.ContentInfo.Content, out tokenInfo, out _))
+                if (Rfc3161TimestampTokenInfo.TryDecode(cms.ContentInfo.Content, out Rfc3161TimestampTokenInfo? tokenInfo, out _))
                 {
                     if (signerCert != null &&
                         !CheckCertificate(signerCert, signer, in certId, in certId2, tokenInfo))
@@ -481,7 +480,7 @@ namespace System.Security.Cryptography.Pkcs
         {
             Debug.Assert(signerCert != null);
             Debug.Assert(certId.HasValue || certId2.HasValue);
-            byte[] serialNumber = null;
+            byte[]? serialNumber = null;
 
             if (certId.HasValue)
             {
@@ -574,7 +573,7 @@ namespace System.Security.Cryptography.Pkcs
 
             foreach (CryptographicAttributeObject attrSet in signer.SignedAttributes)
             {
-                string setOid = attrSet.Oid?.Value;
+                string? setOid = attrSet.Oid?.Value;
 
                 if (setOid != null &&
                     setOid != Oids.SigningCertificate &&
@@ -585,7 +584,7 @@ namespace System.Security.Cryptography.Pkcs
 
                 foreach (AsnEncodedData attr in attrSet.Values)
                 {
-                    string attrOid = attr.Oid?.Value;
+                    string? attrOid = attr.Oid?.Value;
 
                     if (attrOid == Oids.SigningCertificate)
                     {
index 7b258db..c2e1d89 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Linq;
 using System.Security.Cryptography.Asn1;
 using System.Security.Cryptography.Pkcs.Asn1;
@@ -27,7 +28,7 @@ namespace System.Security.Cryptography.Pkcs
             bool isOrdering = false,
             ReadOnlyMemory<byte>? nonce = null,
             ReadOnlyMemory<byte>? tsaName = null,
-            X509ExtensionCollection extensions = null)
+            X509ExtensionCollection? extensions = null)
         {
             _encodedBytes = Encode(
                 policyId,
@@ -134,12 +135,12 @@ namespace System.Security.Cryptography.Pkcs
 
         public static bool TryDecode(
             ReadOnlyMemory<byte> source,
-            out Rfc3161TimestampTokenInfo timestampTokenInfo,
+            [NotNullWhen(true)] out Rfc3161TimestampTokenInfo? timestampTokenInfo,
             out int bytesConsumed)
         {
-            if (TryDecode(source, false, out Rfc3161TstInfo tstInfo, out bytesConsumed, out byte[] copiedBytes))
+            if (TryDecode(source, false, out Rfc3161TstInfo tstInfo, out bytesConsumed, out byte[]? copiedBytes))
             {
-                timestampTokenInfo = new Rfc3161TimestampTokenInfo(copiedBytes, tstInfo);
+                timestampTokenInfo = new Rfc3161TimestampTokenInfo(copiedBytes!, tstInfo);
                 return true;
             }
 
@@ -153,7 +154,7 @@ namespace System.Security.Cryptography.Pkcs
             bool ownsMemory,
             out Rfc3161TstInfo tstInfo,
             out int bytesConsumed,
-            out byte[] copiedBytes)
+            out byte[]? copiedBytes)
         {
             // https://tools.ietf.org/html/rfc3161#section-2.4.2
             // The eContent SHALL be the DER-encoded value of TSTInfo.
@@ -216,7 +217,7 @@ namespace System.Security.Cryptography.Pkcs
             long? accuracyInMicroseconds,
             ReadOnlyMemory<byte>? nonce,
             ReadOnlyMemory<byte>? tsaName,
-            X509ExtensionCollection extensions)
+            X509ExtensionCollection? extensions)
         {
             if (policyId == null)
                 throw new ArgumentNullException(nameof(policyId));
index 24ed0e5..d7a5e8a 100644 (file)
@@ -34,7 +34,7 @@ namespace System.Security.Cryptography.Pkcs
 
         // Similar to _heldContent, the Windows CMS API held this separate internally,
         // and thus we need to be reslilient against modification.
-        private string _contentType;
+        private string? _contentType;
 
         public int Version { get; private set; }
         public ContentInfo ContentInfo { get; private set; }
@@ -89,6 +89,7 @@ namespace System.Security.Cryptography.Pkcs
 
                 foreach (CertificateChoiceAsn choice in certChoices)
                 {
+                    Debug.Assert(choice.Certificate.HasValue);
                     coll.Add(new X509Certificate2(choice.Certificate.Value.ToArray()));
                 }
 
@@ -236,7 +237,7 @@ namespace System.Security.Cryptography.Pkcs
             // dynamic adapter.
             //
             // See https://tools.ietf.org/html/rfc5652#section-5.2.1
-            byte[] rented = null;
+            byte[]? rented = null;
             int bytesWritten = 0;
             try
             {
@@ -405,6 +406,7 @@ namespace System.Security.Cryptography.Pkcs
 
         internal ReadOnlySpan<byte> GetHashableContentSpan()
         {
+            Debug.Assert(_heldContent.HasValue);
             ReadOnlyMemory<byte> content = _heldContent.Value;
 
             if (!_hasPkcs7Content)
@@ -642,9 +644,9 @@ namespace System.Security.Cryptography.Pkcs
 
             if (existingLength > 0)
             {
-                foreach (CertificateChoiceAsn cert in _signedData.CertificateSet)
+                foreach (CertificateChoiceAsn cert in _signedData.CertificateSet!)
                 {
-                    if (cert.Certificate.Value.Span.SequenceEqual(rawData))
+                    if (cert.Certificate!.Value.Span.SequenceEqual(rawData))
                     {
                         throw new CryptographicException(SR.Cryptography_Cms_CertificateAlreadyInCollection);
                     }
@@ -677,9 +679,9 @@ namespace System.Security.Cryptography.Pkcs
                 int idx = 0;
                 byte[] rawData = certificate.RawData;
 
-                foreach (CertificateChoiceAsn cert in _signedData.CertificateSet)
+                foreach (CertificateChoiceAsn cert in _signedData.CertificateSet!)
                 {
-                    if (cert.Certificate.Value.Span.SequenceEqual(rawData))
+                    if (cert.Certificate!.Value.Span.SequenceEqual(rawData))
                     {
                         PkcsHelpers.RemoveAt(ref _signedData.CertificateSet, idx);
                         Reencode();
index 80030f7..546eea1 100644 (file)
@@ -20,18 +20,18 @@ namespace System.Security.Cryptography.Pkcs
         public SubjectIdentifier SignerIdentifier { get; }
 
         private readonly Oid _digestAlgorithm;
-        private readonly AttributeAsn[] _signedAttributes;
+        private readonly AttributeAsn[]? _signedAttributes;
         private readonly ReadOnlyMemory<byte>? _signedAttributesMemory;
         private readonly Oid _signatureAlgorithm;
         private readonly ReadOnlyMemory<byte>? _signatureAlgorithmParameters;
         private readonly ReadOnlyMemory<byte> _signature;
-        private readonly AttributeAsn[] _unsignedAttributes;
+        private readonly AttributeAsn[]? _unsignedAttributes;
 
         private readonly SignedCms _document;
-        private X509Certificate2 _signerCertificate;
-        private SignerInfo _parentSignerInfo;
-        private CryptographicAttributeObjectCollection _parsedSignedAttrs;
-        private CryptographicAttributeObjectCollection _parsedUnsignedAttrs;
+        private X509Certificate2? _signerCertificate;
+        private SignerInfo? _parentSignerInfo;
+        private CryptographicAttributeObjectCollection? _parsedSignedAttrs;
+        private CryptographicAttributeObjectCollection? _parsedUnsignedAttrs;
 
         internal SignerInfo(ref SignerInfoAsn parsedData, SignedCms ownerDocument)
         {
@@ -87,7 +87,7 @@ namespace System.Security.Cryptography.Pkcs
 
         public byte[] GetSignature() => _signature.ToArray();
 
-        public X509Certificate2 Certificate
+        public X509Certificate2? Certificate
         {
             get
             {
@@ -159,7 +159,7 @@ namespace System.Security.Cryptography.Pkcs
                     throw new CryptographicException(SR.Cryptography_Cms_NoSignerAtIndex);
                 }
 
-                ref AttributeAsn[] unsignedAttrs = ref parentData.UnsignedAttributes;
+                ref AttributeAsn[] unsignedAttrs = ref parentData.UnsignedAttributes!;
 
                 for (int i = 0; i < unsignedAttrs.Length; i++)
                 {
@@ -208,7 +208,7 @@ namespace System.Security.Cryptography.Pkcs
 
         private static void AddUnsignedAttribute(ref SignerInfoAsn mySigner, AsnEncodedData unsignedAttribute)
         {
-            int existingAttribute = mySigner.UnsignedAttributes == null ? -1 : FindAttributeIndexByOid(mySigner.UnsignedAttributes, unsignedAttribute.Oid);
+            int existingAttribute = mySigner.UnsignedAttributes == null ? -1 : FindAttributeIndexByOid(mySigner.UnsignedAttributes, unsignedAttribute.Oid!);
 
             if (existingAttribute == -1)
             {
@@ -232,7 +232,7 @@ namespace System.Security.Cryptography.Pkcs
             else
             {
                 // merge with existing attribute
-                ref AttributeAsn modifiedAttr = ref mySigner.UnsignedAttributes[existingAttribute];
+                ref AttributeAsn modifiedAttr = ref mySigner.UnsignedAttributes![existingAttribute];
                 int newIndex = modifiedAttr.AttrValues.Length;
                 Array.Resize(ref modifiedAttr.AttrValues, newIndex + 1);
                 modifiedAttr.AttrValues[newIndex] = unsignedAttribute.RawData;
@@ -258,11 +258,11 @@ namespace System.Security.Cryptography.Pkcs
 
             if (isOnlyValue)
             {
-                PkcsHelpers.RemoveAt(ref mySigner.UnsignedAttributes, outerIndex);
+                PkcsHelpers.RemoveAt(ref mySigner.UnsignedAttributes!, outerIndex);
             }
             else
             {
-                PkcsHelpers.RemoveAt(ref mySigner.UnsignedAttributes[outerIndex].AttrValues, innerIndex);
+                PkcsHelpers.RemoveAt(ref mySigner.UnsignedAttributes![outerIndex].AttrValues, innerIndex);
             }
         }
 
@@ -468,7 +468,7 @@ namespace System.Security.Cryptography.Pkcs
             if (extraStore == null)
                 throw new ArgumentNullException(nameof(extraStore));
 
-            X509Certificate2 certificate = Certificate;
+            X509Certificate2? certificate = Certificate;
 
             if (certificate == null)
             {
@@ -498,7 +498,7 @@ namespace System.Security.Cryptography.Pkcs
 
         private bool CheckHash(bool compatMode)
         {
-            using (IncrementalHash hasher = PrepareDigest(compatMode))
+            using (IncrementalHash? hasher = PrepareDigest(compatMode))
             {
                 if (hasher == null)
                 {
@@ -511,28 +511,28 @@ namespace System.Security.Cryptography.Pkcs
             }
         }
 
-        private X509Certificate2 FindSignerCertificate()
+        private X509Certificate2? FindSignerCertificate()
         {
             return FindSignerCertificate(SignerIdentifier, _document.Certificates);
         }
 
-        private static X509Certificate2 FindSignerCertificate(
+        private static X509Certificate2? FindSignerCertificate(
             SubjectIdentifier signerIdentifier,
-            X509Certificate2Collection extraStore)
+            X509Certificate2Collection? extraStore)
         {
             if (extraStore == null || extraStore.Count == 0)
             {
                 return null;
             }
 
-            X509Certificate2Collection filtered = null;
-            X509Certificate2 match = null;
+            X509Certificate2Collection? filtered = null;
+            X509Certificate2? match = null;
 
             switch (signerIdentifier.Type)
             {
                 case SubjectIdentifierType.IssuerAndSerialNumber:
                 {
-                    X509IssuerSerial issuerSerial = (X509IssuerSerial)signerIdentifier.Value;
+                    X509IssuerSerial issuerSerial = (X509IssuerSerial)signerIdentifier.Value!;
                     filtered = extraStore.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false);
 
                     foreach (X509Certificate2 cert in filtered)
@@ -573,7 +573,7 @@ namespace System.Security.Cryptography.Pkcs
             return match;
         }
 
-        private IncrementalHash PrepareDigest(bool compatMode)
+        private IncrementalHash? PrepareDigest(bool compatMode)
         {
             HashAlgorithmName hashAlgorithmName = GetDigestAlgorithm();
 
@@ -705,7 +705,7 @@ namespace System.Security.Cryptography.Pkcs
             X509Certificate2 certificate,
             bool verifySignatureOnly)
         {
-            CmsSignature signatureProcessor = CmsSignature.ResolveAndVerifyKeyType(SignatureAlgorithm.Value, key: null);
+            CmsSignature? signatureProcessor = CmsSignature.ResolveAndVerifyKeyType(SignatureAlgorithm.Value!, key: null);
 
             if (signatureProcessor == null)
             {
@@ -741,7 +741,7 @@ namespace System.Security.Cryptography.Pkcs
 
                 foreach (X509Extension ext in certificate.Extensions)
                 {
-                    if (ext.Oid.Value == Oids.KeyUsage)
+                    if (ext.Oid!.Value == Oids.KeyUsage)
                     {
                         if (!(ext is X509KeyUsageExtension keyUsage))
                         {
@@ -763,7 +763,7 @@ namespace System.Security.Cryptography.Pkcs
             X509Certificate2 certificate,
             bool compatMode)
         {
-            using (IncrementalHash hasher = PrepareDigest(compatMode))
+            using (IncrementalHash? hasher = PrepareDigest(compatMode))
             {
                 if (hasher == null)
                 {
@@ -802,10 +802,10 @@ namespace System.Security.Cryptography.Pkcs
 
         private HashAlgorithmName GetDigestAlgorithm()
         {
-            return PkcsHelpers.GetDigestAlgorithm(DigestAlgorithm.Value, forVerification: true);
+            return PkcsHelpers.GetDigestAlgorithm(DigestAlgorithm.Value!, forVerification: true);
         }
 
-        internal static CryptographicAttributeObjectCollection MakeAttributeCollection(AttributeAsn[] attributes)
+        internal static CryptographicAttributeObjectCollection MakeAttributeCollection(AttributeAsn[]? attributes)
         {
             var coll = new CryptographicAttributeObjectCollection();
 
@@ -868,13 +868,13 @@ namespace System.Security.Cryptography.Pkcs
             return -1;
         }
 
-        private static (int, int) FindAttributeLocation(AttributeAsn[] attributes, AsnEncodedData attribute, out bool isOnlyValue)
+        private static (int, int) FindAttributeLocation(AttributeAsn[]? attributes, AsnEncodedData attribute, out bool isOnlyValue)
         {
             if (attributes != null)
             {
                 for (int outerIndex = 0; ; outerIndex++)
                 {
-                    outerIndex = FindAttributeIndexByOid(attributes, attribute.Oid, outerIndex);
+                    outerIndex = FindAttributeIndexByOid(attributes, attribute.Oid!, outerIndex);
 
                     if (outerIndex == -1)
                     {
index d3c483b..8e9c5cf 100644 (file)
@@ -12,8 +12,6 @@ namespace System.Security.Cryptography.Pkcs
         private readonly SignerInfoCollection _signerInfos;
         private int _position;
 
-        private SignerInfoEnumerator() { }
-
         internal SignerInfoEnumerator(SignerInfoCollection signerInfos)
         {
             Debug.Assert(signerInfos != null);
index 9a9affc..2159b73 100644 (file)
@@ -96,7 +96,7 @@ namespace System.Security.Cryptography.Pkcs
         }
 
         public SubjectIdentifierType Type { get; }
-        public object Value { get; }
+        public object? Value { get; }
 
         public bool MatchesCertificate(X509Certificate2 certificate)
         {
@@ -104,7 +104,7 @@ namespace System.Security.Cryptography.Pkcs
             {
                 case SubjectIdentifierType.IssuerAndSerialNumber:
                     {
-                        X509IssuerSerial issuerSerial = (X509IssuerSerial)Value;
+                        X509IssuerSerial issuerSerial = (X509IssuerSerial)Value!;
                         byte[] serialNumber = issuerSerial.SerialNumber.ToSerialBytes();
                         string issuer = issuerSerial.IssuerName;
                         byte[] certSerialNumber = certificate.GetSerialNumber();
@@ -114,7 +114,7 @@ namespace System.Security.Cryptography.Pkcs
 
                 case SubjectIdentifierType.SubjectKeyIdentifier:
                     {
-                        string skiString = (string)Value;
+                        string skiString = (string)Value!;
                         byte[] ski = skiString.ToSkiBytes();
                         byte[] candidateSki = PkcsPal.Instance.GetSubjectKeyIdentifier(certificate);
 
@@ -141,20 +141,20 @@ namespace System.Security.Cryptography.Pkcs
 
             if (Type == SubjectIdentifierType.IssuerAndSerialNumber)
             {
-                issuerSerial = (X509IssuerSerial)Value;
+                issuerSerial = (X509IssuerSerial)Value!;
             }
 
             switch (Type)
             {
                 case SubjectIdentifierType.IssuerAndSerialNumber:
                     {
-                        X509IssuerSerial currentIssuerSerial = (X509IssuerSerial)currentId.Value;
+                        X509IssuerSerial currentIssuerSerial = (X509IssuerSerial)currentId.Value!;
 
                         return currentIssuerSerial.IssuerName == issuerSerial.IssuerName &&
                             currentIssuerSerial.SerialNumber == issuerSerial.SerialNumber;
                     }
                 case SubjectIdentifierType.SubjectKeyIdentifier:
-                    return (string)Value == (string)currentId.Value;
+                    return (string)Value! == (string)currentId.Value!;
                 case SubjectIdentifierType.NoSignature:
                     return true;
                 default: