diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ConvertToLibraryImportFixer.cs b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ConvertToLibraryImportFixer.cs index 9ebbb56a339f21..4fdedd095bed8d 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ConvertToLibraryImportFixer.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ConvertToLibraryImportFixer.cs @@ -74,7 +74,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) context.Diagnostics); if (!bool.Parse(diagnostic.Properties[ConvertToLibraryImportAnalyzer.ExactSpelling])) { - CharSet charSet = (CharSet)Enum.Parse(typeof(CharSet), diagnostic.Properties[ConvertToLibraryImportAnalyzer.CharSet]); + CharSet charSet = (CharSet)Enum.Parse(typeof(CharSet), diagnostic.Properties[ConvertToLibraryImportAnalyzer.CharSet]!); // CharSet.Auto traditionally maps to either an A or W suffix // depending on the default CharSet of the platform. // We will offer both suffix options when CharSet.Auto is provided diff --git a/src/libraries/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.cs b/src/libraries/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.cs index 2ee83409bebac3..d53d23b1c55c11 100644 --- a/src/libraries/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.cs @@ -11,8 +11,10 @@ public sealed partial class CipherData public CipherData() { } public CipherData(byte[] cipherValue) { } public CipherData(System.Security.Cryptography.Xml.CipherReference cipherReference) { } - public System.Security.Cryptography.Xml.CipherReference CipherReference { get { throw null; } set { } } - public byte[] CipherValue { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.DisallowNullAttribute] + public System.Security.Cryptography.Xml.CipherReference? CipherReference { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.DisallowNullAttribute] + public byte[]? CipherValue { get { throw null; } set { } } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } } @@ -29,9 +31,9 @@ public partial class DataObject public DataObject() { } public DataObject(string id, string mimeType, string encoding, System.Xml.XmlElement data) { } public System.Xml.XmlNodeList Data { get { throw null; } set { } } - public string Encoding { get { throw null; } set { } } - public string Id { get { throw null; } set { } } - public string MimeType { get { throw null; } set { } } + public string? Encoding { get { throw null; } set { } } + public string? Id { get { throw null; } set { } } + public string? MimeType { get { throw null; } set { } } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } } @@ -60,7 +62,8 @@ public override void LoadXml(System.Xml.XmlElement value) { } public sealed partial class EncryptedKey : System.Security.Cryptography.Xml.EncryptedType { public EncryptedKey() { } - public string CarriedKeyName { get { throw null; } set { } } + public string? CarriedKeyName { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNullAttribute] public string Recipient { get { throw null; } set { } } public System.Security.Cryptography.Xml.ReferenceList ReferenceList { get { throw null; } } public void AddReference(System.Security.Cryptography.Xml.DataReference dataReference) { } @@ -74,7 +77,7 @@ protected EncryptedReference() { } protected EncryptedReference(string uri) { } protected EncryptedReference(string uri, System.Security.Cryptography.Xml.TransformChain transformChain) { } protected internal bool CacheValid { get { throw null; } } - protected string ReferenceType { get { throw null; } set { } } + protected string? ReferenceType { get { throw null; } set { } } public System.Security.Cryptography.Xml.TransformChain TransformChain { get { throw null; } set { } } public string Uri { get { throw null; } set { } } public void AddTransform(System.Security.Cryptography.Xml.Transform transform) { } @@ -85,13 +88,14 @@ public abstract partial class EncryptedType { protected EncryptedType() { } public virtual System.Security.Cryptography.Xml.CipherData CipherData { get { throw null; } set { } } - public virtual string Encoding { get { throw null; } set { } } - public virtual System.Security.Cryptography.Xml.EncryptionMethod EncryptionMethod { get { throw null; } set { } } + public virtual string? Encoding { get { throw null; } set { } } + public virtual System.Security.Cryptography.Xml.EncryptionMethod? EncryptionMethod { get { throw null; } set { } } public virtual System.Security.Cryptography.Xml.EncryptionPropertyCollection EncryptionProperties { get { throw null; } } - public virtual string Id { get { throw null; } set { } } + public virtual string? Id { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNullAttribute] public System.Security.Cryptography.Xml.KeyInfo KeyInfo { get { throw null; } set { } } - public virtual string MimeType { get { throw null; } set { } } - public virtual string Type { get { throw null; } set { } } + public virtual string? MimeType { get { throw null; } set { } } + public virtual string? Type { get { throw null; } set { } } public void AddProperty(System.Security.Cryptography.Xml.EncryptionProperty ep) { } public abstract System.Xml.XmlElement GetXml(); public abstract void LoadXml(System.Xml.XmlElement value); @@ -117,19 +121,20 @@ public partial class EncryptedXml public const string XmlEncTripleDESUrl = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"; public EncryptedXml() { } public EncryptedXml(System.Xml.XmlDocument document) { } - public EncryptedXml(System.Xml.XmlDocument document, System.Security.Policy.Evidence evidence) { } - public System.Security.Policy.Evidence DocumentEvidence { get { throw null; } set { } } + public EncryptedXml(System.Xml.XmlDocument document, System.Security.Policy.Evidence? evidence) { } + public System.Security.Policy.Evidence? DocumentEvidence { get { throw null; } set { } } public System.Text.Encoding Encoding { get { throw null; } set { } } public System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } } public System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.AllowNullAttribute] public string Recipient { get { throw null; } set { } } - public System.Xml.XmlResolver Resolver { get { throw null; } set { } } + public System.Xml.XmlResolver? Resolver { get { throw null; } set { } } public int XmlDSigSearchDepth { get { throw null; } set { } } public void AddKeyNameMapping(string keyName, object keyObject) { } public void ClearKeyNameMappings() { } public byte[] DecryptData(System.Security.Cryptography.Xml.EncryptedData encryptedData, System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm) { throw null; } public void DecryptDocument() { } - public virtual byte[] DecryptEncryptedKey(System.Security.Cryptography.Xml.EncryptedKey encryptedKey) { throw null; } + public virtual byte[]? DecryptEncryptedKey(System.Security.Cryptography.Xml.EncryptedKey encryptedKey) { throw null; } public static byte[] DecryptKey(byte[] keyData, System.Security.Cryptography.RSA rsa, bool useOAEP) { throw null; } public static byte[] DecryptKey(byte[] keyData, System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm) { throw null; } public System.Security.Cryptography.Xml.EncryptedData Encrypt(System.Xml.XmlElement inputElement, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { throw null; } @@ -138,17 +143,17 @@ public void DecryptDocument() { } public byte[] EncryptData(System.Xml.XmlElement inputElement, System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm, bool content) { throw null; } public static byte[] EncryptKey(byte[] keyData, System.Security.Cryptography.RSA rsa, bool useOAEP) { throw null; } public static byte[] EncryptKey(byte[] keyData, System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm) { throw null; } - public virtual byte[] GetDecryptionIV(System.Security.Cryptography.Xml.EncryptedData encryptedData, string symmetricAlgorithmUri) { throw null; } - public virtual System.Security.Cryptography.SymmetricAlgorithm GetDecryptionKey(System.Security.Cryptography.Xml.EncryptedData encryptedData, string symmetricAlgorithmUri) { throw null; } - public virtual System.Xml.XmlElement GetIdElement(System.Xml.XmlDocument document, string idValue) { throw null; } + public virtual byte[] GetDecryptionIV(System.Security.Cryptography.Xml.EncryptedData encryptedData, string? symmetricAlgorithmUri) { throw null; } + public virtual System.Security.Cryptography.SymmetricAlgorithm? GetDecryptionKey(System.Security.Cryptography.Xml.EncryptedData encryptedData, string? symmetricAlgorithmUri) { throw null; } + public virtual System.Xml.XmlElement? GetIdElement(System.Xml.XmlDocument document, string idValue) { throw null; } public void ReplaceData(System.Xml.XmlElement inputElement, byte[] decryptedData) { } public static void ReplaceElement(System.Xml.XmlElement inputElement, System.Security.Cryptography.Xml.EncryptedData encryptedData, bool content) { } } public partial class EncryptionMethod { public EncryptionMethod() { } - public EncryptionMethod(string algorithm) { } - public string KeyAlgorithm { get { throw null; } set { } } + public EncryptionMethod(string? algorithm) { } + public string? KeyAlgorithm { get { throw null; } set { } } public int KeySize { get { throw null; } set { } } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } @@ -157,9 +162,10 @@ public sealed partial class EncryptionProperty { public EncryptionProperty() { } public EncryptionProperty(System.Xml.XmlElement elementProperty) { } - public string Id { get { throw null; } } - public System.Xml.XmlElement PropertyElement { get { throw null; } set { } } - public string Target { get { throw null; } } + public string? Id { get { throw null; } } + [System.Diagnostics.CodeAnalysis.DisallowNullAttribute] + public System.Xml.XmlElement? PropertyElement { get { throw null; } set { } } + public string? Target { get { throw null; } } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } } @@ -173,7 +179,7 @@ public EncryptionPropertyCollection() { } [System.Runtime.CompilerServices.IndexerName("ItemOf")] public System.Security.Cryptography.Xml.EncryptionProperty this[int index] { get { throw null; } set { } } public object SyncRoot { get { throw null; } } - object System.Collections.IList.this[int index] { get { throw null; } set { } } + object? System.Collections.IList.this[int index] { get { throw null; } set { } } public int Add(System.Security.Cryptography.Xml.EncryptionProperty value) { throw null; } public void Clear() { } public bool Contains(System.Security.Cryptography.Xml.EncryptionProperty value) { throw null; } @@ -185,11 +191,11 @@ public void Insert(int index, System.Security.Cryptography.Xml.EncryptionPropert public System.Security.Cryptography.Xml.EncryptionProperty Item(int index) { throw null; } public void Remove(System.Security.Cryptography.Xml.EncryptionProperty value) { } public void RemoveAt(int index) { } - int System.Collections.IList.Add(object value) { throw null; } - bool System.Collections.IList.Contains(object value) { throw null; } - int System.Collections.IList.IndexOf(object value) { throw null; } - void System.Collections.IList.Insert(int index, object value) { } - void System.Collections.IList.Remove(object value) { } + int System.Collections.IList.Add(object? value) { throw null; } + bool System.Collections.IList.Contains(object? value) { throw null; } + int System.Collections.IList.IndexOf(object? value) { throw null; } + void System.Collections.IList.Insert(int index, object? value) { } + void System.Collections.IList.Remove(object? value) { } } public partial interface IRelDecryptor { @@ -199,7 +205,7 @@ public partial class KeyInfo : System.Collections.IEnumerable { public KeyInfo() { } public int Count { get { throw null; } } - public string Id { get { throw null; } set { } } + public string? Id { get { throw null; } set { } } public void AddClause(System.Security.Cryptography.Xml.KeyInfoClause clause) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } public System.Collections.IEnumerator GetEnumerator(System.Type requestedObjectType) { throw null; } @@ -216,15 +222,15 @@ public partial class KeyInfoEncryptedKey : System.Security.Cryptography.Xml.KeyI { public KeyInfoEncryptedKey() { } public KeyInfoEncryptedKey(System.Security.Cryptography.Xml.EncryptedKey encryptedKey) { } - public System.Security.Cryptography.Xml.EncryptedKey EncryptedKey { get { throw null; } set { } } + public System.Security.Cryptography.Xml.EncryptedKey? EncryptedKey { get { throw null; } set { } } public override System.Xml.XmlElement GetXml() { throw null; } public override void LoadXml(System.Xml.XmlElement value) { } } public partial class KeyInfoName : System.Security.Cryptography.Xml.KeyInfoClause { public KeyInfoName() { } - public KeyInfoName(string keyName) { } - public string Value { get { throw null; } set { } } + public KeyInfoName(string? keyName) { } + public string? Value { get { throw null; } set { } } public override System.Xml.XmlElement GetXml() { throw null; } public override void LoadXml(System.Xml.XmlElement value) { } } @@ -232,17 +238,17 @@ public partial class KeyInfoNode : System.Security.Cryptography.Xml.KeyInfoClaus { public KeyInfoNode() { } public KeyInfoNode(System.Xml.XmlElement node) { } - public System.Xml.XmlElement Value { get { throw null; } set { } } + public System.Xml.XmlElement? Value { get { throw null; } set { } } public override System.Xml.XmlElement GetXml() { throw null; } public override void LoadXml(System.Xml.XmlElement value) { } } public partial class KeyInfoRetrievalMethod : System.Security.Cryptography.Xml.KeyInfoClause { public KeyInfoRetrievalMethod() { } - public KeyInfoRetrievalMethod(string strUri) { } + public KeyInfoRetrievalMethod(string? strUri) { } public KeyInfoRetrievalMethod(string strUri, string typeName) { } - public string Type { get { throw null; } set { } } - public string Uri { get { throw null; } set { } } + public string? Type { get { throw null; } set { } } + public string? Uri { get { throw null; } set { } } public override System.Xml.XmlElement GetXml() { throw null; } public override void LoadXml(System.Xml.XmlElement value) { } } @@ -252,11 +258,11 @@ public KeyInfoX509Data() { } public KeyInfoX509Data(byte[] rgbCert) { } public KeyInfoX509Data(System.Security.Cryptography.X509Certificates.X509Certificate cert) { } public KeyInfoX509Data(System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Security.Cryptography.X509Certificates.X509IncludeOption includeOption) { } - public System.Collections.ArrayList Certificates { get { throw null; } } - public byte[] CRL { get { throw null; } set { } } - public System.Collections.ArrayList IssuerSerials { get { throw null; } } - public System.Collections.ArrayList SubjectKeyIds { get { throw null; } } - public System.Collections.ArrayList SubjectNames { get { throw null; } } + public System.Collections.ArrayList? Certificates { get { throw null; } } + public byte[]? CRL { get { throw null; } set { } } + public System.Collections.ArrayList? IssuerSerials { get { throw null; } } + public System.Collections.ArrayList? SubjectKeyIds { get { throw null; } } + public System.Collections.ArrayList? SubjectNames { get { throw null; } } public void AddCertificate(System.Security.Cryptography.X509Certificates.X509Certificate certificate) { } public void AddIssuerSerial(string issuerName, string serialNumber) { } public void AddSubjectKeyId(byte[] subjectKeyId) { } @@ -275,13 +281,13 @@ public partial class Reference { public Reference() { } public Reference(System.IO.Stream stream) { } - public Reference(string uri) { } + public Reference(string? uri) { } public string DigestMethod { get { throw null; } set { } } - public byte[] DigestValue { get { throw null; } set { } } - public string Id { get { throw null; } set { } } + public byte[]? DigestValue { get { throw null; } set { } } + public string? Id { get { throw null; } set { } } public System.Security.Cryptography.Xml.TransformChain TransformChain { get { throw null; } set { } } - public string Type { get { throw null; } set { } } - public string Uri { get { throw null; } set { } } + public string? Type { get { throw null; } set { } } + public string? Uri { get { throw null; } set { } } public void AddTransform(System.Security.Cryptography.Xml.Transform transform) { } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } @@ -296,16 +302,16 @@ public ReferenceList() { } public object SyncRoot { get { throw null; } } bool System.Collections.IList.IsFixedSize { get { throw null; } } bool System.Collections.IList.IsReadOnly { get { throw null; } } - object System.Collections.IList.this[int index] { get { throw null; } set { } } - public int Add(object value) { throw null; } + object? System.Collections.IList.this[int index] { get { throw null; } set { } } + public int Add(object? value) { throw null; } public void Clear() { } - public bool Contains(object value) { throw null; } + public bool Contains(object? value) { throw null; } public void CopyTo(System.Array array, int index) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } - public int IndexOf(object value) { throw null; } - public void Insert(int index, object value) { } - public System.Security.Cryptography.Xml.EncryptedReference Item(int index) { throw null; } - public void Remove(object value) { } + public int IndexOf(object? value) { throw null; } + public void Insert(int index, object? value) { } + public System.Security.Cryptography.Xml.EncryptedReference? Item(int index) { throw null; } + public void Remove(object? value) { } public void RemoveAt(int index) { } } public partial class RSAKeyValue : System.Security.Cryptography.Xml.KeyInfoClause @@ -319,11 +325,11 @@ public override void LoadXml(System.Xml.XmlElement value) { } public partial class Signature { public Signature() { } - public string Id { get { throw null; } set { } } + public string? Id { get { throw null; } set { } } public System.Security.Cryptography.Xml.KeyInfo KeyInfo { get { throw null; } set { } } public System.Collections.IList ObjectList { get { throw null; } set { } } - public byte[] SignatureValue { get { throw null; } set { } } - public System.Security.Cryptography.Xml.SignedInfo SignedInfo { get { throw null; } set { } } + public byte[]? SignatureValue { get { throw null; } set { } } + public System.Security.Cryptography.Xml.SignedInfo? SignedInfo { get { throw null; } set { } } public void AddObject(System.Security.Cryptography.Xml.DataObject dataObject) { } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } @@ -331,15 +337,16 @@ public void LoadXml(System.Xml.XmlElement value) { } public partial class SignedInfo : System.Collections.ICollection, System.Collections.IEnumerable { public SignedInfo() { } + [System.Diagnostics.CodeAnalysis.AllowNullAttribute] public string CanonicalizationMethod { get { throw null; } set { } } public System.Security.Cryptography.Xml.Transform CanonicalizationMethodObject { get { throw null; } } public int Count { get { throw null; } } - public string Id { get { throw null; } set { } } + public string? Id { get { throw null; } set { } } public bool IsReadOnly { get { throw null; } } public bool IsSynchronized { get { throw null; } } public System.Collections.ArrayList References { get { throw null; } } - public string SignatureLength { get { throw null; } set { } } - public string SignatureMethod { get { throw null; } set { } } + public string? SignatureLength { get { throw null; } set { } } + public string? SignatureMethod { get { throw null; } set { } } public object SyncRoot { get { throw null; } } public void AddReference(System.Security.Cryptography.Xml.Reference reference) { } public void CopyTo(System.Array array, int index) { } @@ -350,7 +357,7 @@ public void LoadXml(System.Xml.XmlElement value) { } public partial class SignedXml { protected System.Security.Cryptography.Xml.Signature m_signature; - protected string m_strSigningKeyName; + protected string? m_strSigningKeyName; public const string XmlDecryptionTransformUrl = "http://www.w3.org/2002/07/decrypt#XML"; public const string XmlDsigBase64TransformUrl = "http://www.w3.org/2000/09/xmldsig#base64"; public const string XmlDsigC14NTransformUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; @@ -378,43 +385,44 @@ public partial class SignedXml public SignedXml() { } public SignedXml(System.Xml.XmlDocument document) { } public SignedXml(System.Xml.XmlElement elem) { } + [System.Diagnostics.CodeAnalysis.AllowNullAttribute] public System.Security.Cryptography.Xml.EncryptedXml EncryptedXml { get { throw null; } set { } } public System.Security.Cryptography.Xml.KeyInfo KeyInfo { get { throw null; } set { } } public System.Xml.XmlResolver Resolver { set { } } public System.Collections.ObjectModel.Collection SafeCanonicalizationMethods { get { throw null; } } public System.Security.Cryptography.Xml.Signature Signature { get { throw null; } } public System.Func SignatureFormatValidator { get { throw null; } set { } } - public string SignatureLength { get { throw null; } } - public string SignatureMethod { get { throw null; } } - public byte[] SignatureValue { get { throw null; } } - public System.Security.Cryptography.Xml.SignedInfo SignedInfo { get { throw null; } } - public System.Security.Cryptography.AsymmetricAlgorithm SigningKey { get { throw null; } set { } } - public string SigningKeyName { get { throw null; } set { } } + public string? SignatureLength { get { throw null; } } + public string? SignatureMethod { get { throw null; } } + public byte[]? SignatureValue { get { throw null; } } + public System.Security.Cryptography.Xml.SignedInfo? SignedInfo { get { throw null; } } + public System.Security.Cryptography.AsymmetricAlgorithm? SigningKey { get { throw null; } set { } } + public string? SigningKeyName { get { throw null; } set { } } public void AddObject(System.Security.Cryptography.Xml.DataObject dataObject) { } public void AddReference(System.Security.Cryptography.Xml.Reference reference) { } public bool CheckSignature() { throw null; } public bool CheckSignature(System.Security.Cryptography.AsymmetricAlgorithm key) { throw null; } public bool CheckSignature(System.Security.Cryptography.KeyedHashAlgorithm macAlg) { throw null; } public bool CheckSignature(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, bool verifySignatureOnly) { throw null; } - public bool CheckSignatureReturningKey(out System.Security.Cryptography.AsymmetricAlgorithm signingKey) { throw null; } + public bool CheckSignatureReturningKey(out System.Security.Cryptography.AsymmetricAlgorithm? signingKey) { throw null; } public void ComputeSignature() { } public void ComputeSignature(System.Security.Cryptography.KeyedHashAlgorithm macAlg) { } - public virtual System.Xml.XmlElement GetIdElement(System.Xml.XmlDocument document, string idValue) { throw null; } - protected virtual System.Security.Cryptography.AsymmetricAlgorithm GetPublicKey() { throw null; } + public virtual System.Xml.XmlElement? GetIdElement(System.Xml.XmlDocument? document, string idValue) { throw null; } + protected virtual System.Security.Cryptography.AsymmetricAlgorithm? GetPublicKey() { throw null; } public System.Xml.XmlElement GetXml() { throw null; } public void LoadXml(System.Xml.XmlElement value) { } } public abstract partial class Transform { protected Transform() { } - public string Algorithm { get { throw null; } set { } } - public System.Xml.XmlElement Context { get { throw null; } set { } } + public string? Algorithm { get { throw null; } set { } } + public System.Xml.XmlElement? Context { get { throw null; } set { } } public abstract System.Type[] InputTypes { get; } public abstract System.Type[] OutputTypes { get; } public System.Collections.Hashtable PropagatedNamespaces { get { throw null; } } - public System.Xml.XmlResolver Resolver { set { } } + public System.Xml.XmlResolver? Resolver { set { } } public virtual byte[] GetDigestedOutput(System.Security.Cryptography.HashAlgorithm hash) { throw null; } - protected abstract System.Xml.XmlNodeList GetInnerXml(); + protected abstract System.Xml.XmlNodeList? GetInnerXml(); public abstract object GetOutput(); public abstract object GetOutput(System.Type type); public System.Xml.XmlElement GetXml() { throw null; } @@ -436,10 +444,10 @@ public XmlDecryptionTransform() { } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } public void AddExceptUri(string uri) { } - protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } + protected override System.Xml.XmlNodeList? GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } - protected virtual bool IsTargetElement(System.Xml.XmlElement inputElement, string idValue) { throw null; } + protected virtual bool IsTargetElement(System.Xml.XmlElement? inputElement, string idValue) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } public override void LoadInput(object obj) { } } @@ -448,7 +456,7 @@ public partial class XmlDsigBase64Transform : System.Security.Cryptography.Xml.T public XmlDsigBase64Transform() { } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } - protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } + protected override System.Xml.XmlNodeList? GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } @@ -461,7 +469,7 @@ public XmlDsigC14NTransform(bool includeComments) { } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } public override byte[] GetDigestedOutput(System.Security.Cryptography.HashAlgorithm hash) { throw null; } - protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } + protected override System.Xml.XmlNodeList? GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } @@ -477,7 +485,7 @@ public XmlDsigEnvelopedSignatureTransform() { } public XmlDsigEnvelopedSignatureTransform(bool includeComments) { } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } - protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } + protected override System.Xml.XmlNodeList? GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } @@ -487,13 +495,13 @@ public partial class XmlDsigExcC14NTransform : System.Security.Cryptography.Xml. { public XmlDsigExcC14NTransform() { } public XmlDsigExcC14NTransform(bool includeComments) { } - public XmlDsigExcC14NTransform(bool includeComments, string inclusiveNamespacesPrefixList) { } + public XmlDsigExcC14NTransform(bool includeComments, string? inclusiveNamespacesPrefixList) { } public XmlDsigExcC14NTransform(string inclusiveNamespacesPrefixList) { } - public string InclusiveNamespacesPrefixList { get { throw null; } set { } } + public string? InclusiveNamespacesPrefixList { get { throw null; } set { } } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } public override byte[] GetDigestedOutput(System.Security.Cryptography.HashAlgorithm hash) { throw null; } - protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } + protected override System.Xml.XmlNodeList? GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } @@ -509,7 +517,7 @@ public partial class XmlDsigXPathTransform : System.Security.Cryptography.Xml.Tr public XmlDsigXPathTransform() { } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } - protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } + protected override System.Xml.XmlNodeList? GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } @@ -521,7 +529,7 @@ public XmlDsigXsltTransform() { } public XmlDsigXsltTransform(bool includeComments) { } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } - protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } + protected override System.Xml.XmlNodeList? GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } @@ -530,10 +538,10 @@ public override void LoadInput(object obj) { } public partial class XmlLicenseTransform : System.Security.Cryptography.Xml.Transform { public XmlLicenseTransform() { } - public System.Security.Cryptography.Xml.IRelDecryptor Decryptor { get { throw null; } set { } } + public System.Security.Cryptography.Xml.IRelDecryptor? Decryptor { get { throw null; } set { } } public override System.Type[] InputTypes { get { throw null; } } public override System.Type[] OutputTypes { get { throw null; } } - protected override System.Xml.XmlNodeList GetInnerXml() { throw null; } + protected override System.Xml.XmlNodeList? GetInnerXml() { throw null; } public override object GetOutput() { throw null; } public override object GetOutput(System.Type type) { throw null; } public override void LoadInnerXml(System.Xml.XmlNodeList nodeList) { } diff --git a/src/libraries/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.csproj b/src/libraries/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.csproj index 9f5143a0efab8a..8e8a1142412243 100644 --- a/src/libraries/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.csproj +++ b/src/libraries/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.csproj @@ -1,7 +1,7 @@ $(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum) - disable + enable diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System.Security.Cryptography.Xml.csproj b/src/libraries/System.Security.Cryptography.Xml/src/System.Security.Cryptography.Xml.csproj index 20a3d77a4641f7..8694a0575e8b75 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System.Security.Cryptography.Xml.csproj +++ b/src/libraries/System.Security.Cryptography.Xml/src/System.Security.Cryptography.Xml.csproj @@ -2,8 +2,6 @@ $(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum) true - disable - $(NoWarn);nullable $(NoWarn);CA1850 true Provides classes to support the creation and validation of XML digital signatures. The classes in this namespace implement the World Wide Web Consortium Recommendation, "XML-Signature Syntax and Processing", described at http://www.w3.org/TR/xmldsig-core/. diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AncestralNamespaceContextManager.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AncestralNamespaceContextManager.cs index 0bbafb6db14ca1..54341e375e07e6 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AncestralNamespaceContextManager.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AncestralNamespaceContextManager.cs @@ -12,7 +12,7 @@ internal abstract class AncestralNamespaceContextManager internal NamespaceFrame GetScopeAt(int i) { - return (NamespaceFrame)_ancestorStack[i]; + return (NamespaceFrame)_ancestorStack[i]!; } internal NamespaceFrame GetCurrentScope() @@ -20,9 +20,9 @@ internal NamespaceFrame GetCurrentScope() return GetScopeAt(_ancestorStack.Count - 1); } - protected XmlAttribute GetNearestRenderedNamespaceWithMatchingPrefix(string nsPrefix, out int depth) + protected XmlAttribute? GetNearestRenderedNamespaceWithMatchingPrefix(string nsPrefix, out int depth) { - XmlAttribute attr; + XmlAttribute? attr; depth = -1; for (int i = _ancestorStack.Count - 1; i >= 0; i--) { @@ -35,9 +35,9 @@ protected XmlAttribute GetNearestRenderedNamespaceWithMatchingPrefix(string nsPr return null; } - protected XmlAttribute GetNearestUnrenderedNamespaceWithMatchingPrefix(string nsPrefix, out int depth) + protected XmlAttribute? GetNearestUnrenderedNamespaceWithMatchingPrefix(string nsPrefix, out int depth) { - XmlAttribute attr; + XmlAttribute? attr; depth = -1; for (int i = _ancestorStack.Count - 1; i >= 0; i--) { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AttributeSortOrder.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AttributeSortOrder.cs index c0ff1120f8b181..ece8cfb89fa20e 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AttributeSortOrder.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AttributeSortOrder.cs @@ -11,10 +11,10 @@ internal sealed class AttributeSortOrder : IComparer { internal AttributeSortOrder() { } - public int Compare(object a, object b) + public int Compare(object? a, object? b) { - XmlNode nodeA = a as XmlNode; - XmlNode nodeB = b as XmlNode; + XmlNode? nodeA = a as XmlNode; + XmlNode? nodeB = b as XmlNode; if ((nodeA == null) || (nodeB == null)) throw new ArgumentException(); int namespaceCompare = string.CompareOrdinal(nodeA.NamespaceURI, nodeB.NamespaceURI); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/C14NAncestralNamespaceContextManager.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/C14NAncestralNamespaceContextManager.cs index 8dcde4c2298d3a..5365bae76f58a8 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/C14NAncestralNamespaceContextManager.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/C14NAncestralNamespaceContextManager.cs @@ -26,8 +26,8 @@ private void GetNamespaceToRender(string nsPrefix, SortedList attrListToRender, } int rDepth; - XmlAttribute local = (XmlAttribute)nsLocallyDeclared[nsPrefix]; - XmlAttribute rAncestral = GetNearestRenderedNamespaceWithMatchingPrefix(nsPrefix, out rDepth); + XmlAttribute? local = (XmlAttribute?)nsLocallyDeclared[nsPrefix]; + XmlAttribute? rAncestral = GetNearestRenderedNamespaceWithMatchingPrefix(nsPrefix, out rDepth); if (local != null) { if (Utils.IsNonRedundantNamespaceDecl(local, rAncestral)) @@ -42,7 +42,7 @@ private void GetNamespaceToRender(string nsPrefix, SortedList attrListToRender, else { int uDepth; - XmlAttribute uAncestral = GetNearestUnrenderedNamespaceWithMatchingPrefix(nsPrefix, out uDepth); + XmlAttribute? uAncestral = GetNearestUnrenderedNamespaceWithMatchingPrefix(nsPrefix, out uDepth); if (uAncestral != null && uDepth > rDepth && Utils.IsNonRedundantNamespaceDecl(uAncestral, rAncestral)) { if (Utils.IsXmlNamespaceNode(uAncestral)) @@ -55,14 +55,14 @@ private void GetNamespaceToRender(string nsPrefix, SortedList attrListToRender, internal override void GetNamespacesToRender(XmlElement element, SortedList attrListToRender, SortedList nsListToRender, Hashtable nsLocallyDeclared) { - XmlAttribute attrib; + XmlAttribute? attrib; object[] attrs = new object[nsLocallyDeclared.Count]; nsLocallyDeclared.Values.CopyTo(attrs, 0); foreach (object a in attrs) { attrib = (XmlAttribute)a; int rDepth; - XmlAttribute rAncestral = GetNearestRenderedNamespaceWithMatchingPrefix(Utils.GetNamespacePrefix(attrib), out rDepth); + XmlAttribute? rAncestral = GetNearestRenderedNamespaceWithMatchingPrefix(Utils.GetNamespacePrefix(attrib), out rDepth); if (Utils.IsNonRedundantNamespaceDecl(attrib, rAncestral)) { nsLocallyDeclared.Remove(Utils.GetNamespacePrefix(attrib)); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs index a42e1b1770307d..2de2731895c4a5 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs @@ -17,7 +17,7 @@ internal sealed class CanonicalXml // private static string defaultXPathWithComments = "(//. | //@* | //namespace::*)"; // private static string defaultXPathWithComments = "(//. | //@* | //namespace::*)"; - internal CanonicalXml(Stream inputStream, bool includeComments, XmlResolver resolver, string strBaseUri) + internal CanonicalXml(Stream inputStream, bool includeComments, XmlResolver? resolver, string strBaseUri) { if (inputStream is null) { @@ -30,8 +30,8 @@ internal CanonicalXml(Stream inputStream, bool includeComments, XmlResolver reso _ancMgr = new C14NAncestralNamespaceContextManager(); } - internal CanonicalXml(XmlDocument document, XmlResolver resolver) : this(document, resolver, false) { } - internal CanonicalXml(XmlDocument document, XmlResolver resolver, bool includeComments) + internal CanonicalXml(XmlDocument document, XmlResolver? resolver) : this(document, resolver, false) { } + internal CanonicalXml(XmlDocument document, XmlResolver? resolver, bool includeComments) { if (document is null) { @@ -44,14 +44,14 @@ internal CanonicalXml(XmlDocument document, XmlResolver resolver, bool includeCo _ancMgr = new C14NAncestralNamespaceContextManager(); } - internal CanonicalXml(XmlNodeList nodeList, XmlResolver resolver, bool includeComments) + internal CanonicalXml(XmlNodeList nodeList, XmlResolver? resolver, bool includeComments) { if (nodeList is null) { throw new ArgumentNullException(nameof(nodeList)); } - XmlDocument doc = Utils.GetOwnerDocument(nodeList); + XmlDocument? doc = Utils.GetOwnerDocument(nodeList); if (doc == null) throw new ArgumentException(nameof(nodeList)); @@ -79,8 +79,8 @@ private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument do { - XmlNode currentNode = (XmlNode)elementList[index]; - XmlNode currentNodeCanonical = (XmlNode)elementListCanonical[index]; + XmlNode currentNode = (XmlNode)elementList[index]!; + XmlNode currentNodeCanonical = (XmlNode)elementListCanonical[index]!; XmlNodeList childNodes = currentNode.ChildNodes; XmlNodeList childNodesCanonical = currentNodeCanonical.ChildNodes; for (int i = 0; i < childNodes.Count; i++) @@ -90,17 +90,17 @@ private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument if (Utils.NodeInList(childNodes[i], nodeList)) { - MarkNodeAsIncluded(childNodesCanonical[i]); + MarkNodeAsIncluded(childNodesCanonical[i]!); } - XmlAttributeCollection attribNodes = childNodes[i].Attributes; + XmlAttributeCollection? attribNodes = childNodes[i]!.Attributes; if (attribNodes != null) { for (int j = 0; j < attribNodes.Count; j++) { if (Utils.NodeInList(attribNodes[j], nodeList)) { - MarkNodeAsIncluded(childNodesCanonical[i].Attributes.Item(j)); + MarkNodeAsIncluded(childNodesCanonical[i]!.Attributes!.Item(j)!); } } } @@ -121,7 +121,7 @@ internal byte[] GetDigestedBytes(HashAlgorithm hash) { _c14nDoc.WriteHash(hash, DocPosition.BeforeRootElement, _ancMgr); hash.TransformFinalBlock(Array.Empty(), 0, 0); - byte[] res = (byte[])hash.Hash.Clone(); + byte[] res = (byte[])hash.Hash!.Clone(); // reinitialize the hash so it is still usable after the call hash.Initialize(); return res; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlAttribute.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlAttribute.cs index 761fc37439adf5..c845f1fbd4e857 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlAttribute.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlAttribute.cs @@ -11,7 +11,7 @@ internal sealed class CanonicalXmlAttribute : XmlAttribute, ICanonicalizableNode { private bool _isInNodeSet; - public CanonicalXmlAttribute(string prefix, string localName, string namespaceURI, XmlDocument doc, bool defaultNodeSetInclusionState) + public CanonicalXmlAttribute(string? prefix, string localName, string? namespaceURI, XmlDocument doc, bool defaultNodeSetInclusionState) : base(prefix, localName, namespaceURI, doc) { IsInNodeSet = defaultNodeSetInclusionState; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlCDataSection.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlCDataSection.cs index ff5d9d4529150b..a80a5d7f546505 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlCDataSection.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlCDataSection.cs @@ -10,7 +10,7 @@ namespace System.Security.Cryptography.Xml internal sealed class CanonicalXmlCDataSection : XmlCDataSection, ICanonicalizableNode { private bool _isInNodeSet; - public CanonicalXmlCDataSection(string data, XmlDocument doc, bool defaultNodeSetInclusionState) : base(data, doc) + public CanonicalXmlCDataSection(string? data, XmlDocument doc, bool defaultNodeSetInclusionState) : base(data, doc) { _isInNodeSet = defaultNodeSetInclusionState; } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlComment.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlComment.cs index 99c4a2fdbcd7f7..af36db1a1b7e15 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlComment.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlComment.cs @@ -12,7 +12,7 @@ internal sealed class CanonicalXmlComment : XmlComment, ICanonicalizableNode private bool _isInNodeSet; private readonly bool _includeComments; - public CanonicalXmlComment(string comment, XmlDocument doc, bool defaultNodeSetInclusionState, bool includeComments) + public CanonicalXmlComment(string? comment, XmlDocument doc, bool defaultNodeSetInclusionState, bool includeComments) : base(comment, doc) { _isInNodeSet = defaultNodeSetInclusionState; @@ -55,7 +55,7 @@ public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespace hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0); rgbData = utf8.GetBytes(""); hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlDocument.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlDocument.cs index 9713d998428f25..da8481cd7597cc 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlDocument.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlDocument.cs @@ -61,42 +61,42 @@ public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespace } } - public override XmlElement CreateElement(string prefix, string localName, string namespaceURI) + public override XmlElement CreateElement(string? prefix, string localName, string? namespaceURI) { return new CanonicalXmlElement(prefix, localName, namespaceURI, this, _defaultNodeSetInclusionState); } - public override XmlAttribute CreateAttribute(string prefix, string localName, string namespaceURI) + public override XmlAttribute CreateAttribute(string? prefix, string localName, string? namespaceURI) { return new CanonicalXmlAttribute(prefix, localName, namespaceURI, this, _defaultNodeSetInclusionState); } - protected override XmlAttribute CreateDefaultAttribute(string prefix, string localName, string namespaceURI) + protected override XmlAttribute CreateDefaultAttribute(string? prefix, string localName, string? namespaceURI) { return new CanonicalXmlAttribute(prefix, localName, namespaceURI, this, _defaultNodeSetInclusionState); } - public override XmlText CreateTextNode(string text) + public override XmlText CreateTextNode(string? text) { return new CanonicalXmlText(text, this, _defaultNodeSetInclusionState); } - public override XmlWhitespace CreateWhitespace(string prefix) + public override XmlWhitespace CreateWhitespace(string? prefix) { return new CanonicalXmlWhitespace(prefix, this, _defaultNodeSetInclusionState); } - public override XmlSignificantWhitespace CreateSignificantWhitespace(string text) + public override XmlSignificantWhitespace CreateSignificantWhitespace(string? text) { return new CanonicalXmlSignificantWhitespace(text, this, _defaultNodeSetInclusionState); } - public override XmlProcessingInstruction CreateProcessingInstruction(string target, string data) + public override XmlProcessingInstruction CreateProcessingInstruction(string target, string? data) { - return new CanonicalXmlProcessingInstruction(target, data, this, _defaultNodeSetInclusionState); + return new CanonicalXmlProcessingInstruction(target, data!, this, _defaultNodeSetInclusionState); } - public override XmlComment CreateComment(string data) + public override XmlComment CreateComment(string? data) { return new CanonicalXmlComment(data, this, _defaultNodeSetInclusionState, _includeComments); } @@ -106,7 +106,7 @@ public override XmlEntityReference CreateEntityReference(string name) return new CanonicalXmlEntityReference(name, this, _defaultNodeSetInclusionState); } - public override XmlCDataSection CreateCDataSection(string data) + public override XmlCDataSection CreateCDataSection(string? data) { return new CanonicalXmlCDataSection(data, this, _defaultNodeSetInclusionState); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlElement.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlElement.cs index 7d3174b0780063..71cb45868b0a96 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlElement.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlElement.cs @@ -12,8 +12,8 @@ internal sealed class CanonicalXmlElement : XmlElement, ICanonicalizableNode { private bool _isInNodeSet; - public CanonicalXmlElement(string prefix, string localName, string namespaceURI, XmlDocument doc, bool defaultNodeSetInclusionState) - : base(prefix, localName, namespaceURI, doc) + public CanonicalXmlElement(string? prefix, string localName, string? namespaceURI, XmlDocument doc, bool defaultNodeSetInclusionState) + : base(prefix!, localName, namespaceURI, doc) { _isInNodeSet = defaultNodeSetInclusionState; } @@ -30,7 +30,7 @@ public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespa SortedList nsListToRender = new SortedList(new NamespaceSortOrder()); SortedList attrListToRender = new SortedList(new AttributeSortOrder()); - XmlAttributeCollection attrList = Attributes; + XmlAttributeCollection? attrList = Attributes; if (attrList != null) { foreach (XmlAttribute attr in attrList) @@ -68,11 +68,11 @@ public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespa strBuilder.Append('<').Append(Name); foreach (object attr in nsListToRender.GetKeyList()) { - (attr as CanonicalXmlAttribute).Write(strBuilder, docPos, anc); + (attr as CanonicalXmlAttribute)!.Write(strBuilder, docPos, anc); } foreach (object attr in attrListToRender.GetKeyList()) { - (attr as CanonicalXmlAttribute).Write(strBuilder, docPos, anc); + (attr as CanonicalXmlAttribute)!.Write(strBuilder, docPos, anc); } strBuilder.Append('>'); } @@ -141,11 +141,11 @@ public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespace hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0); foreach (object attr in nsListToRender.GetKeyList()) { - (attr as CanonicalXmlAttribute).WriteHash(hash, docPos, anc); + (attr as CanonicalXmlAttribute)!.WriteHash(hash, docPos, anc); } foreach (object attr in attrListToRender.GetKeyList()) { - (attr as CanonicalXmlAttribute).WriteHash(hash, docPos, anc); + (attr as CanonicalXmlAttribute)!.WriteHash(hash, docPos, anc); } rgbData = utf8.GetBytes(">"); hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlNodeList.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlNodeList.cs index e1308ea8849808..03db7132bf317a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlNodeList.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlNodeList.cs @@ -17,7 +17,7 @@ internal CanonicalXmlNodeList() public override XmlNode Item(int index) { - return (XmlNode)_nodeArray[index]; + return (XmlNode)_nodeArray[index]!; } public override IEnumerator GetEnumerator() @@ -31,7 +31,7 @@ public override int Count } // IList methods - public int Add(object value) + public int Add(object? value) { if (!(value is XmlNode)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, "node"); @@ -43,24 +43,24 @@ public void Clear() _nodeArray.Clear(); } - public bool Contains(object value) + public bool Contains(object? value) { return _nodeArray.Contains(value); } - public int IndexOf(object value) + public int IndexOf(object? value) { return _nodeArray.IndexOf(value); } - public void Insert(int index, object value) + public void Insert(int index, object? value) { if (!(value is XmlNode)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); _nodeArray.Insert(index, value); } - public void Remove(object value) + public void Remove(object? value) { _nodeArray.Remove(value); } @@ -80,7 +80,7 @@ public bool IsReadOnly get { return _nodeArray.IsReadOnly; } } - object IList.this[int index] + object? IList.this[int index] { get { return _nodeArray[index]; } set diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlSignificantWhitespace.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlSignificantWhitespace.cs index cd4ec4820e2471..2d3e8066b18fb5 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlSignificantWhitespace.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlSignificantWhitespace.cs @@ -11,7 +11,7 @@ internal sealed class CanonicalXmlSignificantWhitespace : XmlSignificantWhitespa { private bool _isInNodeSet; - public CanonicalXmlSignificantWhitespace(string strData, XmlDocument doc, bool defaultNodeSetInclusionState) + public CanonicalXmlSignificantWhitespace(string? strData, XmlDocument doc, bool defaultNodeSetInclusionState) : base(strData, doc) { _isInNodeSet = defaultNodeSetInclusionState; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlText.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlText.cs index 90982628d4be33..de81dfea23e087 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlText.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlText.cs @@ -11,7 +11,7 @@ internal sealed class CanonicalXmlText : XmlText, ICanonicalizableNode { private bool _isInNodeSet; - public CanonicalXmlText(string strData, XmlDocument doc, bool defaultNodeSetInclusionState) + public CanonicalXmlText(string? strData, XmlDocument doc, bool defaultNodeSetInclusionState) : base(strData, doc) { _isInNodeSet = defaultNodeSetInclusionState; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlWhitespace.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlWhitespace.cs index 38fae307ed4dc0..9871fac19b4ea9 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlWhitespace.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlWhitespace.cs @@ -11,7 +11,7 @@ internal sealed class CanonicalXmlWhitespace : XmlWhitespace, ICanonicalizableNo { private bool _isInNodeSet; - public CanonicalXmlWhitespace(string strData, XmlDocument doc, bool defaultNodeSetInclusionState) + public CanonicalXmlWhitespace(string? strData, XmlDocument doc, bool defaultNodeSetInclusionState) : base(strData, doc) { _isInNodeSet = defaultNodeSetInclusionState; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs index 877c641a4eabd3..9b1dfb2d6aa018 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs @@ -1,15 +1,16 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Xml; namespace System.Security.Cryptography.Xml { public sealed class CipherData { - private XmlElement _cachedXml; - private CipherReference _cipherReference; - private byte[] _cipherValue; + private XmlElement? _cachedXml; + private CipherReference? _cipherReference; + private byte[]? _cipherValue; public CipherData() { } @@ -23,6 +24,7 @@ public CipherData(CipherReference cipherReference) CipherReference = cipherReference; } + [MemberNotNullWhen(true, nameof(_cachedXml))] private bool CacheValid { get @@ -31,7 +33,8 @@ private bool CacheValid } } - public CipherReference CipherReference + [DisallowNull] + public CipherReference? CipherReference { get { return _cipherReference; } set @@ -46,7 +49,8 @@ public CipherReference CipherReference } } - public byte[] CipherValue + [DisallowNull] + public byte[]? CipherValue { get { return _cipherValue; } set @@ -100,8 +104,8 @@ public void LoadXml(XmlElement value) XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); - XmlNode cipherValueNode = value.SelectSingleNode("enc:CipherValue", nsm); - XmlNode cipherReferenceNode = value.SelectSingleNode("enc:CipherReference", nsm); + XmlNode? cipherValueNode = value.SelectSingleNode("enc:CipherValue", nsm); + XmlNode? cipherReferenceNode = value.SelectSingleNode("enc:CipherReference", nsm); if (cipherValueNode != null) { if (cipherReferenceNode != null) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs index b87286eb7f118b..635d8996e2af25 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs @@ -7,7 +7,7 @@ namespace System.Security.Cryptography.Xml { public sealed class CipherReference : EncryptedReference { - private byte[] _cipherValue; + private byte[]? _cipherValue; public CipherReference() : base() { @@ -25,7 +25,7 @@ public CipherReference(string uri, TransformChain transformChain) : base(uri, tr } // This method is used to cache results from resolved cipher references. - internal byte[] CipherValue + internal byte[]? CipherValue { get { @@ -73,15 +73,15 @@ public override void LoadXml(XmlElement value) } ReferenceType = value.LocalName; - string uri = Utils.GetAttribute(value, "URI", EncryptedXml.XmlEncNamespaceUrl); + string? uri = Utils.GetAttribute(value, "URI", EncryptedXml.XmlEncNamespaceUrl); Uri = uri ?? throw new CryptographicException(SR.Cryptography_Xml_UriRequired); // Transforms XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); - XmlNode transformsNode = value.SelectSingleNode("enc:Transforms", nsm); + XmlNode? transformsNode = value.SelectSingleNode("enc:Transforms", nsm); if (transformsNode != null) - TransformChain.LoadXml(transformsNode as XmlElement); + TransformChain.LoadXml((transformsNode as XmlElement)!); // cache the Xml _cachedXml = value; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CryptoHelpers.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CryptoHelpers.cs index 0f9365f9e01642..1e602141bcfa6a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CryptoHelpers.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CryptoHelpers.cs @@ -7,7 +7,7 @@ internal static class CryptoHelpers { private static readonly char[] _invalidChars = new char[] { ',', '`', '[', '*', '&' }; - public static object CreateFromKnownName(string name) => + public static object? CreateFromKnownName(string name) => name switch { "http://www.w3.org/TR/2001/REC-xml-c14n-20010315" => new XmlDsigC14NTransform(), @@ -38,7 +38,7 @@ public static object CreateFromKnownName(string name) => _ => null, }; - public static T CreateFromName(string name) where T : class + public static T? CreateFromName(string? name) where T : class { if (name == null || name.IndexOfAny(_invalidChars) >= 0) { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs index d1b347e1379936..19d2f73817c675 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs @@ -84,19 +84,19 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) XmlElement dsaKeyValueElement = xmlDocument.CreateElement(DSAKeyValueElementName, SignedXml.XmlDsigNamespaceUrl); XmlElement pElement = xmlDocument.CreateElement(PElementName, SignedXml.XmlDsigNamespaceUrl); - pElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.P))); + pElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.P!))); dsaKeyValueElement.AppendChild(pElement); XmlElement qElement = xmlDocument.CreateElement(QElementName, SignedXml.XmlDsigNamespaceUrl); - qElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.Q))); + qElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.Q!))); dsaKeyValueElement.AppendChild(qElement); XmlElement gElement = xmlDocument.CreateElement(GElementName, SignedXml.XmlDsigNamespaceUrl); - gElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.G))); + gElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.G!))); dsaKeyValueElement.AppendChild(gElement); XmlElement yElement = xmlDocument.CreateElement(YElementName, SignedXml.XmlDsigNamespaceUrl); - yElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.Y))); + yElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dsaParams.Y!))); dsaKeyValueElement.AppendChild(yElement); // Add optional components if present @@ -155,28 +155,28 @@ public override void LoadXml(XmlElement value) XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(value.OwnerDocument.NameTable); xmlNamespaceManager.AddNamespace(xmlDsigNamespacePrefix, SignedXml.XmlDsigNamespaceUrl); - XmlNode dsaKeyValueElement = value.SelectSingleNode($"{xmlDsigNamespacePrefix}:{DSAKeyValueElementName}", xmlNamespaceManager); + XmlNode? dsaKeyValueElement = value.SelectSingleNode($"{xmlDsigNamespacePrefix}:{DSAKeyValueElementName}", xmlNamespaceManager); if (dsaKeyValueElement == null) { throw new CryptographicException(SR.Format(SR.MustContainChildElement, KeyValueElementName, DSAKeyValueElementName)); } - XmlNode yNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{YElementName}", xmlNamespaceManager); + XmlNode? yNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{YElementName}", xmlNamespaceManager); if (yNode == null) throw new CryptographicException(SR.Format(SR.ElementMissing, YElementName)); - XmlNode pNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{PElementName}", xmlNamespaceManager); - XmlNode qNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{QElementName}", xmlNamespaceManager); + XmlNode? pNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{PElementName}", xmlNamespaceManager); + XmlNode? qNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{QElementName}", xmlNamespaceManager); if ((pNode == null && qNode != null) || (pNode != null && qNode == null)) throw new CryptographicException(SR.Format(SR.ElementCombinationMissing, PElementName, QElementName)); - XmlNode gNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{GElementName}", xmlNamespaceManager); - XmlNode jNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{JElementName}", xmlNamespaceManager); + XmlNode? gNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{GElementName}", xmlNamespaceManager); + XmlNode? jNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{JElementName}", xmlNamespaceManager); - XmlNode seedNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{SeedElementName}", xmlNamespaceManager); - XmlNode pgenCounterNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{PgenCounterElementName}", xmlNamespaceManager); + XmlNode? seedNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{SeedElementName}", xmlNamespaceManager); + XmlNode? pgenCounterNode = dsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{PgenCounterElementName}", xmlNamespaceManager); if ((seedNode == null && pgenCounterNode != null) || (seedNode != null && pgenCounterNode == null)) throw new CryptographicException(SR.Format(SR.ElementCombinationMissing, SeedElementName, PgenCounterElementName)); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSASignatureDescription.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSASignatureDescription.cs index 1d3fe08ab8dde9..2b423e681e0fbc 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSASignatureDescription.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSASignatureDescription.cs @@ -19,7 +19,7 @@ public DSASignatureDescription() public sealed override AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key) { - var item = (AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(DeformatterAlgorithm); + var item = (AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(DeformatterAlgorithm!)!; item.SetKey(key); item.SetHashAlgorithm(HashAlgorithm); return item; @@ -27,7 +27,7 @@ public sealed override AsymmetricSignatureDeformatter CreateDeformatter(Asymmetr public sealed override AsymmetricSignatureFormatter CreateFormatter(AsymmetricAlgorithm key) { - var item = (AsymmetricSignatureFormatter)CryptoConfig.CreateFromName(FormatterAlgorithm); + var item = (AsymmetricSignatureFormatter)CryptoConfig.CreateFromName(FormatterAlgorithm!)!; item.SetKey(key); item.SetHashAlgorithm(HashAlgorithm); return item; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs index 83d5929dc68f0c..3242122610acd5 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs @@ -1,17 +1,18 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Xml; namespace System.Security.Cryptography.Xml { public class DataObject { - private string _id; - private string _mimeType; - private string _encoding; + private string? _id; + private string? _mimeType; + private string? _encoding; private CanonicalXmlNodeList _elData; - private XmlElement _cachedXml; + private XmlElement? _cachedXml; // // public constructors @@ -42,7 +43,7 @@ public DataObject(string id, string mimeType, string encoding, XmlElement data) // public properties // - public string Id + public string? Id { get { return _id; } set @@ -52,7 +53,7 @@ public string Id } } - public string MimeType + public string? MimeType { get { return _mimeType; } set @@ -62,7 +63,7 @@ public string MimeType } } - public string Encoding + public string? Encoding { get { return _encoding; } set @@ -90,6 +91,7 @@ public XmlNodeList Data } } + [MemberNotNullWhen(true, nameof(_cachedXml))] private bool CacheValid { get @@ -104,7 +106,7 @@ private bool CacheValid public XmlElement GetXml() { - if (CacheValid) return (_cachedXml); + if (CacheValid) return _cachedXml; XmlDocument document = new XmlDocument(); document.PreserveWhitespace = true; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs index 7320dd628118c3..016018883c4348 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs @@ -23,39 +23,39 @@ public override void LoadXml(XmlElement value) MimeType = Utils.GetAttribute(value, "MimeType", EncryptedXml.XmlEncNamespaceUrl); Encoding = Utils.GetAttribute(value, "Encoding", EncryptedXml.XmlEncNamespaceUrl); - XmlNode encryptionMethodNode = value.SelectSingleNode("enc:EncryptionMethod", nsm); + XmlNode? encryptionMethodNode = value.SelectSingleNode("enc:EncryptionMethod", nsm); // EncryptionMethod EncryptionMethod = new EncryptionMethod(); if (encryptionMethodNode != null) - EncryptionMethod.LoadXml(encryptionMethodNode as XmlElement); + EncryptionMethod.LoadXml((encryptionMethodNode as XmlElement)!); // Key Info KeyInfo = new KeyInfo(); - XmlNode keyInfoNode = value.SelectSingleNode("ds:KeyInfo", nsm); + XmlNode? keyInfoNode = value.SelectSingleNode("ds:KeyInfo", nsm); if (keyInfoNode != null) - KeyInfo.LoadXml(keyInfoNode as XmlElement); + KeyInfo.LoadXml((keyInfoNode as XmlElement)!); // CipherData - XmlNode cipherDataNode = value.SelectSingleNode("enc:CipherData", nsm); + XmlNode? cipherDataNode = value.SelectSingleNode("enc:CipherData", nsm); if (cipherDataNode == null) throw new CryptographicException(SR.Cryptography_Xml_MissingCipherData); CipherData = new CipherData(); - CipherData.LoadXml(cipherDataNode as XmlElement); + CipherData.LoadXml((cipherDataNode as XmlElement)!); // EncryptionProperties - XmlNode encryptionPropertiesNode = value.SelectSingleNode("enc:EncryptionProperties", nsm); + XmlNode? encryptionPropertiesNode = value.SelectSingleNode("enc:EncryptionProperties", nsm); if (encryptionPropertiesNode != null) { // Select the EncryptionProperty elements inside the EncryptionProperties element - XmlNodeList encryptionPropertyNodes = encryptionPropertiesNode.SelectNodes("enc:EncryptionProperty", nsm); + XmlNodeList? encryptionPropertyNodes = encryptionPropertiesNode.SelectNodes("enc:EncryptionProperty", nsm); if (encryptionPropertyNodes != null) { foreach (XmlNode node in encryptionPropertyNodes) { EncryptionProperty ep = new EncryptionProperty(); - ep.LoadXml(node as XmlElement); + ep.LoadXml((node as XmlElement)!); EncryptionProperties.Add(ep); } } @@ -67,7 +67,7 @@ public override void LoadXml(XmlElement value) public override XmlElement GetXml() { - if (CacheValid) return (_cachedXml); + if (CacheValid) return _cachedXml; XmlDocument document = new XmlDocument(); document.PreserveWhitespace = true; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs index 47f374e9e02975..2b3f9e02ac3f6e 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs @@ -1,18 +1,20 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Xml; namespace System.Security.Cryptography.Xml { public sealed class EncryptedKey : EncryptedType { - private string _recipient; - private string _carriedKeyName; - private ReferenceList _referenceList; + private string? _recipient; + private string? _carriedKeyName; + private ReferenceList? _referenceList; public EncryptedKey() { } + [AllowNull] public string Recipient { get => _recipient ??= string.Empty; // an unspecified value for an XmlAttribute is string.Empty @@ -23,7 +25,7 @@ public string Recipient } } - public string CarriedKeyName + public string? CarriedKeyName { get { return _carriedKeyName; } set @@ -62,74 +64,74 @@ public override void LoadXml(XmlElement value) Encoding = Utils.GetAttribute(value, "Encoding", EncryptedXml.XmlEncNamespaceUrl); Recipient = Utils.GetAttribute(value, "Recipient", EncryptedXml.XmlEncNamespaceUrl); - XmlNode encryptionMethodNode = value.SelectSingleNode("enc:EncryptionMethod", nsm); + XmlNode? encryptionMethodNode = value.SelectSingleNode("enc:EncryptionMethod", nsm); // EncryptionMethod EncryptionMethod = new EncryptionMethod(); if (encryptionMethodNode != null) - EncryptionMethod.LoadXml(encryptionMethodNode as XmlElement); + EncryptionMethod.LoadXml((encryptionMethodNode as XmlElement)!); // Key Info KeyInfo = new KeyInfo(); - XmlNode keyInfoNode = value.SelectSingleNode("ds:KeyInfo", nsm); + XmlNode? keyInfoNode = value.SelectSingleNode("ds:KeyInfo", nsm); if (keyInfoNode != null) - KeyInfo.LoadXml(keyInfoNode as XmlElement); + KeyInfo.LoadXml((keyInfoNode as XmlElement)!); // CipherData - XmlNode cipherDataNode = value.SelectSingleNode("enc:CipherData", nsm); + XmlNode? cipherDataNode = value.SelectSingleNode("enc:CipherData", nsm); if (cipherDataNode == null) throw new CryptographicException(SR.Cryptography_Xml_MissingCipherData); CipherData = new CipherData(); - CipherData.LoadXml(cipherDataNode as XmlElement); + CipherData.LoadXml((cipherDataNode as XmlElement)!); // EncryptionProperties - XmlNode encryptionPropertiesNode = value.SelectSingleNode("enc:EncryptionProperties", nsm); + XmlNode? encryptionPropertiesNode = value.SelectSingleNode("enc:EncryptionProperties", nsm); if (encryptionPropertiesNode != null) { // Select the EncryptionProperty elements inside the EncryptionProperties element - XmlNodeList encryptionPropertyNodes = encryptionPropertiesNode.SelectNodes("enc:EncryptionProperty", nsm); + XmlNodeList? encryptionPropertyNodes = encryptionPropertiesNode.SelectNodes("enc:EncryptionProperty", nsm); if (encryptionPropertyNodes != null) { foreach (XmlNode node in encryptionPropertyNodes) { EncryptionProperty ep = new EncryptionProperty(); - ep.LoadXml(node as XmlElement); + ep.LoadXml((node as XmlElement)!); EncryptionProperties.Add(ep); } } } // CarriedKeyName - XmlNode carriedKeyNameNode = value.SelectSingleNode("enc:CarriedKeyName", nsm); + XmlNode? carriedKeyNameNode = value.SelectSingleNode("enc:CarriedKeyName", nsm); if (carriedKeyNameNode != null) { CarriedKeyName = carriedKeyNameNode.InnerText; } // ReferenceList - XmlNode referenceListNode = value.SelectSingleNode("enc:ReferenceList", nsm); + XmlNode? referenceListNode = value.SelectSingleNode("enc:ReferenceList", nsm); if (referenceListNode != null) { // Select the DataReference elements inside the ReferenceList element - XmlNodeList dataReferenceNodes = referenceListNode.SelectNodes("enc:DataReference", nsm); + XmlNodeList? dataReferenceNodes = referenceListNode.SelectNodes("enc:DataReference", nsm); if (dataReferenceNodes != null) { foreach (XmlNode node in dataReferenceNodes) { DataReference dr = new DataReference(); - dr.LoadXml(node as XmlElement); + dr.LoadXml((node as XmlElement)!); ReferenceList.Add(dr); } } // Select the KeyReference elements inside the ReferenceList element - XmlNodeList keyReferenceNodes = referenceListNode.SelectNodes("enc:KeyReference", nsm); + XmlNodeList? keyReferenceNodes = referenceListNode.SelectNodes("enc:KeyReference", nsm); if (keyReferenceNodes != null) { foreach (XmlNode node in keyReferenceNodes) { KeyReference kr = new KeyReference(); - kr.LoadXml(node as XmlElement); + kr.LoadXml((node as XmlElement)!); ReferenceList.Add(kr); } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs index 315e5ea0cb122c..04d6e3a0d14902 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Xml; namespace System.Security.Cryptography.Xml @@ -8,9 +9,9 @@ namespace System.Security.Cryptography.Xml public abstract class EncryptedReference { private string _uri; - private string _referenceType; - private TransformChain _transformChain; - internal XmlElement _cachedXml; + private string? _referenceType; + private TransformChain? _transformChain; + internal XmlElement? _cachedXml; protected EncryptedReference() : this(string.Empty, new TransformChain()) { @@ -30,6 +31,8 @@ protected EncryptedReference(string uri, TransformChain transformChain) public string Uri { get { return _uri; } + + [MemberNotNull(nameof(_uri))] set { if (value == null) @@ -54,7 +57,7 @@ public void AddTransform(Transform transform) TransformChain.Add(transform); } - protected string ReferenceType + protected string? ReferenceType { get { return _referenceType; } set @@ -64,6 +67,7 @@ protected string ReferenceType } } + [MemberNotNullWhen(true, nameof(_cachedXml))] protected internal bool CacheValid { get @@ -107,7 +111,7 @@ public virtual void LoadXml(XmlElement value) ReferenceType = value.LocalName; - string uri = Utils.GetAttribute(value, "URI", EncryptedXml.XmlEncNamespaceUrl); + string? uri = Utils.GetAttribute(value, "URI", EncryptedXml.XmlEncNamespaceUrl); if (uri == null) throw new ArgumentNullException(SR.Cryptography_Xml_UriRequired); Uri = uri; @@ -115,9 +119,9 @@ public virtual void LoadXml(XmlElement value) // Transforms XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); - XmlNode transformsNode = value.SelectSingleNode("ds:Transforms", nsm); + XmlNode? transformsNode = value.SelectSingleNode("ds:Transforms", nsm); if (transformsNode != null) - TransformChain.LoadXml(transformsNode as XmlElement); + TransformChain.LoadXml((transformsNode as XmlElement)!); // cache the Xml _cachedXml = value; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs index 61c5339f0264fc..e32f63ec067f5d 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs @@ -1,22 +1,24 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Xml; namespace System.Security.Cryptography.Xml { public abstract class EncryptedType { - private string _id; - private string _type; - private string _mimeType; - private string _encoding; - private EncryptionMethod _encryptionMethod; - private CipherData _cipherData; - private EncryptionPropertyCollection _props; - private KeyInfo _keyInfo; - internal XmlElement _cachedXml; + private string? _id; + private string? _type; + private string? _mimeType; + private string? _encoding; + private EncryptionMethod? _encryptionMethod; + private CipherData? _cipherData; + private EncryptionPropertyCollection? _props; + private KeyInfo? _keyInfo; + internal XmlElement? _cachedXml; + [MemberNotNullWhen(true, nameof(_cachedXml))] internal bool CacheValid { get @@ -25,7 +27,7 @@ internal bool CacheValid } } - public virtual string Id + public virtual string? Id { get { return _id; } set @@ -35,7 +37,7 @@ public virtual string Id } } - public virtual string Type + public virtual string? Type { get { return _type; } set @@ -45,7 +47,7 @@ public virtual string Type } } - public virtual string MimeType + public virtual string? MimeType { get { return _mimeType; } set @@ -55,7 +57,7 @@ public virtual string MimeType } } - public virtual string Encoding + public virtual string? Encoding { get { return _encoding; } set @@ -65,13 +67,14 @@ public virtual string Encoding } } + [AllowNull] public KeyInfo KeyInfo { get => _keyInfo ??= new KeyInfo(); set => _keyInfo = value; } - public virtual EncryptionMethod EncryptionMethod + public virtual EncryptionMethod? EncryptionMethod { get { return _encryptionMethod; } set diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs index fc860409ec515d..1b769ebe3f687b 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Security.Policy; @@ -59,8 +60,8 @@ public class EncryptedXml // private readonly XmlDocument _document; - private Evidence _evidence; - private XmlResolver _xmlResolver; + private Evidence? _evidence; + private XmlResolver? _xmlResolver; // hash table defining the key name mapping private const int _capacity = 4; // 4 is a reasonable capacity for // the key name mapping hash table @@ -68,7 +69,7 @@ public class EncryptedXml private PaddingMode _padding; private CipherMode _mode; private Encoding _encoding; - private string _recipient; + private string? _recipient; private int _xmlDsigSearchDepthCounter; private int _xmlDsigSearchDepth; @@ -79,7 +80,7 @@ public EncryptedXml() : this(new XmlDocument()) { } public EncryptedXml(XmlDocument document) : this(document, null) { } - public EncryptedXml(XmlDocument document, Evidence evidence) + public EncryptedXml(XmlDocument document, Evidence? evidence) { _document = document; _evidence = evidence; @@ -124,14 +125,14 @@ public int XmlDSigSearchDepth } // The evidence of the document being loaded: will be used to resolve external URIs - public Evidence DocumentEvidence + public Evidence? DocumentEvidence { get { return _evidence; } set { _evidence = value; } } // The resolver to use for external entities - public XmlResolver Resolver + public XmlResolver? Resolver { get { return _xmlResolver; } set { _xmlResolver = value; } @@ -162,6 +163,7 @@ public Encoding Encoding // This is used to specify the EncryptedKey elements that should be considered // when an EncryptedData references an EncryptedKey using a CarriedKeyName and Recipient + [AllowNull] public string Recipient { get => _recipient ??= string.Empty; // an unspecified value for an XmlAttribute is string.Empty @@ -179,7 +181,7 @@ private byte[] GetCipherValue(CipherData cipherData) throw new ArgumentNullException(nameof(cipherData)); } - Stream inputStream = null; + Stream? inputStream = null; if (cipherData.CipherValue != null) { @@ -189,7 +191,7 @@ private byte[] GetCipherValue(CipherData cipherData) { if (cipherData.CipherReference.CipherValue != null) return cipherData.CipherReference.CipherValue; - Stream decInputStream; + Stream? decInputStream; if (cipherData.CipherReference.Uri == null) { throw new CryptographicException(SR.Cryptography_Xml_UriNotSupported); @@ -198,7 +200,7 @@ private byte[] GetCipherValue(CipherData cipherData) if (cipherData.CipherReference.Uri.Length == 0) { // self referenced Uri - string baseUri = _document?.BaseURI; + string? baseUri = _document?.BaseURI; TransformChain tc = cipherData.CipherReference.TransformChain; if (tc == null) { @@ -210,13 +212,13 @@ private byte[] GetCipherValue(CipherData cipherData) { string idref = Utils.ExtractIdFromLocalUri(cipherData.CipherReference.Uri); // Serialize - XmlElement idElem = GetIdElement(_document, idref); + XmlElement? idElem = GetIdElement(_document, idref); if (idElem == null || idElem.OuterXml == null) { throw new CryptographicException(SR.Cryptography_Xml_UriNotSupported); } inputStream = new MemoryStream(_encoding.GetBytes(idElem.OuterXml)); - string baseUri = _document?.BaseURI; + string baseUri = _document.BaseURI; TransformChain tc = cipherData.CipherReference.TransformChain; if (tc == null) { @@ -229,7 +231,7 @@ private byte[] GetCipherValue(CipherData cipherData) throw new CryptographicException(SR.Cryptography_Xml_UriNotResolved, cipherData.CipherReference.Uri); } // read the output stream into a memory stream - byte[] cipherValue = null; + byte[]? cipherValue = null; using (MemoryStream ms = new MemoryStream()) { Utils.Pump(decInputStream, ms); @@ -253,13 +255,13 @@ private byte[] GetCipherValue(CipherData cipherData) // // This describes how the application wants to associate id references to elements - public virtual XmlElement GetIdElement(XmlDocument document, string idValue) + public virtual XmlElement? GetIdElement(XmlDocument document, string idValue) { return SignedXml.DefaultGetIdElement(document, idValue); } // default behaviour is to look for the IV in the CipherValue - public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string symmetricAlgorithmUri) + public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string? symmetricAlgorithmUri) { if (encryptedData is null) { @@ -297,7 +299,7 @@ public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string symmet // default behaviour is to look for keys defined by an EncryptedKey clause // either directly or through a KeyInfoRetrievalMethod, and key names in the key mapping - public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri) + public virtual SymmetricAlgorithm? GetDecryptionKey(EncryptedData encryptedData, string? symmetricAlgorithmUri) { if (encryptedData is null) { @@ -307,10 +309,10 @@ public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, if (encryptedData.KeyInfo == null) return null; IEnumerator keyInfoEnum = encryptedData.KeyInfo.GetEnumerator(); - KeyInfoRetrievalMethod kiRetrievalMethod; - KeyInfoName kiName; - KeyInfoEncryptedKey kiEncKey; - EncryptedKey ek = null; + KeyInfoRetrievalMethod? kiRetrievalMethod; + KeyInfoName? kiName; + KeyInfoEncryptedKey? kiEncKey; + EncryptedKey? ek = null; while (keyInfoEnum.MoveNext()) { @@ -318,18 +320,18 @@ public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, if (kiName != null) { // Get the decryption key from the key mapping - string keyName = kiName.Value; - if ((SymmetricAlgorithm)_keyNameMapping[keyName] != null) - return (SymmetricAlgorithm)_keyNameMapping[keyName]; + string keyName = kiName.Value!; + if ((SymmetricAlgorithm?)_keyNameMapping[keyName] != null) + return (SymmetricAlgorithm)_keyNameMapping[keyName]!; // try to get it from a CarriedKeyName XmlNamespaceManager nsm = new XmlNamespaceManager(_document.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); - XmlNodeList encryptedKeyList = _document.SelectNodes("//enc:EncryptedKey", nsm); + XmlNodeList? encryptedKeyList = _document.SelectNodes("//enc:EncryptedKey", nsm); if (encryptedKeyList != null) { foreach (XmlNode encryptedKeyNode in encryptedKeyList) { - XmlElement encryptedKeyElement = encryptedKeyNode as XmlElement; + XmlElement encryptedKeyElement = (encryptedKeyNode as XmlElement)!; EncryptedKey ek1 = new EncryptedKey(); ek1.LoadXml(encryptedKeyElement); if (ek1.CarriedKeyName == keyName && ek1.Recipient == Recipient) @@ -344,9 +346,9 @@ public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod; if (kiRetrievalMethod != null) { - string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri); + string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri!); ek = new EncryptedKey(); - ek.LoadXml(GetIdElement(_document, idref)); + ek.LoadXml(GetIdElement(_document, idref)!); break; } kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey; @@ -368,11 +370,11 @@ public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm; } - byte[] key = DecryptEncryptedKey(ek); + byte[]? key = DecryptEncryptedKey(ek); if (key == null) throw new CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey); - SymmetricAlgorithm symAlg = CryptoHelpers.CreateFromName(symmetricAlgorithmUri); + SymmetricAlgorithm? symAlg = CryptoHelpers.CreateFromName(symmetricAlgorithmUri); if (symAlg == null) { throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); @@ -384,7 +386,7 @@ public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, } // Try to decrypt the EncryptedKey given the key mapping - public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) + public virtual byte[]? DecryptEncryptedKey(EncryptedKey encryptedKey) { if (encryptedKey is null) { @@ -395,11 +397,11 @@ public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) return null; IEnumerator keyInfoEnum = encryptedKey.KeyInfo.GetEnumerator(); - KeyInfoName kiName; - KeyInfoX509Data kiX509Data; - KeyInfoRetrievalMethod kiRetrievalMethod; - KeyInfoEncryptedKey kiEncKey; - EncryptedKey ek; + KeyInfoName? kiName; + KeyInfoX509Data? kiX509Data; + KeyInfoRetrievalMethod? kiRetrievalMethod; + KeyInfoEncryptedKey? kiEncKey; + EncryptedKey? ek; bool fOAEP; while (keyInfoEnum.MoveNext()) @@ -408,8 +410,8 @@ public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) if (kiName != null) { // Get the decryption key from the key mapping - string keyName = kiName.Value; - object kek = _keyNameMapping[keyName]; + string keyName = kiName.Value!; + object? kek = _keyNameMapping[keyName]; if (kek != null) { if (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null) @@ -432,7 +434,7 @@ public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) X509Certificate2Collection collection = Utils.BuildBagOfCerts(kiX509Data, CertUsageType.Decryption); foreach (X509Certificate2 certificate in collection) { - using (RSA privateKey = certificate.GetRSAPrivateKey()) + using (RSA? privateKey = certificate.GetRSAPrivateKey()) { if (privateKey != null) { @@ -450,9 +452,9 @@ public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod; if (kiRetrievalMethod != null) { - string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri); + string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri!); ek = new EncryptedKey(); - ek.LoadXml(GetIdElement(_document, idref)); + ek.LoadXml(GetIdElement(_document, idref)!); try { //Following checks if XML dsig processing is in loop and within the limit defined by machine @@ -478,11 +480,11 @@ public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) { ek = kiEncKey.EncryptedKey; // recursively process EncryptedKey elements - byte[] encryptionKey = DecryptEncryptedKey(ek); + byte[]? encryptionKey = DecryptEncryptedKey(ek!); if (encryptionKey != null) { // this is a symmetric algorithm for sure - SymmetricAlgorithm symAlg = CryptoHelpers.CreateFromName(encryptedKey.EncryptionMethod.KeyAlgorithm); + SymmetricAlgorithm? symAlg = CryptoHelpers.CreateFromName(encryptedKey.EncryptionMethod!.KeyAlgorithm); if (symAlg == null) { throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); @@ -540,7 +542,7 @@ public EncryptedData Encrypt(XmlElement inputElement, X509Certificate2 certifica throw new ArgumentNullException(nameof(certificate)); } - using (RSA rsaPublicKey = certificate.GetRSAPublicKey()) + using (RSA? rsaPublicKey = certificate.GetRSAPublicKey()) { if (rsaPublicKey == null) throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); @@ -584,7 +586,7 @@ public EncryptedData Encrypt(XmlElement inputElement, string keyName) throw new ArgumentNullException(nameof(keyName)); } - object encryptionKey = null; + object? encryptionKey = null; if (_keyNameMapping != null) encryptionKey = _keyNameMapping[keyName]; @@ -592,8 +594,8 @@ public EncryptedData Encrypt(XmlElement inputElement, string keyName) throw new CryptographicException(SR.Cryptography_Xml_MissingEncryptionKey); // kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table - SymmetricAlgorithm symKey = encryptionKey as SymmetricAlgorithm; - RSA rsa = encryptionKey as RSA; + SymmetricAlgorithm symKey = (encryptionKey as SymmetricAlgorithm)!; + RSA rsa = (encryptionKey as RSA)!; // Create the EncryptedData object, using an AES-256 session key by default. EncryptedData ed = new EncryptedData(); @@ -601,7 +603,7 @@ public EncryptedData Encrypt(XmlElement inputElement, string keyName) ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); // Include the key name in the EncryptedKey KeyInfo. - string encryptionMethod = null; + string? encryptionMethod = null; if (symKey == null) { encryptionMethod = EncryptedXml.XmlEncRSA15Url; @@ -660,15 +662,15 @@ public void DecryptDocument() // Look for all EncryptedData elements and decrypt them XmlNamespaceManager nsm = new XmlNamespaceManager(_document.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); - XmlNodeList encryptedDataList = _document.SelectNodes("//enc:EncryptedData", nsm); + XmlNodeList? encryptedDataList = _document.SelectNodes("//enc:EncryptedData", nsm); if (encryptedDataList != null) { foreach (XmlNode encryptedDataNode in encryptedDataList) { - XmlElement encryptedDataElement = encryptedDataNode as XmlElement; + XmlElement encryptedDataElement = (encryptedDataNode as XmlElement)!; EncryptedData ed = new EncryptedData(); ed.LoadXml(encryptedDataElement); - SymmetricAlgorithm symAlg = GetDecryptionKey(ed, null); + SymmetricAlgorithm? symAlg = GetDecryptionKey(ed, null); if (symAlg == null) throw new CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey); byte[] decrypted = DecryptData(ed, symAlg); @@ -693,7 +695,7 @@ public byte[] EncryptData(byte[] plaintext, SymmetricAlgorithm symmetricAlgorith CipherMode origMode = symmetricAlgorithm.Mode; PaddingMode origPadding = symmetricAlgorithm.Padding; - byte[] cipher = null; + byte[]? cipher = null; try { symmetricAlgorithm.Mode = _mode; @@ -761,11 +763,11 @@ public byte[] DecryptData(EncryptedData encryptedData, SymmetricAlgorithm symmet byte[] origIV = symmetricAlgorithm.IV; // read the IV from cipherValue - byte[] decryptionIV = null; + byte[]? decryptionIV = null; if (_mode != CipherMode.ECB) decryptionIV = GetDecryptionIV(encryptedData, null); - byte[] output = null; + byte[]? output = null; try { int lengthIV = 0; @@ -803,7 +805,7 @@ public void ReplaceData(XmlElement inputElement, byte[] decryptedData) throw new ArgumentNullException(nameof(decryptedData)); } - XmlNode parent = inputElement.ParentNode; + XmlNode parent = inputElement.ParentNode!; if (parent.NodeType == XmlNodeType.Document) { // We're replacing the root element, but we can't just wholesale replace the owner @@ -821,14 +823,14 @@ public void ReplaceData(XmlElement inputElement, byte[] decryptedData) } } - XmlNode importedNode = inputElement.OwnerDocument.ImportNode(importDocument.DocumentElement, true); + XmlNode importedNode = inputElement.OwnerDocument.ImportNode(importDocument.DocumentElement!, true); parent.RemoveChild(inputElement); parent.AppendChild(importedNode); } else { - XmlNode dummy = parent.OwnerDocument.CreateElement(parent.Prefix, parent.LocalName, parent.NamespaceURI); + XmlNode dummy = parent.OwnerDocument!.CreateElement(parent.Prefix, parent.LocalName, parent.NamespaceURI); try { @@ -839,10 +841,10 @@ public void ReplaceData(XmlElement inputElement, byte[] decryptedData) dummy.InnerXml = _encoding.GetString(decryptedData); // Move the children of the dummy node up to the parent. - XmlNode child = dummy.FirstChild; - XmlNode sibling = inputElement.NextSibling; + XmlNode? child = dummy.FirstChild; + XmlNode? sibling = inputElement.NextSibling; - XmlNode nextChild = null; + XmlNode? nextChild = null; while (child != null) { nextChild = child.NextSibling; @@ -888,7 +890,7 @@ public static void ReplaceElement(XmlElement inputElement, EncryptedData encrypt inputElement.AppendChild(elemED); break; case false: - XmlNode parentNode = inputElement.ParentNode; + XmlNode parentNode = inputElement.ParentNode!; // remove the input element from the containing document parentNode.ReplaceChild(elemED, inputElement); break; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs index 4ef3bf89a87969..d50aa84b1dc2ae 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs @@ -1,27 +1,29 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Xml; namespace System.Security.Cryptography.Xml { public class EncryptionMethod { - private XmlElement _cachedXml; + private XmlElement? _cachedXml; private int _keySize; - private string _algorithm; + private string? _algorithm; public EncryptionMethod() { _cachedXml = null; } - public EncryptionMethod(string algorithm) + public EncryptionMethod(string? algorithm) { _algorithm = algorithm; _cachedXml = null; } + [MemberNotNullWhen(true, nameof(_cachedXml))] private bool CacheValid { get @@ -42,7 +44,7 @@ public int KeySize } } - public string KeyAlgorithm + public string? KeyAlgorithm { get { return _algorithm; } set @@ -54,7 +56,7 @@ public string KeyAlgorithm public XmlElement GetXml() { - if (CacheValid) return (_cachedXml); + if (CacheValid) return _cachedXml; XmlDocument document = new XmlDocument(); document.PreserveWhitespace = true; @@ -90,7 +92,7 @@ public void LoadXml(XmlElement value) XmlElement encryptionMethodElement = value; _algorithm = Utils.GetAttribute(encryptionMethodElement, "Algorithm", EncryptedXml.XmlEncNamespaceUrl); - XmlNode keySizeNode = value.SelectSingleNode("enc:KeySize", nsm); + XmlNode? keySizeNode = value.SelectSingleNode("enc:KeySize", nsm); if (keySizeNode != null) { KeySize = Convert.ToInt32(Utils.DiscardWhiteSpaces(keySizeNode.InnerText), null); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs index 6077bd264f8c52..73fc558402c512 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs @@ -1,16 +1,17 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Xml; namespace System.Security.Cryptography.Xml { public sealed class EncryptionProperty { - private string _target; - private string _id; - private XmlElement _elemProp; - private XmlElement _cachedXml; + private string? _target; + private string? _id; + private XmlElement? _elemProp; + private XmlElement? _cachedXml; // We are being lax here as per the spec public EncryptionProperty() { } @@ -29,17 +30,18 @@ public EncryptionProperty(XmlElement elementProperty) _cachedXml = null; } - public string Id + public string? Id { get { return _id; } } - public string Target + public string? Target { get { return _target; } } - public XmlElement PropertyElement + [DisallowNull] + public XmlElement? PropertyElement { get { return _elemProp; } set @@ -54,6 +56,7 @@ public XmlElement PropertyElement } } + [MemberNotNullWhen(true, nameof(_cachedXml))] private bool CacheValid { get @@ -73,7 +76,7 @@ public XmlElement GetXml() internal XmlElement GetXml(XmlDocument document) { - return document.ImportNode(_elemProp, true) as XmlElement; + return (document.ImportNode(_elemProp!, true) as XmlElement)!; } public void LoadXml(XmlElement value) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionPropertyCollection.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionPropertyCollection.cs index 0fca5ef01afeb6..6246b541f61b96 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionPropertyCollection.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionPropertyCollection.cs @@ -25,7 +25,7 @@ public int Count } /// - int IList.Add(object value) + int IList.Add(object? value) { if (!(value is EncryptionProperty)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); @@ -44,7 +44,7 @@ public void Clear() } /// - bool IList.Contains(object value) + bool IList.Contains(object? value) { if (!(value is EncryptionProperty)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); @@ -58,7 +58,7 @@ public bool Contains(EncryptionProperty value) } /// - int IList.IndexOf(object value) + int IList.IndexOf(object? value) { if (!(value is EncryptionProperty)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); @@ -72,7 +72,7 @@ public int IndexOf(EncryptionProperty value) } /// - void IList.Insert(int index, object value) + void IList.Insert(int index, object? value) { if (!(value is EncryptionProperty)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); @@ -86,7 +86,7 @@ public void Insert(int index, EncryptionProperty value) } /// - void IList.Remove(object value) + void IList.Remove(object? value) { if (!(value is EncryptionProperty)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); @@ -116,7 +116,7 @@ public bool IsReadOnly public EncryptionProperty Item(int index) { - return (EncryptionProperty)_props[index]; + return (EncryptionProperty)_props[index]!; } [System.Runtime.CompilerServices.IndexerName("ItemOf")] @@ -124,7 +124,7 @@ public EncryptionProperty this[int index] { get { - return (EncryptionProperty)((IList)this)[index]; + return (EncryptionProperty)((IList)this)[index]!; } set { @@ -133,7 +133,7 @@ public EncryptionProperty this[int index] } /// - object IList.this[int index] + object? IList.this[int index] { get { return _props[index]; } set diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcAncestralNamespaceContextManager.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcAncestralNamespaceContextManager.cs index 4c5738fcf69ff4..92b47b42f5c4e7 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcAncestralNamespaceContextManager.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcAncestralNamespaceContextManager.cs @@ -33,8 +33,8 @@ private void GatherNamespaceToRender(string nsPrefix, SortedList nsListToRender, } int rDepth; - XmlAttribute local = (XmlAttribute)nsLocallyDeclared[nsPrefix]; - XmlAttribute rAncestral = GetNearestRenderedNamespaceWithMatchingPrefix(nsPrefix, out rDepth); + XmlAttribute? local = (XmlAttribute?)nsLocallyDeclared[nsPrefix]; + XmlAttribute? rAncestral = GetNearestRenderedNamespaceWithMatchingPrefix(nsPrefix, out rDepth); if (local != null) { @@ -47,7 +47,7 @@ private void GatherNamespaceToRender(string nsPrefix, SortedList nsListToRender, else { int uDepth; - XmlAttribute uAncestral = GetNearestUnrenderedNamespaceWithMatchingPrefix(nsPrefix, out uDepth); + XmlAttribute? uAncestral = GetNearestUnrenderedNamespaceWithMatchingPrefix(nsPrefix, out uDepth); if (uAncestral != null && uDepth > rDepth && Utils.IsNonRedundantNamespaceDecl(uAncestral, rAncestral)) { nsListToRender.Add(uAncestral, null); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs index 4a846539bccccd..41d3a466d65075 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs @@ -45,7 +45,7 @@ internal ExcCanonicalXml(XmlNodeList nodeList, bool includeComments, string incl throw new ArgumentNullException(nameof(nodeList)); } - XmlDocument doc = Utils.GetOwnerDocument(nodeList); + XmlDocument? doc = Utils.GetOwnerDocument(nodeList); if (doc == null) throw new ArgumentException(nameof(nodeList)); @@ -69,7 +69,7 @@ internal byte[] GetDigestedBytes(HashAlgorithm hash) { _c14nDoc.WriteHash(hash, DocPosition.BeforeRootElement, _ancMgr); hash.TransformFinalBlock(Array.Empty(), 0, 0); - byte[] res = (byte[])hash.Hash.Clone(); + byte[] res = (byte[])hash.Hash!.Clone(); // reinitialize the hash so it is still usable after the call hash.Initialize(); return res; @@ -85,8 +85,8 @@ private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument do { - XmlNode currentNode = (XmlNode)elementList[index]; - XmlNode currentNodeCanonical = (XmlNode)elementListCanonical[index]; + XmlNode currentNode = (XmlNode)elementList[index]!; + XmlNode currentNodeCanonical = (XmlNode)elementListCanonical[index]!; XmlNodeList childNodes = currentNode.ChildNodes; XmlNodeList childNodesCanonical = currentNodeCanonical.ChildNodes; for (int i = 0; i < childNodes.Count; i++) @@ -96,17 +96,17 @@ private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument if (Utils.NodeInList(childNodes[i], nodeList)) { - MarkNodeAsIncluded(childNodesCanonical[i]); + MarkNodeAsIncluded(childNodesCanonical[i]!); } - XmlAttributeCollection attribNodes = childNodes[i].Attributes; + XmlAttributeCollection? attribNodes = childNodes[i]!.Attributes; if (attribNodes != null) { for (int j = 0; j < attribNodes.Count; j++) { if (Utils.NodeInList(attribNodes[j], nodeList)) { - MarkNodeAsIncluded(childNodesCanonical[i].Attributes.Item(j)); + MarkNodeAsIncluded(childNodesCanonical[i]!.Attributes!.Item(j)!); } } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs index 81bad806cd9bed..8b4db7b7674664 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs @@ -8,7 +8,7 @@ namespace System.Security.Cryptography.Xml { public class KeyInfo : IEnumerable { - private string _id; + private string? _id; private readonly ArrayList _keyInfoClauses; // @@ -24,7 +24,7 @@ public KeyInfo() // public properties // - public string Id + public string? Id { get { return _id; } set { _id = value; } @@ -49,7 +49,7 @@ internal XmlElement GetXml(XmlDocument xmlDocument) // Add all the clauses that go underneath it for (int i = 0; i < _keyInfoClauses.Count; ++i) { - XmlElement xmlElement = ((KeyInfoClause)_keyInfoClauses[i]).GetXml(xmlDocument); + XmlElement xmlElement = ((KeyInfoClause)_keyInfoClauses[i]!).GetXml(xmlDocument); if (xmlElement != null) { keyInfoElement.AppendChild(xmlElement); @@ -70,10 +70,10 @@ public void LoadXml(XmlElement value) if (!Utils.VerifyAttributes(keyInfoElement, "Id")) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "KeyInfo"); - XmlNode child = keyInfoElement.FirstChild; + XmlNode? child = keyInfoElement.FirstChild; while (child != null) { - XmlElement elem = child as XmlElement; + XmlElement? elem = child as XmlElement; if (elem != null) { // Create the right type of KeyInfoClause; we use a combination of the namespace and tag name (local name) @@ -81,14 +81,14 @@ public void LoadXml(XmlElement value) // Special-case handling for KeyValue -- we have to go one level deeper if (kicString == "http://www.w3.org/2000/09/xmldsig# KeyValue") { - if (!Utils.VerifyAttributes(elem, (string[])null)) + if (!Utils.VerifyAttributes(elem, (string[]?)null)) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "KeyInfo/KeyValue"); } XmlNodeList nodeList2 = elem.ChildNodes; foreach (XmlNode node2 in nodeList2) { - XmlElement elem2 = node2 as XmlElement; + XmlElement? elem2 = node2 as XmlElement; if (elem2 != null) { kicString += "/" + elem2.LocalName; @@ -97,7 +97,7 @@ public void LoadXml(XmlElement value) } } - KeyInfoClause keyInfoClause = CryptoHelpers.CreateFromName(kicString); + KeyInfoClause? keyInfoClause = CryptoHelpers.CreateFromName(kicString); // if we don't know what kind of KeyInfoClause we're looking at, use a generic KeyInfoNode: keyInfoClause ??= new KeyInfoNode(); @@ -138,7 +138,7 @@ public IEnumerator GetEnumerator(Type requestedObjectType) while (tempEnum.MoveNext()) { - tempObj = tempEnum.Current; + tempObj = tempEnum.Current!; if (requestedObjectType.Equals(tempObj.GetType())) requestedList.Add(tempObj); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoEncryptedKey.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoEncryptedKey.cs index 2ddeee99d99029..02321596fdb833 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoEncryptedKey.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoEncryptedKey.cs @@ -7,7 +7,7 @@ namespace System.Security.Cryptography.Xml { public class KeyInfoEncryptedKey : KeyInfoClause { - private EncryptedKey _encryptedKey; + private EncryptedKey? _encryptedKey; public KeyInfoEncryptedKey() { } @@ -16,7 +16,7 @@ public KeyInfoEncryptedKey(EncryptedKey encryptedKey) _encryptedKey = encryptedKey; } - public EncryptedKey EncryptedKey + public EncryptedKey? EncryptedKey { get { return _encryptedKey; } set { _encryptedKey = value; } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs index 7c39edd82a724d..46082bbb0aaeb0 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs @@ -7,7 +7,7 @@ namespace System.Security.Cryptography.Xml { public class KeyInfoName : KeyInfoClause { - private string _keyName; + private string? _keyName; // // public constructors @@ -15,7 +15,7 @@ public class KeyInfoName : KeyInfoClause public KeyInfoName() : this(null) { } - public KeyInfoName(string keyName) + public KeyInfoName(string? keyName) { Value = keyName; } @@ -24,7 +24,7 @@ public KeyInfoName(string keyName) // public properties // - public string Value + public string? Value { get { return _keyName; } set { _keyName = value; } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoNode.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoNode.cs index 87e7c19c335334..c0c47bd4cc318e 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoNode.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoNode.cs @@ -8,7 +8,7 @@ namespace System.Security.Cryptography.Xml // This is for generic, unknown nodes public class KeyInfoNode : KeyInfoClause { - private XmlElement _node; + private XmlElement? _node; // // public constructors @@ -25,7 +25,7 @@ public KeyInfoNode(XmlElement node) // public properties // - public XmlElement Value + public XmlElement? Value { get { return _node; } set { _node = value; } @@ -44,7 +44,7 @@ public override XmlElement GetXml() internal override XmlElement GetXml(XmlDocument xmlDocument) { - return xmlDocument.ImportNode(_node, true) as XmlElement; + return (xmlDocument.ImportNode(_node!, true) as XmlElement)!; } public override void LoadXml(XmlElement value) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs index 65b6853437e9a4..9f26e6f18668c5 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs @@ -7,8 +7,8 @@ namespace System.Security.Cryptography.Xml { public class KeyInfoRetrievalMethod : KeyInfoClause { - private string _uri; - private string _type; + private string? _uri; + private string? _type; // // public constructors @@ -16,7 +16,7 @@ public class KeyInfoRetrievalMethod : KeyInfoClause public KeyInfoRetrievalMethod() { } - public KeyInfoRetrievalMethod(string strUri) + public KeyInfoRetrievalMethod(string? strUri) { _uri = strUri; } @@ -31,13 +31,13 @@ public KeyInfoRetrievalMethod(string strUri, string typeName) // public properties // - public string Uri + public string? Uri { get { return _uri; } set { _uri = value; } } - public string Type + public string? Type { get { return _type; } set { _type = value; } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs index cfde60fc31ddb3..87bb9ac53ef7f8 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs @@ -12,15 +12,15 @@ namespace System.Security.Cryptography.Xml public class KeyInfoX509Data : KeyInfoClause { // An array of certificates representing the certificate chain - private ArrayList _certificates; + private ArrayList? _certificates; // An array of issuer serial structs - private ArrayList _issuerSerials; + private ArrayList? _issuerSerials; // An array of SKIs - private ArrayList _subjectKeyIds; + private ArrayList? _subjectKeyIds; // An array of subject names - private ArrayList _subjectNames; + private ArrayList? _subjectNames; // A raw byte data representing a certificate revocation list - private byte[] _CRL; + private byte[]? _CRL; // // public constructors @@ -97,7 +97,7 @@ public KeyInfoX509Data(X509Certificate cert, X509IncludeOption includeOption) // public properties // - public ArrayList Certificates + public ArrayList? Certificates { get { return _certificates; } } @@ -115,7 +115,7 @@ public void AddCertificate(X509Certificate certificate) _certificates.Add(x509); } - public ArrayList SubjectKeyIds + public ArrayList? SubjectKeyIds { get { return _subjectKeyIds; } } @@ -132,7 +132,7 @@ public void AddSubjectKeyId(string subjectKeyId) _subjectKeyIds.Add(Utils.DecodeHexString(subjectKeyId)); } - public ArrayList SubjectNames + public ArrayList? SubjectNames { get { return _subjectNames; } } @@ -143,7 +143,7 @@ public void AddSubjectName(string subjectName) _subjectNames.Add(subjectName); } - public ArrayList IssuerSerials + public ArrayList? IssuerSerials { get { return _issuerSerials; } } @@ -171,7 +171,7 @@ internal void InternalAddIssuerSerial(string issuerName, string serialNumber) _issuerSerials.Add(Utils.CreateX509IssuerSerial(issuerName, serialNumber)); } - public byte[] CRL + public byte[]? CRL { get { return _CRL; } set { _CRL = value; } @@ -270,11 +270,11 @@ public override void LoadXml(XmlElement element) XmlNamespaceManager nsm = new XmlNamespaceManager(element.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); - XmlNodeList x509IssuerSerialNodes = element.SelectNodes("ds:X509IssuerSerial", nsm); - XmlNodeList x509SKINodes = element.SelectNodes("ds:X509SKI", nsm); - XmlNodeList x509SubjectNameNodes = element.SelectNodes("ds:X509SubjectName", nsm); - XmlNodeList x509CertificateNodes = element.SelectNodes("ds:X509Certificate", nsm); - XmlNodeList x509CRLNodes = element.SelectNodes("ds:X509CRL", nsm); + XmlNodeList x509IssuerSerialNodes = element.SelectNodes("ds:X509IssuerSerial", nsm)!; + XmlNodeList x509SKINodes = element.SelectNodes("ds:X509SKI", nsm)!; + XmlNodeList x509SubjectNameNodes = element.SelectNodes("ds:X509SubjectName", nsm)!; + XmlNodeList x509CertificateNodes = element.SelectNodes("ds:X509Certificate", nsm)!; + XmlNodeList x509CRLNodes = element.SelectNodes("ds:X509CRL", nsm)!; if ((x509CRLNodes.Count == 0 && x509IssuerSerialNodes.Count == 0 && x509SKINodes.Count == 0 && x509SubjectNameNodes.Count == 0 && x509CertificateNodes.Count == 0)) // Bad X509Data tag, or Empty tag @@ -284,12 +284,12 @@ public override void LoadXml(XmlElement element) Clear(); if (x509CRLNodes.Count != 0) - _CRL = Convert.FromBase64String(Utils.DiscardWhiteSpaces(x509CRLNodes.Item(0).InnerText)); + _CRL = Convert.FromBase64String(Utils.DiscardWhiteSpaces(x509CRLNodes.Item(0)!.InnerText)); foreach (XmlNode issuerSerialNode in x509IssuerSerialNodes) { - XmlNode x509IssuerNameNode = issuerSerialNode.SelectSingleNode("ds:X509IssuerName", nsm); - XmlNode x509SerialNumberNode = issuerSerialNode.SelectSingleNode("ds:X509SerialNumber", nsm); + XmlNode? x509IssuerNameNode = issuerSerialNode.SelectSingleNode("ds:X509IssuerName", nsm); + XmlNode? x509SerialNumberNode = issuerSerialNode.SelectSingleNode("ds:X509SerialNumber", nsm); if (x509IssuerNameNode == null || x509SerialNumberNode == null) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "IssuerSerial"); InternalAddIssuerSerial(x509IssuerNameNode.InnerText.Trim(), x509SerialNumberNode.InnerText.Trim()); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/MyXmlDocument.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/MyXmlDocument.cs index 808a3bbbd777f8..281c64f6929e9d 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/MyXmlDocument.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/MyXmlDocument.cs @@ -7,7 +7,7 @@ namespace System.Security.Cryptography.Xml { internal sealed class MyXmlDocument : XmlDocument { - protected override XmlAttribute CreateDefaultAttribute(string prefix, string localName, string namespaceURI) + protected override XmlAttribute CreateDefaultAttribute(string? prefix, string localName, string? namespaceURI) { return CreateAttribute(prefix, localName, namespaceURI); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/NamespaceFrame.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/NamespaceFrame.cs index 1af976d8fb8a39..639f25e15796bc 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/NamespaceFrame.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/NamespaceFrame.cs @@ -21,9 +21,9 @@ internal void AddRendered(XmlAttribute attr) _rendered.Add(Utils.GetNamespacePrefix(attr), attr); } - internal XmlAttribute GetRendered(string nsPrefix) + internal XmlAttribute? GetRendered(string nsPrefix) { - return (XmlAttribute)_rendered[nsPrefix]; + return (XmlAttribute?)_rendered[nsPrefix]; } internal void AddUnrendered(XmlAttribute attr) @@ -31,9 +31,9 @@ internal void AddUnrendered(XmlAttribute attr) _unrendered.Add(Utils.GetNamespacePrefix(attr), attr); } - internal XmlAttribute GetUnrendered(string nsPrefix) + internal XmlAttribute? GetUnrendered(string nsPrefix) { - return (XmlAttribute)_unrendered[nsPrefix]; + return (XmlAttribute?)_unrendered[nsPrefix]; } internal Hashtable GetUnrendered() diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/NamespaceSortOrder.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/NamespaceSortOrder.cs index 1e998ef7e88e20..7a0766dbdc3fd7 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/NamespaceSortOrder.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/NamespaceSortOrder.cs @@ -10,10 +10,10 @@ internal sealed class NamespaceSortOrder : IComparer { internal NamespaceSortOrder() { } - public int Compare(object a, object b) + public int Compare(object? a, object? b) { - XmlNode nodeA = a as XmlNode; - XmlNode nodeB = b as XmlNode; + XmlNode? nodeA = a as XmlNode; + XmlNode? nodeB = b as XmlNode; if ((nodeA == null) || (nodeB == null)) throw new ArgumentException(); bool nodeAdefault = Utils.IsDefaultNamespaceNode(nodeA); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs index 44b524db5f9956..60969d497d56d0 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs @@ -66,11 +66,11 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) XmlElement rsaKeyValueElement = xmlDocument.CreateElement(RSAKeyValueElementName, SignedXml.XmlDsigNamespaceUrl); XmlElement modulusElement = xmlDocument.CreateElement(ModulusElementName, SignedXml.XmlDsigNamespaceUrl); - modulusElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(rsaParams.Modulus))); + modulusElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(rsaParams.Modulus!))); rsaKeyValueElement.AppendChild(modulusElement); XmlElement exponentElement = xmlDocument.CreateElement(ExponentElementName, SignedXml.XmlDsigNamespaceUrl); - exponentElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(rsaParams.Exponent))); + exponentElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(rsaParams.Exponent!))); rsaKeyValueElement.AppendChild(exponentElement); keyValueElement.AppendChild(rsaKeyValueElement); @@ -110,7 +110,7 @@ public override void LoadXml(XmlElement value) XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(value.OwnerDocument.NameTable); xmlNamespaceManager.AddNamespace(xmlDsigNamespacePrefix, SignedXml.XmlDsigNamespaceUrl); - XmlNode rsaKeyValueElement = value.SelectSingleNode($"{xmlDsigNamespacePrefix}:{RSAKeyValueElementName}", xmlNamespaceManager); + XmlNode? rsaKeyValueElement = value.SelectSingleNode($"{xmlDsigNamespacePrefix}:{RSAKeyValueElementName}", xmlNamespaceManager); if (rsaKeyValueElement == null) { throw new CryptographicException(SR.Format(SR.MustContainChildElement, KeyValueElementName, RSAKeyValueElementName)); @@ -120,8 +120,8 @@ public override void LoadXml(XmlElement value) { Key.ImportParameters(new RSAParameters { - Modulus = Convert.FromBase64String(rsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{ModulusElementName}", xmlNamespaceManager).InnerText), - Exponent = Convert.FromBase64String(rsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{ExponentElementName}", xmlNamespaceManager).InnerText) + Modulus = Convert.FromBase64String(rsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{ModulusElementName}", xmlNamespaceManager)!.InnerText), + Exponent = Convert.FromBase64String(rsaKeyValueElement.SelectSingleNode($"{xmlDsigNamespacePrefix}:{ExponentElementName}", xmlNamespaceManager)!.InnerText) }); } catch (Exception ex) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SignatureDescription.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SignatureDescription.cs index f19884fbc88609..9c48c3172d45fe 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SignatureDescription.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SignatureDescription.cs @@ -15,17 +15,17 @@ public RSAPKCS1SignatureDescription(string hashAlgorithmName) public sealed override AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key) { - var item = (AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(DeformatterAlgorithm); + var item = (AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(DeformatterAlgorithm!)!; item.SetKey(key); - item.SetHashAlgorithm(DigestAlgorithm); + item.SetHashAlgorithm(DigestAlgorithm!); return item; } public sealed override AsymmetricSignatureFormatter CreateFormatter(AsymmetricAlgorithm key) { - var item = (AsymmetricSignatureFormatter)CryptoConfig.CreateFromName(FormatterAlgorithm); + var item = (AsymmetricSignatureFormatter)CryptoConfig.CreateFromName(FormatterAlgorithm!)!; item.SetKey(key); - item.SetHashAlgorithm(DigestAlgorithm); + item.SetHashAlgorithm(DigestAlgorithm!); return item; } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs index 05c7625170e5b5..801dae7f9e9022 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs @@ -4,6 +4,7 @@ using System.IO; using System.Net; using System.Xml; +using System.Diagnostics.CodeAnalysis; namespace System.Security.Cryptography.Xml { @@ -11,18 +12,18 @@ public class Reference { internal const string DefaultDigestMethod = SignedXml.XmlDsigSHA256Url; - private string _id; - private string _uri; - private string _type; + private string? _id; + private string? _uri; + private string? _type; private TransformChain _transformChain; private string _digestMethod; - private byte[] _digestValue; - private HashAlgorithm _hashAlgorithm; - private readonly object _refTarget; + private byte[]? _digestValue; + private HashAlgorithm? _hashAlgorithm; + private readonly object? _refTarget; private readonly ReferenceTargetType _refTargetType; - private XmlElement _cachedXml; - private SignedXml _signedXml; - internal CanonicalXmlNodeList _namespaces; + private XmlElement? _cachedXml; + private SignedXml? _signedXml; + internal CanonicalXmlNodeList? _namespaces; // // public constructors @@ -46,7 +47,7 @@ public Reference(Stream stream) _digestMethod = DefaultDigestMethod; } - public Reference(string uri) + public Reference(string? uri) { _transformChain = new TransformChain(); _refTarget = uri; @@ -69,13 +70,13 @@ internal Reference(XmlElement element) // public properties // - public string Id + public string? Id { get { return _id; } set { _id = value; } } - public string Uri + public string? Uri { get { return _uri; } set @@ -85,7 +86,7 @@ public string Uri } } - public string Type + public string? Type { get { return _type; } set @@ -105,7 +106,7 @@ public string DigestMethod } } - public byte[] DigestValue + public byte[]? DigestValue { get { return _digestValue; } set @@ -125,6 +126,7 @@ public TransformChain TransformChain } } + [MemberNotNullWhen(true, nameof(_cachedXml))] internal bool CacheValid { get @@ -133,7 +135,7 @@ internal bool CacheValid } } - internal SignedXml SignedXml + internal SignedXml? SignedXml { get { return _signedXml; } set { _signedXml = value; } @@ -153,7 +155,7 @@ internal ReferenceTargetType ReferenceTargetType public XmlElement GetXml() { - if (CacheValid) return (_cachedXml); + if (CacheValid) return _cachedXml; XmlDocument document = new XmlDocument(); document.PreserveWhitespace = true; @@ -188,13 +190,13 @@ internal XmlElement GetXml(XmlDocument document) if (DigestValue == null) { - if (_hashAlgorithm.Hash == null) + if (_hashAlgorithm!.Hash == null) throw new CryptographicException(SR.Cryptography_Xml_DigestValueRequired); DigestValue = _hashAlgorithm.Hash; } XmlElement digestValueElement = document.CreateElement("DigestValue", SignedXml.XmlDsigNamespaceUrl); - digestValueElement.AppendChild(document.CreateTextNode(Convert.ToBase64String(_digestValue))); + digestValueElement.AppendChild(document.CreateTextNode(Convert.ToBase64String(_digestValue!))); referenceElement.AppendChild(digestValueElement); return referenceElement; @@ -219,7 +221,7 @@ public void LoadXml(XmlElement value) // Transforms bool hasTransforms = false; TransformChain = new TransformChain(); - XmlNodeList transformsNodes = value.SelectNodes("ds:Transforms", nsm); + XmlNodeList? transformsNodes = value.SelectNodes("ds:Transforms", nsm); if (transformsNodes != null && transformsNodes.Count != 0) { if (transformsNodes.Count > 1) @@ -227,15 +229,15 @@ public void LoadXml(XmlElement value) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms"); } hasTransforms = true; - XmlElement transformsElement = transformsNodes[0] as XmlElement; - if (!Utils.VerifyAttributes(transformsElement, (string[])null)) + XmlElement transformsElement = (transformsNodes[0] as XmlElement)!; + if (!Utils.VerifyAttributes(transformsElement, (string[]?)null)) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms"); } - XmlNodeList transformNodes = transformsElement.SelectNodes("ds:Transform", nsm); + XmlNodeList? transformNodes = transformsElement.SelectNodes("ds:Transform", nsm); if (transformNodes != null) { - if (transformNodes.Count != transformsElement.SelectNodes("*").Count) + if (transformNodes.Count != transformsElement.SelectNodes("*")!.Count) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/Transforms"); } @@ -245,13 +247,13 @@ public void LoadXml(XmlElement value) } foreach (XmlNode transformNode in transformNodes) { - XmlElement transformElement = transformNode as XmlElement; - string algorithm = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); + XmlElement transformElement = (transformNode as XmlElement)!; + string? algorithm = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); if (algorithm == null || !Utils.VerifyAttributes(transformElement, "Algorithm")) { throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); } - Transform transform = CryptoHelpers.CreateFromName(algorithm); + Transform? transform = CryptoHelpers.CreateFromName(algorithm); if (transform == null) { throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); @@ -265,15 +267,15 @@ public void LoadXml(XmlElement value) { // Walk back to the Signature tag. Find the nearest signature ancestor // Signature-->SignedInfo-->Reference-->Transforms-->Transform - XmlNode signatureTag = transformElement.SelectSingleNode("ancestor::ds:Signature[1]", nsm); + XmlNode? signatureTag = transformElement.SelectSingleNode("ancestor::ds:Signature[1]", nsm); // Resolve the reference to get starting point for position calculation. - XmlNode referenceTarget = + XmlNode? referenceTarget = _uri.Length == 0 ? transformElement.OwnerDocument - : SignedXml.GetIdElement(transformElement.OwnerDocument, Utils.GetIdFromLocalUri(_uri, out bool _)); + : SignedXml!.GetIdElement(transformElement.OwnerDocument, Utils.GetIdFromLocalUri(_uri, out bool _)); - XmlNodeList signatureList = referenceTarget?.SelectNodes(".//ds:Signature", nsm); + XmlNodeList? signatureList = referenceTarget?.SelectNodes(".//ds:Signature", nsm); if (signatureList != null) { int position = 0; @@ -293,26 +295,26 @@ public void LoadXml(XmlElement value) } // DigestMethod - XmlNodeList digestMethodNodes = value.SelectNodes("ds:DigestMethod", nsm); + XmlNodeList? digestMethodNodes = value.SelectNodes("ds:DigestMethod", nsm); if (digestMethodNodes == null || digestMethodNodes.Count == 0 || digestMethodNodes.Count > 1) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestMethod"); - XmlElement digestMethodElement = digestMethodNodes[0] as XmlElement; - _digestMethod = Utils.GetAttribute(digestMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); + XmlElement digestMethodElement = (digestMethodNodes[0] as XmlElement)!; + _digestMethod = Utils.GetAttribute(digestMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl)!; if (_digestMethod == null || !Utils.VerifyAttributes(digestMethodElement, "Algorithm")) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestMethod"); // DigestValue - XmlNodeList digestValueNodes = value.SelectNodes("ds:DigestValue", nsm); + XmlNodeList? digestValueNodes = value.SelectNodes("ds:DigestValue", nsm); if (digestValueNodes == null || digestValueNodes.Count == 0 || digestValueNodes.Count > 1) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestValue"); - XmlElement digestValueElement = digestValueNodes[0] as XmlElement; + XmlElement digestValueElement = (digestValueNodes[0] as XmlElement)!; _digestValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(digestValueElement.InnerText)); - if (!Utils.VerifyAttributes(digestValueElement, (string[])null)) + if (!Utils.VerifyAttributes(digestValueElement, (string[]?)null)) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference/DigestValue"); // Verify that there aren't any extra nodes that aren't allowed int expectedChildNodeCount = hasTransforms ? 3 : 2; - if (value.SelectNodes("*").Count != expectedChildNodeCount) + if (value.SelectNodes("*")!.Count != expectedChildNodeCount) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Reference"); // cache the Xml @@ -337,7 +339,7 @@ internal void UpdateHashValue(XmlDocument document, CanonicalXmlNodeList refList // What we want to do is pump the input through the TransformChain and then // hash the output of the chain document is the document context for resolving relative references - internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList) + internal byte[]? CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList) { // refList is a list of elements that might be targets of references // Now's the time to create our hashing algorithm @@ -347,11 +349,11 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re // Let's go get the target. string baseUri = (document == null ? System.Environment.CurrentDirectory + "\\" : document.BaseURI); - Stream hashInputStream = null; - WebResponse response = null; - Stream inputStream = null; - XmlResolver resolver = null; - byte[] hashval = null; + Stream? hashInputStream = null; + WebResponse? response = null; + Stream? inputStream = null; + XmlResolver? resolver = null; + byte[] hashval; try { @@ -359,8 +361,8 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re { case ReferenceTargetType.Stream: // This is the easiest case. We already have a stream, so just pump it through the TransformChain - resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : XmlResolverHelper.GetThrowingResolver()); - hashInputStream = TransformChain.TransformToOctetStream((Stream)_refTarget, resolver, baseUri); + resolver = (SignedXml!.ResolverSet ? SignedXml._xmlResolver : XmlResolverHelper.GetThrowingResolver()); + hashInputStream = TransformChain.TransformToOctetStream((Stream?)_refTarget, resolver, baseUri); break; case ReferenceTargetType.UriReference: // Second-easiest case -- dereference the URI & pump through the TransformChain @@ -369,10 +371,10 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re if (_uri == null) { // We need to create a DocumentNavigator out of the XmlElement - resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : XmlResolverHelper.GetThrowingResolver()); + resolver = (SignedXml!.ResolverSet ? SignedXml._xmlResolver : XmlResolverHelper.GetThrowingResolver()); // In the case of a Uri-less reference, we will simply pass null to the transform chain. // The first transform in the chain is expected to know how to retrieve the data to hash. - hashInputStream = TransformChain.TransformToOctetStream((Stream)null, resolver, baseUri); + hashInputStream = TransformChain.TransformToOctetStream((Stream?)null, resolver!, baseUri); } else if (_uri.Length == 0) { @@ -382,8 +384,8 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re throw new CryptographicException(SR.Format(SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri)); // Normalize the containing document - resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : XmlResolverHelper.GetThrowingResolver()); - XmlDocument docWithNoComments = Utils.DiscardComments(Utils.PreProcessDocumentInput(document, resolver, baseUri)); + resolver = (SignedXml!.ResolverSet ? SignedXml._xmlResolver : XmlResolverHelper.GetThrowingResolver()); + XmlDocument docWithNoComments = Utils.DiscardComments(Utils.PreProcessDocumentInput(document, resolver!, baseUri)); hashInputStream = TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else if (_uri[0] == '#') @@ -398,12 +400,12 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re throw new CryptographicException(SR.Format(SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri)); // We should not discard comments here!!! - resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : XmlResolverHelper.GetThrowingResolver()); - hashInputStream = TransformChain.TransformToOctetStream(Utils.PreProcessDocumentInput(document, resolver, baseUri), resolver, baseUri); + resolver = (SignedXml!.ResolverSet ? SignedXml._xmlResolver : XmlResolverHelper.GetThrowingResolver()); + hashInputStream = TransformChain.TransformToOctetStream(Utils.PreProcessDocumentInput(document, resolver!, baseUri), resolver, baseUri); break; } - XmlElement elem = SignedXml.GetIdElement(document, idref); + XmlElement? elem = SignedXml!.GetIdElement(document, idref); if (elem != null) _namespaces = Utils.GetPropagatedAttributes(elem.ParentNode as XmlElement); @@ -414,12 +416,12 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re { foreach (XmlNode node in refList) { - XmlElement tempElem = node as XmlElement; + XmlElement? tempElem = node as XmlElement; if ((tempElem != null) && (Utils.HasAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl)) - && (Utils.GetAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl).Equals(idref))) + && (Utils.GetAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl)!.Equals(idref))) { elem = tempElem; - if (_signedXml._context != null) + if (_signedXml!._context != null) _namespaces = Utils.GetPropagatedAttributes(_signedXml._context); break; } @@ -430,9 +432,9 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re if (elem == null) throw new CryptographicException(SR.Cryptography_Xml_InvalidReference); - XmlDocument normDocument = Utils.PreProcessElementInput(elem, resolver, baseUri); + XmlDocument normDocument = Utils.PreProcessElementInput(elem, resolver!, baseUri); // Add the propagated attributes - Utils.AddNamespaces(normDocument.DocumentElement, _namespaces); + Utils.AddNamespaces(normDocument.DocumentElement!, _namespaces); resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : XmlResolverHelper.GetThrowingResolver()); if (discardComments) @@ -454,8 +456,8 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re break; case ReferenceTargetType.XmlElement: // We need to create a DocumentNavigator out of the XmlElement - resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : XmlResolverHelper.GetThrowingResolver()); - hashInputStream = TransformChain.TransformToOctetStream(Utils.PreProcessElementInput((XmlElement)_refTarget, resolver, baseUri), resolver, baseUri); + resolver = (SignedXml!.ResolverSet ? SignedXml._xmlResolver : XmlResolverHelper.GetThrowingResolver()); + hashInputStream = TransformChain.TransformToOctetStream(Utils.PreProcessElementInput((XmlElement)_refTarget!, resolver!, baseUri), resolver, baseUri); break; default: throw new CryptographicException(SR.Cryptography_Xml_UriNotResolved, _uri); @@ -463,7 +465,7 @@ internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList re // Compute the new hash value hashInputStream = SignedXmlDebugLog.LogReferenceData(this, hashInputStream); - hashval = _hashAlgorithm.ComputeHash(hashInputStream); + hashval = _hashAlgorithm.ComputeHash(hashInputStream!); } finally { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs index ed01208d6d7384..a1c76e80507da8 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs @@ -24,7 +24,8 @@ public int Count get { return _references.Count; } } - public int Add(object value) +#pragma warning disable CS8995 // Nullable type 'object?' is null-checked and will throw if null. + public int Add(object? value) { if (value is null) { @@ -36,23 +37,24 @@ public int Add(object value) return _references.Add(value); } +#pragma warning restore public void Clear() { _references.Clear(); } - public bool Contains(object value) + public bool Contains(object? value) { return _references.Contains(value); } - public int IndexOf(object value) + public int IndexOf(object? value) { return _references.IndexOf(value); } - public void Insert(int index, object value) + public void Insert(int index, object? value) { if (value is null) { @@ -64,8 +66,9 @@ public void Insert(int index, object value) _references.Insert(index, value); } +#pragma warning restore - public void Remove(object value) + public void Remove(object? value) { _references.Remove(value); } @@ -75,9 +78,9 @@ public void RemoveAt(int index) _references.RemoveAt(index); } - public EncryptedReference Item(int index) + public EncryptedReference? Item(int index) { - return (EncryptedReference)_references[index]; + return (EncryptedReference?)_references[index]; } [System.Runtime.CompilerServices.IndexerName("ItemOf")] @@ -85,7 +88,7 @@ public EncryptedReference this[int index] { get { - return Item(index); + return Item(index)!; } set { @@ -94,7 +97,7 @@ public EncryptedReference this[int index] } /// - object IList.this[int index] + object? IList.this[int index] { get { return _references[index]; } set diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs index e88334f9ee1a68..d227ea020a1b3b 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs @@ -8,16 +8,16 @@ namespace System.Security.Cryptography.Xml { public class Signature { - private string _id; - private SignedInfo _signedInfo; - private byte[] _signatureValue; - private string _signatureValueId; - private KeyInfo _keyInfo; + private string? _id; + private SignedInfo? _signedInfo; + private byte[]? _signatureValue; + private string? _signatureValueId; + private KeyInfo? _keyInfo; private IList _embeddedObjects; private readonly CanonicalXmlNodeList _referencedItems; - private SignedXml _signedXml; + private SignedXml? _signedXml; - internal SignedXml SignedXml + internal SignedXml? SignedXml { get { return _signedXml; } set { _signedXml = value; } @@ -37,13 +37,13 @@ public Signature() // public properties // - public string Id + public string? Id { get { return _id; } set { _id = value; } } - public SignedInfo SignedInfo + public SignedInfo? SignedInfo { get { return _signedInfo; } set @@ -54,7 +54,7 @@ public SignedInfo SignedInfo } } - public byte[] SignatureValue + public byte[]? SignatureValue { get { return _signatureValue; } set { _signatureValue = value; } @@ -118,7 +118,7 @@ internal XmlElement GetXml(XmlDocument document) // Add the Objects foreach (object obj in _embeddedObjects) { - DataObject dataObj = obj as DataObject; + DataObject? dataObj = obj as DataObject; if (dataObj != null) { signatureElement.AppendChild(dataObj.GetXml(document)); @@ -150,20 +150,20 @@ public void LoadXml(XmlElement value) int expectedChildNodes = 0; // SignedInfo - XmlNodeList signedInfoNodes = signatureElement.SelectNodes("ds:SignedInfo", nsm); + XmlNodeList? signedInfoNodes = signatureElement.SelectNodes("ds:SignedInfo", nsm); if (signedInfoNodes == null || signedInfoNodes.Count == 0 || signedInfoNodes.Count > 1) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo"); - XmlElement signedInfoElement = signedInfoNodes[0] as XmlElement; + XmlElement signedInfoElement = (signedInfoNodes[0] as XmlElement)!; expectedChildNodes += signedInfoNodes.Count; SignedInfo = new SignedInfo(); SignedInfo.LoadXml(signedInfoElement); // SignatureValue - XmlNodeList signatureValueNodes = signatureElement.SelectNodes("ds:SignatureValue", nsm); + XmlNodeList? signatureValueNodes = signatureElement.SelectNodes("ds:SignatureValue", nsm); if (signatureValueNodes == null || signatureValueNodes.Count == 0 || signatureValueNodes.Count > 1) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignatureValue"); - XmlElement signatureValueElement = signatureValueNodes[0] as XmlElement; + XmlElement signatureValueElement = (signatureValueNodes[0] as XmlElement)!; expectedChildNodes += signatureValueNodes.Count; _signatureValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(signatureValueElement.InnerText)); _signatureValueId = Utils.GetAttribute(signatureValueElement, "Id", SignedXml.XmlDsigNamespaceUrl); @@ -171,7 +171,7 @@ public void LoadXml(XmlElement value) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignatureValue"); // KeyInfo - optional single element - XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm); + XmlNodeList? keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm); _keyInfo = new KeyInfo(); if (keyInfoNodes != null) { @@ -181,7 +181,7 @@ public void LoadXml(XmlElement value) } foreach (XmlNode node in keyInfoNodes) { - XmlElement keyInfoElement = node as XmlElement; + XmlElement? keyInfoElement = node as XmlElement; if (keyInfoElement != null) _keyInfo.LoadXml(keyInfoElement); } @@ -189,13 +189,13 @@ public void LoadXml(XmlElement value) } // Object - zero or more elements allowed - XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm); + XmlNodeList? objectNodes = signatureElement.SelectNodes("ds:Object", nsm); _embeddedObjects.Clear(); if (objectNodes != null) { foreach (XmlNode node in objectNodes) { - XmlElement objectElement = node as XmlElement; + XmlElement? objectElement = node as XmlElement; if (objectElement != null) { DataObject dataObj = new DataObject(); @@ -207,7 +207,7 @@ public void LoadXml(XmlElement value) } // Select all elements that have Id attributes - XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm); + XmlNodeList? nodeList = signatureElement.SelectNodes("//*[@Id]", nsm); if (nodeList != null) { foreach (XmlNode node in nodeList) @@ -216,7 +216,7 @@ public void LoadXml(XmlElement value) } } // Verify that there aren't any extra nodes that aren't allowed - if (signatureElement.SelectNodes("*").Count != expectedChildNodes) + if (signatureElement.SelectNodes("*")!.Count != expectedChildNodes) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Signature"); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs index 6cac8c541c3b0b..8941e4635b62b6 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs @@ -2,22 +2,23 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.Xml; namespace System.Security.Cryptography.Xml { public class SignedInfo : ICollection { - private string _id; - private string _canonicalizationMethod; - private string _signatureMethod; - private string _signatureLength; + private string? _id; + private string? _canonicalizationMethod; + private string? _signatureMethod; + private string? _signatureLength; private readonly ArrayList _references; - private XmlElement _cachedXml; - private SignedXml _signedXml; - private Transform _canonicalizationMethodTransform; + private XmlElement? _cachedXml; + private SignedXml? _signedXml; + private Transform? _canonicalizationMethodTransform; - internal SignedXml SignedXml + internal SignedXml? SignedXml { get { return _signedXml; } set { _signedXml = value; } @@ -62,7 +63,7 @@ public object SyncRoot // public properties // - public string Id + public string? Id { get { return _id; } set @@ -72,6 +73,7 @@ public string Id } } + [AllowNull] public string CanonicalizationMethod { get @@ -104,7 +106,7 @@ public Transform CanonicalizationMethodObject } } - public string SignatureMethod + public string? SignatureMethod { get { return _signatureMethod; } set @@ -114,7 +116,7 @@ public string SignatureMethod } } - public string SignatureLength + public string? SignatureLength { get { return _signatureLength; } set @@ -129,6 +131,7 @@ public ArrayList References get { return _references; } } + [MemberNotNullWhen(true, nameof(_cachedXml))] internal bool CacheValid { get @@ -190,7 +193,7 @@ internal XmlElement GetXml(XmlDocument document) for (int i = 0; i < _references.Count; ++i) { - Reference reference = (Reference)_references[i]; + Reference reference = (Reference)_references[i]!; signedInfoElement.AppendChild(reference.GetXml(document)); } @@ -219,10 +222,10 @@ public void LoadXml(XmlElement value) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo"); // CanonicalizationMethod -- must be present - XmlNodeList canonicalizationMethodNodes = signedInfoElement.SelectNodes("ds:CanonicalizationMethod", nsm); + XmlNodeList? canonicalizationMethodNodes = signedInfoElement.SelectNodes("ds:CanonicalizationMethod", nsm); if (canonicalizationMethodNodes == null || canonicalizationMethodNodes.Count == 0 || canonicalizationMethodNodes.Count > 1) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo/CanonicalizationMethod"); - XmlElement canonicalizationMethodElement = canonicalizationMethodNodes.Item(0) as XmlElement; + XmlElement canonicalizationMethodElement = (canonicalizationMethodNodes.Item(0) as XmlElement)!; expectedChildNodes += canonicalizationMethodNodes.Count; _canonicalizationMethod = Utils.GetAttribute(canonicalizationMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); if (_canonicalizationMethod == null || !Utils.VerifyAttributes(canonicalizationMethodElement, "Algorithm")) @@ -232,17 +235,17 @@ public void LoadXml(XmlElement value) CanonicalizationMethodObject.LoadInnerXml(canonicalizationMethodElement.ChildNodes); // SignatureMethod -- must be present - XmlNodeList signatureMethodNodes = signedInfoElement.SelectNodes("ds:SignatureMethod", nsm); + XmlNodeList? signatureMethodNodes = signedInfoElement.SelectNodes("ds:SignatureMethod", nsm); if (signatureMethodNodes == null || signatureMethodNodes.Count == 0 || signatureMethodNodes.Count > 1) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo/SignatureMethod"); - XmlElement signatureMethodElement = signatureMethodNodes.Item(0) as XmlElement; + XmlElement signatureMethodElement = (signatureMethodNodes.Item(0) as XmlElement)!; expectedChildNodes += signatureMethodNodes.Count; _signatureMethod = Utils.GetAttribute(signatureMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); if (_signatureMethod == null || !Utils.VerifyAttributes(signatureMethodElement, "Algorithm")) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo/SignatureMethod"); // Now get the output length if we are using a MAC algorithm - XmlElement signatureLengthElement = signatureMethodElement.SelectSingleNode("ds:HMACOutputLength", nsm) as XmlElement; + XmlElement? signatureLengthElement = signatureMethodElement.SelectSingleNode("ds:HMACOutputLength", nsm) as XmlElement; if (signatureLengthElement != null) _signatureLength = signatureLengthElement.InnerXml; @@ -250,7 +253,7 @@ public void LoadXml(XmlElement value) _references.Clear(); // Reference - 0 or more - XmlNodeList referenceNodes = signedInfoElement.SelectNodes("ds:Reference", nsm); + XmlNodeList? referenceNodes = signedInfoElement.SelectNodes("ds:Reference", nsm); if (referenceNodes != null) { if (referenceNodes.Count > Utils.MaxReferencesPerSignedInfo) @@ -259,14 +262,14 @@ public void LoadXml(XmlElement value) } foreach (XmlNode node in referenceNodes) { - XmlElement referenceElement = node as XmlElement; + XmlElement referenceElement = (node as XmlElement)!; Reference reference = new Reference(); AddReference(reference); reference.LoadXml(referenceElement); } expectedChildNodes += referenceNodes.Count; // Verify that there aren't any extra nodes that aren't allowed - if (signedInfoElement.SelectNodes("*").Count != expectedChildNodes) + if (signedInfoElement.SelectNodes("*")!.Count != expectedChildNodes) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo"); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs index 5d722d0f180f50..0a3a3510cb8ca3 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs @@ -4,6 +4,8 @@ using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Security.Cryptography.X509Certificates; using System.Xml; @@ -13,28 +15,28 @@ namespace System.Security.Cryptography.Xml public class SignedXml { protected Signature m_signature; - protected string m_strSigningKeyName; + protected string? m_strSigningKeyName; - private AsymmetricAlgorithm _signingKey; - private XmlDocument _containingDocument; - private IEnumerator _keyInfoEnum; - private X509Certificate2Collection _x509Collection; - private IEnumerator _x509Enum; + private AsymmetricAlgorithm? _signingKey; + private XmlDocument? _containingDocument; + private IEnumerator? _keyInfoEnum; + private X509Certificate2Collection? _x509Collection; + private IEnumerator? _x509Enum; - private bool[] _refProcessed; - private int[] _refLevelCache; + private bool[]? _refProcessed; + private int[]? _refLevelCache; - internal XmlResolver _xmlResolver; - internal XmlElement _context; + internal XmlResolver? _xmlResolver; + internal XmlElement? _context; private bool _bResolverSet; private Func _signatureFormatValidator = DefaultSignatureFormatValidator; private Collection _safeCanonicalizationMethods; // Built in canonicalization algorithm URIs - private static IList s_knownCanonicalizationMethods; + private static IList? s_knownCanonicalizationMethods; // Built in transform algorithm URIs (excluding canonicalization URIs) - private static IList s_defaultSafeTransformMethods; + private static IList? s_defaultSafeTransformMethods; // additional HMAC Url identifiers private const string XmlDsigMoreHMACMD5Url = "http://www.w3.org/2001/04/xmldsig-more#hmac-md5"; @@ -44,7 +46,7 @@ public class SignedXml private const string XmlDsigMoreHMACRIPEMD160Url = "http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160"; // defines the XML encryption processing rules - private EncryptedXml _exml; + private EncryptedXml? _exml; // // public constant Url identifiers most frequently used within the XML Signature classes @@ -110,7 +112,9 @@ public SignedXml(XmlElement elem) Initialize(elem); } - private void Initialize(XmlElement element) + [MemberNotNull(nameof(m_signature))] + [MemberNotNull(nameof(_safeCanonicalizationMethods))] + private void Initialize(XmlElement? element) { _containingDocument = element?.OwnerDocument; _context = element; @@ -127,7 +131,7 @@ private void Initialize(XmlElement element) // /// - public string SigningKeyName + public string? SigningKeyName { get { return m_strSigningKeyName; } set { m_strSigningKeyName = value; } @@ -160,15 +164,16 @@ public Collection SafeCanonicalizationMethods get { return _safeCanonicalizationMethods; } } - public AsymmetricAlgorithm SigningKey + public AsymmetricAlgorithm? SigningKey { get { return _signingKey; } set { _signingKey = value; } } + [AllowNull] public EncryptedXml EncryptedXml { - get => _exml ??= new EncryptedXml(_containingDocument); // default processing rules + get => _exml ??= new EncryptedXml(_containingDocument!); // default processing rules set => _exml = value; } @@ -177,22 +182,22 @@ public Signature Signature get { return m_signature; } } - public SignedInfo SignedInfo + public SignedInfo? SignedInfo { get { return m_signature.SignedInfo; } } - public string SignatureMethod + public string? SignatureMethod { - get { return m_signature.SignedInfo.SignatureMethod; } + get { return m_signature.SignedInfo!.SignatureMethod; } } - public string SignatureLength + public string? SignatureLength { - get { return m_signature.SignedInfo.SignatureLength; } + get { return m_signature.SignedInfo!.SignatureLength; } } - public byte[] SignatureValue + public byte[]? SignatureValue { get { return m_signature.SignatureValue; } } @@ -232,7 +237,7 @@ public void LoadXml(XmlElement value) public void AddReference(Reference reference) { - m_signature.SignedInfo.AddReference(reference); + m_signature.SignedInfo!.AddReference(reference); } public void AddObject(DataObject dataObject) @@ -245,13 +250,13 @@ public bool CheckSignature() return CheckSignatureReturningKey(out _); } - public bool CheckSignatureReturningKey(out AsymmetricAlgorithm signingKey) + public bool CheckSignatureReturningKey(out AsymmetricAlgorithm? signingKey) { SignedXmlDebugLog.LogBeginSignatureVerification(this, _context); signingKey = null; bool bRet = false; - AsymmetricAlgorithm key; + AsymmetricAlgorithm? key; if (!CheckSignatureFormat()) { @@ -326,7 +331,7 @@ public bool CheckSignature(X509Certificate2 certificate, bool verifySignatureOnl // Check key usages to make sure it is good for signing. foreach (X509Extension extension in certificate.Extensions) { - if (string.Equals(extension.Oid.Value, "2.5.29.15" /* szOID_KEY_USAGE */, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(extension.Oid!.Value, "2.5.29.15" /* szOID_KEY_USAGE */, StringComparison.OrdinalIgnoreCase)) { X509KeyUsageExtension keyUsage = new X509KeyUsageExtension(); keyUsage.CopyFrom(extension); @@ -357,9 +362,9 @@ public bool CheckSignature(X509Certificate2 certificate, bool verifySignatureOnl } } - using (AsymmetricAlgorithm publicKey = Utils.GetAnyPublicKey(certificate)) + using (AsymmetricAlgorithm? publicKey = Utils.GetAnyPublicKey(certificate)) { - if (!CheckSignature(publicKey)) + if (!CheckSignature(publicKey!)) { return false; } @@ -371,18 +376,18 @@ public bool CheckSignature(X509Certificate2 certificate, bool verifySignatureOnl public void ComputeSignature() { - SignedXmlDebugLog.LogBeginSignatureComputation(this, _context); + SignedXmlDebugLog.LogBeginSignatureComputation(this, _context!); BuildDigestedReferences(); // Load the key - AsymmetricAlgorithm key = SigningKey; + AsymmetricAlgorithm? key = SigningKey; if (key == null) throw new CryptographicException(SR.Cryptography_Xml_LoadKeyFailed); // Check the signature algorithm associated with the key so that we can accordingly set the signature method - if (SignedInfo.SignatureMethod == null) + if (SignedInfo!.SignatureMethod == null) { if (key is DSA) { @@ -400,10 +405,10 @@ public void ComputeSignature() } // See if there is a signature description class defined in the Config file - SignatureDescription signatureDescription = CryptoHelpers.CreateFromName(SignedInfo.SignatureMethod); + SignatureDescription? signatureDescription = CryptoHelpers.CreateFromName(SignedInfo.SignatureMethod); if (signatureDescription == null) throw new CryptographicException(SR.Cryptography_Xml_SignatureDescriptionNotCreated); - HashAlgorithm hashAlg = signatureDescription.CreateDigest(); + HashAlgorithm? hashAlg = signatureDescription.CreateDigest(); if (hashAlg == null) throw new CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed); @@ -424,12 +429,12 @@ public void ComputeSignature(KeyedHashAlgorithm macAlg) throw new ArgumentNullException(nameof(macAlg)); } - HMAC hash = macAlg as HMAC; + HMAC? hash = macAlg as HMAC; if (hash == null) throw new CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch); int signatureLength; - if (m_signature.SignedInfo.SignatureLength == null) + if (m_signature.SignedInfo!.SignatureLength == null) signatureLength = hash.HashSize; else signatureLength = Convert.ToInt32(m_signature.SignedInfo.SignatureLength, null); @@ -440,7 +445,7 @@ public void ComputeSignature(KeyedHashAlgorithm macAlg) throw new CryptographicException(SR.Cryptography_Xml_InvalidSignatureLength2); BuildDigestedReferences(); - SignedInfo.SignatureMethod = hash.HashName switch + SignedInfo!.SignatureMethod = hash.HashName switch { "SHA1" => SignedXml.XmlDsigHMACSHA1Url, "SHA256" => SignedXml.XmlDsigMoreHMACSHA256Url, @@ -461,14 +466,14 @@ public void ComputeSignature(KeyedHashAlgorithm macAlg) // virtual methods // - protected virtual AsymmetricAlgorithm GetPublicKey() + protected virtual AsymmetricAlgorithm? GetPublicKey() { if (KeyInfo == null) throw new CryptographicException(SR.Cryptography_Xml_KeyInfoRequired); if (_x509Enum != null) { - AsymmetricAlgorithm key = GetNextCertificatePublicKey(); + AsymmetricAlgorithm? key = GetNextCertificatePublicKey(); if (key != null) return key; } @@ -491,7 +496,7 @@ protected virtual AsymmetricAlgorithm GetPublicKey() if (_x509Collection.Count > 0) { _x509Enum = _x509Collection.GetEnumerator(); - AsymmetricAlgorithm key = GetNextCertificatePublicKey(); + AsymmetricAlgorithm? key = GetNextCertificatePublicKey(); if (key != null) return key; } @@ -519,11 +524,11 @@ private X509Certificate2Collection BuildBagOfCerts() return collection; } - private AsymmetricAlgorithm GetNextCertificatePublicKey() + private AsymmetricAlgorithm? GetNextCertificatePublicKey() { - while (_x509Enum.MoveNext()) + while (_x509Enum!.MoveNext()) { - X509Certificate2 certificate = (X509Certificate2)_x509Enum.Current; + X509Certificate2? certificate = (X509Certificate2?)_x509Enum.Current; if (certificate != null) return Utils.GetAnyPublicKey(certificate); } @@ -531,12 +536,12 @@ private AsymmetricAlgorithm GetNextCertificatePublicKey() return null; } - public virtual XmlElement GetIdElement(XmlDocument document, string idValue) + public virtual XmlElement? GetIdElement(XmlDocument? document, string idValue) { return DefaultGetIdElement(document, idValue); } - internal static XmlElement DefaultGetIdElement(XmlDocument document, string idValue) + internal static XmlElement? DefaultGetIdElement(XmlDocument? document, string idValue) { if (document == null) return null; @@ -555,14 +560,14 @@ internal static XmlElement DefaultGetIdElement(XmlDocument document, string idVa } // Get the element with idValue - XmlElement elem = document.GetElementById(idValue); + XmlElement? elem = document.GetElementById(idValue); if (elem != null) { // Have to check for duplicate ID values from the DTD. XmlDocument docClone = (XmlDocument)document.CloneNode(true); - XmlElement cloneElem = docClone.GetElementById(idValue); + XmlElement? cloneElem = docClone.GetElementById(idValue); // If it's null here we want to know about it, because it means that // GetElementById failed to work across the cloning, and our uniqueness @@ -574,7 +579,7 @@ internal static XmlElement DefaultGetIdElement(XmlDocument document, string idVa { cloneElem.Attributes.RemoveAll(); - XmlElement cloneElem2 = docClone.GetElementById(idValue); + XmlElement? cloneElem2 = docClone.GetElementById(idValue); if (cloneElem2 != null) { @@ -602,7 +607,7 @@ internal static XmlElement DefaultGetIdElement(XmlDocument document, string idVa // private bool _bCacheValid; - private byte[] _digestedSignedInfo; + private byte[]? _digestedSignedInfo; private static bool DefaultSignatureFormatValidator(SignedXml signedXml) { @@ -628,13 +633,13 @@ private static bool DefaultSignatureFormatValidator(SignedXml signedXml) private bool DoesSignatureUseTruncatedHmac() { // If we're not using the SignatureLength property, then we're not truncating the signature length - if (SignedInfo.SignatureLength == null) + if (SignedInfo!.SignatureLength == null) { return false; } // See if we're signed witn an HMAC algorithm - HMAC hmac = CryptoHelpers.CreateFromName(SignatureMethod); + HMAC? hmac = CryptoHelpers.CreateFromName(SignatureMethod!); if (hmac == null) { // We aren't signed with an HMAC algorithm, so we cannot have a truncated HMAC @@ -661,13 +666,13 @@ private bool DoesSignatureUseSafeCanonicalizationMethod() { foreach (string safeAlgorithm in SafeCanonicalizationMethods) { - if (string.Equals(safeAlgorithm, SignedInfo.CanonicalizationMethod, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(safeAlgorithm, SignedInfo!.CanonicalizationMethod, StringComparison.OrdinalIgnoreCase)) { return true; } } - SignedXmlDebugLog.LogUnsafeCanonicalizationMethod(this, SignedInfo.CanonicalizationMethod, SafeCanonicalizationMethods); + SignedXmlDebugLog.LogUnsafeCanonicalizationMethod(this, SignedInfo!.CanonicalizationMethod, SafeCanonicalizationMethods); return false; } @@ -680,7 +685,7 @@ private bool ReferenceUsesSafeTransformMethods(Reference reference) { Transform transform = transformChain[i]; - if (!IsSafeTransform(transform.Algorithm)) + if (!IsSafeTransform(transform.Algorithm!)) { return false; } @@ -772,16 +777,16 @@ private static IList DefaultSafeTransformMethods private byte[] GetC14NDigest(HashAlgorithm hash) { bool isKeyedHashAlgorithm = hash is KeyedHashAlgorithm; - if (isKeyedHashAlgorithm || !_bCacheValid || !SignedInfo.CacheValid) + if (isKeyedHashAlgorithm || !_bCacheValid || !SignedInfo!.CacheValid) { - string baseUri = _containingDocument?.BaseURI; - XmlResolver resolver = (_bResolverSet ? _xmlResolver : XmlResolverHelper.GetThrowingResolver()); - XmlDocument doc = Utils.PreProcessElementInput(SignedInfo.GetXml(), resolver, baseUri); + string? baseUri = _containingDocument?.BaseURI; + XmlResolver? resolver = (_bResolverSet ? _xmlResolver : XmlResolverHelper.GetThrowingResolver()); + XmlDocument doc = Utils.PreProcessElementInput(SignedInfo!.GetXml(), resolver!, baseUri ); // Add non default namespaces in scope - CanonicalXmlNodeList namespaces = (_context == null ? null : Utils.GetPropagatedAttributes(_context)); + CanonicalXmlNodeList? namespaces = (_context == null ? null : Utils.GetPropagatedAttributes(_context)); SignedXmlDebugLog.LogNamespacePropagation(this, namespaces); - Utils.AddNamespaces(doc.DocumentElement, namespaces); + Utils.AddNamespaces(doc.DocumentElement!, namespaces); Transform c14nMethodTransform = SignedInfo.CanonicalizationMethodObject; c14nMethodTransform.Resolver = resolver; @@ -794,14 +799,17 @@ private byte[] GetC14NDigest(HashAlgorithm hash) _bCacheValid = !isKeyedHashAlgorithm; } - return _digestedSignedInfo; + return _digestedSignedInfo!; } private int GetReferenceLevel(int index, ArrayList references) { + Debug.Assert(_refProcessed != null); + Debug.Assert(_refLevelCache != null); + if (_refProcessed[index]) return _refLevelCache[index]; _refProcessed[index] = true; - Reference reference = (Reference)references[index]; + Reference reference = (Reference)references[index]!; if (reference.Uri == null || reference.Uri.Length == 0 || (reference.Uri.Length > 0 && reference.Uri[0] != '#')) { _refLevelCache[index] = 0; @@ -818,7 +826,7 @@ private int GetReferenceLevel(int index, ArrayList references) // If this is pointing to another reference for (int j = 0; j < references.Count; ++j) { - if (((Reference)references[j]).Id == idref) + if (((Reference)references[j]!).Id == idref) { _refLevelCache[index] = GetReferenceLevel(j, references) + 1; return (_refLevelCache[index]); @@ -834,19 +842,19 @@ private int GetReferenceLevel(int index, ArrayList references) private sealed class ReferenceLevelSortOrder : IComparer { - private ArrayList _references; + private ArrayList? _references; public ReferenceLevelSortOrder() { } public ArrayList References { - get { return _references; } + get { return _references!; } set { _references = value; } } - public int Compare(object a, object b) + public int Compare(object? a, object? b) { - Reference referenceA = a as Reference; - Reference referenceB = b as Reference; + Reference? referenceA = a as Reference; + Reference? referenceB = b as Reference; // Get the indexes int iIndexA = 0; @@ -859,8 +867,8 @@ public int Compare(object a, object b) i++; } - int iLevelA = referenceA.SignedXml.GetReferenceLevel(iIndexA, References); - int iLevelB = referenceB.SignedXml.GetReferenceLevel(iIndexB, References); + int iLevelA = referenceA!.SignedXml!.GetReferenceLevel(iIndexA, References); + int iLevelB = referenceB!.SignedXml!.GetReferenceLevel(iIndexB, References); return iLevelA.CompareTo(iLevelB); } } @@ -868,7 +876,7 @@ public int Compare(object a, object b) private void BuildDigestedReferences() { // Default the DigestMethod and Canonicalization - ArrayList references = SignedInfo.References; + ArrayList references = SignedInfo!.References; // Reset the cache _refProcessed = new bool[references.Count]; _refLevelCache = new int[references.Count]; @@ -895,7 +903,7 @@ private void BuildDigestedReferences() SignedXmlDebugLog.LogSigningReference(this, reference); - reference.UpdateHashValue(_containingDocument, nodeList); + reference.UpdateHashValue(_containingDocument!, nodeList); // If this reference has an Id attribute, add it if (reference.Id != null) nodeList.Add(reference.GetXml()); @@ -904,10 +912,10 @@ private void BuildDigestedReferences() private bool CheckDigestedReferences() { - ArrayList references = m_signature.SignedInfo.References; + ArrayList references = m_signature.SignedInfo!.References; for (int i = 0; i < references.Count; ++i) { - Reference digestedReference = (Reference)references[i]; + Reference digestedReference = (Reference)references[i]!; if (!ReferenceUsesSafeTransformMethods(digestedReference)) { @@ -915,10 +923,10 @@ private bool CheckDigestedReferences() } SignedXmlDebugLog.LogVerifyReference(this, digestedReference); - byte[] calculatedHash; + byte[]? calculatedHash; try { - calculatedHash = digestedReference.CalculateHashValue(_containingDocument, m_signature.ReferencedItems); + calculatedHash = digestedReference.CalculateHashValue(_containingDocument!, m_signature.ReferencedItems); } catch (CryptoSignedXmlRecursionException) { @@ -943,7 +951,7 @@ private bool CheckDigestedReferences() // This method makes no attempt to disguise the length of either of its inputs. It is assumed the attacker has // knowledge of the algorithms used, and thus the output length. Length is difficult to properly blind in modern CPUs. [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] - private static bool CryptographicEquals(byte[] a, byte[] b) + private static bool CryptographicEquals(byte[]? a, byte[]? b) { System.Diagnostics.Debug.Assert(a != null); System.Diagnostics.Debug.Assert(b != null); @@ -997,18 +1005,18 @@ private bool CheckSignedInfo(AsymmetricAlgorithm key) throw new ArgumentNullException(nameof(key)); } - SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo); + SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo!); - SignatureDescription signatureDescription = CryptoHelpers.CreateFromName(SignatureMethod); + SignatureDescription? signatureDescription = CryptoHelpers.CreateFromName(SignatureMethod); if (signatureDescription == null) throw new CryptographicException(SR.Cryptography_Xml_SignatureDescriptionNotCreated); // Let's see if the key corresponds with the SignatureMethod - Type ta = Type.GetType(signatureDescription.KeyAlgorithm); + Type ta = Type.GetType(signatureDescription.KeyAlgorithm!)!; if (!IsKeyTheCorrectAlgorithm(key, ta)) return false; - HashAlgorithm hashAlgorithm = signatureDescription.CreateDigest(); + HashAlgorithm? hashAlgorithm = signatureDescription.CreateDigest(); if (hashAlgorithm == null) throw new CryptographicException(SR.Cryptography_Xml_CreateHashAlgorithmFailed); byte[] hashval = GetC14NDigest(hashAlgorithm); @@ -1021,7 +1029,7 @@ private bool CheckSignedInfo(AsymmetricAlgorithm key) asymmetricSignatureDeformatter, hashval, m_signature.SignatureValue); - return asymmetricSignatureDeformatter.VerifySignature(hashval, m_signature.SignatureValue); + return asymmetricSignatureDeformatter.VerifySignature(hashval, m_signature.SignatureValue!); } private bool CheckSignedInfo(KeyedHashAlgorithm macAlg) @@ -1031,10 +1039,10 @@ private bool CheckSignedInfo(KeyedHashAlgorithm macAlg) throw new ArgumentNullException(nameof(macAlg)); } - SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo); + SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo!); int signatureLength; - if (m_signature.SignedInfo.SignatureLength == null) + if (m_signature.SignedInfo!.SignatureLength == null) signatureLength = macAlg.HashSize; else signatureLength = Convert.ToInt32(m_signature.SignedInfo.SignatureLength, null); @@ -1056,7 +1064,7 @@ private bool CheckSignedInfo(KeyedHashAlgorithm macAlg) return m_signature.SignatureValue.AsSpan().SequenceEqual(hashValue.AsSpan(0, m_signature.SignatureValue.Length)); } - private static XmlElement GetSingleReferenceTarget(XmlDocument document, string idAttributeName, string idValue) + private static XmlElement? GetSingleReferenceTarget(XmlDocument document, string idAttributeName, string idValue) { // idValue has already been tested as an NCName (unless overridden for compatibility), so there's no // escaping that needs to be done here. @@ -1071,7 +1079,7 @@ private static XmlElement GetSingleReferenceTarget(XmlDocument document, string // In this case, we'll treat it the same as having found nothing across all fallbacks (but shortcut so that we don't // fall into a trap of finding a secondary element which wasn't the originally signed one). - XmlNodeList nodeList = document.SelectNodes(xPath); + XmlNodeList? nodeList = document.SelectNodes(xPath); if (nodeList == null || nodeList.Count == 0) { @@ -1108,7 +1116,7 @@ private static bool IsKeyTheCorrectAlgorithm(AsymmetricAlgorithm key, Type expec // while (expectedType != null && expectedType.BaseType != typeof(AsymmetricAlgorithm)) { - expectedType = expectedType.BaseType; + expectedType = expectedType.BaseType!; } if (expectedType == null) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs index bbe28edd204b86..7c9f7e74be89f2 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Reflection; @@ -191,7 +192,7 @@ private static bool VerboseLoggingEnabled /// /// Convert the byte array into a hex string /// - private static string FormatBytes(byte[] bytes) + private static string FormatBytes(byte[]? bytes) { if (bytes == null) return NullString; @@ -206,9 +207,9 @@ private static string GetKeyName(object key) { Debug.Assert(key != null, "key != null"); - ICspAsymmetricAlgorithm cspKey = key as ICspAsymmetricAlgorithm; - X509Certificate certificate = key as X509Certificate; - X509Certificate2 certificate2 = key as X509Certificate2; + ICspAsymmetricAlgorithm? cspKey = key as ICspAsymmetricAlgorithm; + X509Certificate? certificate = key as X509Certificate; + X509Certificate2? certificate2 = key as X509Certificate2; // // Use the following sources for key names, if available: @@ -255,11 +256,11 @@ private static string GetObjectId(object o) /// /// Map an OID to the friendliest name possible /// - private static string GetOidName(Oid oid) + private static string? GetOidName(Oid oid) { Debug.Assert(oid != null, "oid != null"); - string friendlyName = oid.FriendlyName; + string? friendlyName = oid.FriendlyName; if (string.IsNullOrEmpty(friendlyName)) friendlyName = oid.Value; @@ -292,7 +293,7 @@ internal static void LogBeginCanonicalization(SignedXml signedXml, Transform can { string canonicalizationSettings = SR.Format(CultureInfo.InvariantCulture, SR.Log_CanonicalizationSettings, - canonicalizationTransform.Resolver.GetType(), + canonicalizationTransform.Resolver!.GetType(), canonicalizationTransform.BaseURI); WriteLine(signedXml, TraceEventType.Verbose, @@ -318,7 +319,7 @@ internal static void LogBeginCheckSignatureFormat(SignedXml signedXml, Func /// SignedXml object doing the verification /// Context of the verification - internal static void LogBeginSignatureVerification(SignedXml signedXml, XmlElement context) + internal static void LogBeginSignatureVerification(SignedXml signedXml, XmlElement? context) { Debug.Assert(signedXml != null, "signedXml != null"); @@ -415,7 +416,7 @@ internal static void LogCanonicalizedOutput(SignedXml signedXml, Transform canon if (VerboseLoggingEnabled) { - using (StreamReader reader = new StreamReader(canonicalizationTransform.GetOutput(typeof(Stream)) as Stream)) + using (StreamReader reader = new StreamReader((canonicalizationTransform.GetOutput(typeof(Stream)) as Stream)!)) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_CanonicalizedOutput, @@ -452,7 +453,7 @@ internal static void LogFormatValidationResult(SignedXml signedXml, bool result) /// SignedXml object doing the signature verification /// Canonicalization algorithm /// List of valid canonicalization algorithms - internal static void LogUnsafeCanonicalizationMethod(SignedXml signedXml, string algorithm, IEnumerable validAlgorithms) + internal static void LogUnsafeCanonicalizationMethod(SignedXml signedXml, string algorithm, IEnumerable? validAlgorithms) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(validAlgorithms != null, "validAlgorithms != null"); @@ -490,7 +491,7 @@ internal static void LogUnsafeCanonicalizationMethod(SignedXml signedXml, string internal static void LogUnsafeTransformMethod( SignedXml signedXml, string algorithm, - IEnumerable validC14nAlgorithms, + IEnumerable? validC14nAlgorithms, IEnumerable validTransformAlgorithms) { Debug.Assert(signedXml != null, "signedXml != null"); @@ -534,7 +535,7 @@ internal static void LogUnsafeTransformMethod( /// /// SignedXml doing the signing or verification /// namespaces being propagated - internal static void LogNamespacePropagation(SignedXml signedXml, XmlNodeList namespaces) + internal static void LogNamespacePropagation(SignedXml signedXml, XmlNodeList? namespaces) { Debug.Assert(signedXml != null, "signedXml != null"); @@ -571,7 +572,8 @@ internal static void LogNamespacePropagation(SignedXml signedXml, XmlNodeList na /// The reference being processed /// Stream containing the output of the reference /// Stream containing the output of the reference - internal static Stream LogReferenceData(Reference reference, Stream data) + [return: NotNullIfNotNull("data")] + internal static Stream? LogReferenceData(Reference reference, Stream? data) { if (VerboseLoggingEnabled) { @@ -589,7 +591,7 @@ internal static Stream LogReferenceData(Reference reference, Stream data) int readBytes; do { - readBytes = data.Read(buffer, 0, buffer.Length); + readBytes = data!.Read(buffer, 0, buffer.Length); ms.Write(buffer, 0, readBytes); } while (readBytes == buffer.Length); @@ -682,7 +684,7 @@ internal static void LogSigningReference(SignedXml signedXml, Reference referenc if (VerboseLoggingEnabled) { - HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName(reference.DigestMethod); + HashAlgorithm? hashAlgorithm = CryptoHelpers.CreateFromName(reference.DigestMethod); string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_SigningReference, @@ -762,7 +764,7 @@ internal static void LogVerifyKeyUsage(SignedXml signedXml, X509Certificate cert string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_KeyUsages, keyUsages.KeyUsages, - GetOidName(keyUsages.Oid), + GetOidName(keyUsages.Oid!), GetKeyName(certificate)); WriteLine(signedXml, @@ -807,8 +809,8 @@ internal static void LogVerifyReference(SignedXml signedXml, Reference reference /// hash value the signature expected the reference to have internal static void LogVerifyReferenceHash(SignedXml signedXml, Reference reference, - byte[] actualHash, - byte[] expectedHash) + byte[]? actualHash, + byte[]? expectedHash) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); @@ -817,7 +819,7 @@ internal static void LogVerifyReferenceHash(SignedXml signedXml, if (VerboseLoggingEnabled) { - HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName(reference.DigestMethod); + HashAlgorithm? hashAlgorithm = CryptoHelpers.CreateFromName(reference.DigestMethod); string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_ReferenceHash, @@ -850,8 +852,8 @@ internal static void LogVerifySignedInfo(SignedXml signedXml, SignatureDescription signatureDescription, HashAlgorithm hashAlgorithm, AsymmetricSignatureDeformatter asymmetricSignatureDeformatter, - byte[] actualHashValue, - byte[] signatureValue) + byte[]? actualHashValue, + byte[]? signatureValue) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signatureDescription != null, "signatureDescription != null"); @@ -896,8 +898,8 @@ internal static void LogVerifySignedInfo(SignedXml signedXml, /// raw signature value internal static void LogVerifySignedInfo(SignedXml signedXml, KeyedHashAlgorithm mac, - byte[] actualHashValue, - byte[] signatureValue) + byte[]? actualHashValue, + byte[]? signatureValue) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(mac != null, "mac != null"); @@ -1031,7 +1033,7 @@ internal static void LogSignedXmlRecursionLimit(SignedXml signedXml, if (InformationLoggingEnabled) { - HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName(reference.DigestMethod); + HashAlgorithm? hashAlgorithm = CryptoHelpers.CreateFromName(reference.DigestMethod); string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name; string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_SignedXmlRecursionLimit, diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SymmetricKeyWrap.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SymmetricKeyWrap.cs index 0cfb7f60218bc3..f4c983e2086abf 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SymmetricKeyWrap.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SymmetricKeyWrap.cs @@ -36,9 +36,9 @@ internal static byte[] TripleDESKeyWrapEncrypt(byte[] rgbKey, byte[] rgbWrappedK // rgbWKCS = rgbWrappedKeyData | (first 8 bytes of the hash) byte[] rgbWKCKS = new byte[rgbWrappedKeyData.Length + 8]; - TripleDES tripleDES = null; - ICryptoTransform enc1 = null; - ICryptoTransform enc2 = null; + TripleDES? tripleDES = null; + ICryptoTransform? enc1 = null; + ICryptoTransform? enc2 = null; try { @@ -75,9 +75,9 @@ internal static byte[] TripleDESKeyWrapDecrypt(byte[] rgbKey, byte[] rgbEncrypte && rgbEncryptedWrappedKeyData.Length != 48) throw new CryptographicException(SR.Cryptography_Xml_KW_BadKeySize); - TripleDES tripleDES = null; - ICryptoTransform dec1 = null; - ICryptoTransform dec2 = null; + TripleDES? tripleDES = null; + ICryptoTransform? dec1 = null; + ICryptoTransform? dec2 = null; try { @@ -125,8 +125,8 @@ internal static byte[] AESKeyWrapEncrypt(byte[] rgbKey, byte[] rgbWrappedKeyData if ((rgbWrappedKeyData.Length % 8 != 0) || N <= 0) throw new CryptographicException(SR.Cryptography_Xml_KW_BadKeySize); - Aes aes = null; - ICryptoTransform enc = null; + Aes? aes = null; + ICryptoTransform? enc = null; try { @@ -188,8 +188,8 @@ internal static byte[] AESKeyWrapDecrypt(byte[] rgbKey, byte[] rgbEncryptedWrapp throw new CryptographicException(SR.Cryptography_Xml_KW_BadKeySize); byte[] rgbOutput = new byte[N << 3]; - Aes aes = null; - ICryptoTransform dec = null; + Aes? aes = null; + ICryptoTransform? dec = null; try { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Transform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Transform.cs index 45a05d6d062b4f..b4d9f66b69c057 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Transform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Transform.cs @@ -14,6 +14,7 @@ // stream. (We only bother implementing that much now since every use of transform chains in XmlDsig ultimately yields something to hash). using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Xml; @@ -21,28 +22,28 @@ namespace System.Security.Cryptography.Xml { public abstract class Transform { - private string _algorithm; - private string _baseUri; - internal XmlResolver _xmlResolver; + private string? _algorithm; + private string? _baseUri; + internal XmlResolver? _xmlResolver; private bool _bResolverSet; - private SignedXml _signedXml; - private Reference _reference; - private Hashtable _propagatedNamespaces; - private XmlElement _context; + private SignedXml? _signedXml; + private Reference? _reference; + private Hashtable? _propagatedNamespaces; + private XmlElement? _context; - internal string BaseURI + internal string? BaseURI { get { return _baseUri; } set { _baseUri = value; } } - internal SignedXml SignedXml + internal SignedXml? SignedXml { get { return _signedXml; } set { _signedXml = value; } } - internal Reference Reference + internal Reference? Reference { get { return _reference; } set { _reference = value; } @@ -58,13 +59,13 @@ protected Transform() { } // public properties // - public string Algorithm + public string? Algorithm { get { return _algorithm; } set { _algorithm = value; } } - public XmlResolver Resolver + public XmlResolver? Resolver { internal get { @@ -79,6 +80,7 @@ internal get } } + [MemberNotNullWhen(true, nameof(_xmlResolver))] internal bool ResolverSet { get { return _bResolverSet; } @@ -128,7 +130,7 @@ internal XmlElement GetXml(XmlDocument document, string name) XmlElement transformElement = document.CreateElement(name, SignedXml.XmlDsigNamespaceUrl); if (!string.IsNullOrEmpty(Algorithm)) transformElement.SetAttribute("Algorithm", Algorithm); - XmlNodeList children = GetInnerXml(); + XmlNodeList? children = GetInnerXml(); if (children != null) { foreach (XmlNode node in children) @@ -141,7 +143,7 @@ internal XmlElement GetXml(XmlDocument document, string name) public abstract void LoadInnerXml(XmlNodeList nodeList); - protected abstract XmlNodeList GetInnerXml(); + protected abstract XmlNodeList? GetInnerXml(); public abstract void LoadInput(object obj); @@ -154,15 +156,15 @@ public virtual byte[] GetDigestedOutput(HashAlgorithm hash) return hash.ComputeHash((Stream)GetOutput(typeof(Stream))); } - public XmlElement Context + public XmlElement? Context { get { if (_context != null) return _context; - Reference reference = Reference; - SignedXml signedXml = (reference == null ? SignedXml : reference.SignedXml); + Reference? reference = Reference; + SignedXml? signedXml = (reference == null ? SignedXml : reference.SignedXml); if (signedXml == null) return null; @@ -181,8 +183,8 @@ public Hashtable PropagatedNamespaces if (_propagatedNamespaces != null) return _propagatedNamespaces; - Reference reference = Reference; - SignedXml signedXml = (reference == null ? SignedXml : reference.SignedXml); + Reference? reference = Reference; + SignedXml? signedXml = (reference == null ? SignedXml : reference.SignedXml); // If the reference is not a Uri reference with a DataObject target, return an empty hashtable. if (reference != null && @@ -193,7 +195,7 @@ public Hashtable PropagatedNamespaces return _propagatedNamespaces; } - CanonicalXmlNodeList namespaces = null; + CanonicalXmlNodeList? namespaces = null; if (reference != null) namespaces = reference._namespaces; else if (signedXml?._context != null) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs index 2aeda5a2ad23f3..bec0ab08e3fadc 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs @@ -52,15 +52,15 @@ public Transform this[int index] { if (index >= _transforms.Count) throw new ArgumentException(SR.ArgumentOutOfRange_IndexMustBeLess, nameof(index)); - return (Transform)_transforms[index]; + return (Transform)_transforms[index]!; } } // The goal behind this method is to pump the input stream through the transforms and get back something that // can be hashed - internal Stream TransformToOctetStream(object inputObject, Type inputType, XmlResolver resolver, string baseUri) + internal Stream TransformToOctetStream(object? inputObject, Type inputType, XmlResolver? resolver, string? baseUri) { - object currentInput = inputObject; + object? currentInput = inputObject; foreach (Transform transform in _transforms) { if (currentInput == null || transform.AcceptsType(currentInput.GetType())) @@ -68,7 +68,7 @@ internal Stream TransformToOctetStream(object inputObject, Type inputType, XmlRe //in this case, no translation necessary, pump it through transform.Resolver = resolver; transform.BaseURI = baseUri; - transform.LoadInput(currentInput); + transform.LoadInput(currentInput!); currentInput = transform.GetOutput(); } else @@ -79,7 +79,7 @@ internal Stream TransformToOctetStream(object inputObject, Type inputType, XmlRe { if (transform.AcceptsType(typeof(XmlDocument))) { - Stream currentInputStream = currentInput as Stream; + Stream currentInputStream = (currentInput as Stream)!; XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; XmlReader valReader = Utils.PreProcessStreamInput(currentInputStream, resolver, baseUri); @@ -131,31 +131,31 @@ internal Stream TransformToOctetStream(object inputObject, Type inputType, XmlRe } // Final processing, either we already have a stream or have to canonicalize - if (currentInput is Stream) + if (currentInput is Stream inputStream) { - return currentInput as Stream; + return inputStream; } if (currentInput is XmlNodeList) { CanonicalXml c14n = new CanonicalXml((XmlNodeList)currentInput, resolver, false); - MemoryStream ms = new MemoryStream(c14n.GetBytes()); + MemoryStream? ms = new MemoryStream(c14n.GetBytes()); return ms; } if (currentInput is XmlDocument) { CanonicalXml c14n = new CanonicalXml((XmlDocument)currentInput, resolver); - MemoryStream ms = new MemoryStream(c14n.GetBytes()); + MemoryStream? ms = new MemoryStream(c14n.GetBytes()); return ms; } throw new CryptographicException(SR.Cryptography_Xml_TransformIncorrectInputType); } - internal Stream TransformToOctetStream(Stream input, XmlResolver resolver, string baseUri) + internal Stream TransformToOctetStream(Stream? input, XmlResolver? resolver, string baseUri) { return TransformToOctetStream(input, typeof(Stream), resolver, baseUri); } - internal Stream TransformToOctetStream(XmlDocument document, XmlResolver resolver, string baseUri) + internal Stream TransformToOctetStream(XmlDocument? document, XmlResolver? resolver, string? baseUri) { return TransformToOctetStream(document, typeof(XmlDocument), resolver, baseUri); } @@ -186,16 +186,16 @@ internal void LoadXml(XmlElement value) XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); - XmlNodeList transformNodes = value.SelectNodes("ds:Transform", nsm); - if (transformNodes.Count == 0) + XmlNodeList? transformNodes = value.SelectNodes("ds:Transform", nsm); + if (transformNodes!.Count == 0) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Transforms"); _transforms.Clear(); for (int i = 0; i < transformNodes.Count; ++i) { - XmlElement transformElement = (XmlElement)transformNodes.Item(i); - string algorithm = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); - Transform transform = CryptoHelpers.CreateFromName(algorithm); + XmlElement transformElement = (XmlElement)transformNodes.Item(i)!; + string? algorithm = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); + Transform? transform = CryptoHelpers.CreateFromName(algorithm); if (transform == null) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); // let the transform read the children of the transformElement for data diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs index e5de6bee4c3c6f..634e30e499087c 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs @@ -50,10 +50,10 @@ internal static bool IsRedundantNamespace(XmlElement element, string prefix, str throw new ArgumentNullException(nameof(element)); } - XmlNode ancestorNode = ((XmlNode)element).ParentNode; + XmlNode? ancestorNode = ((XmlNode)element).ParentNode; while (ancestorNode != null) { - XmlElement ancestorElement = ancestorNode as XmlElement; + XmlElement? ancestorElement = ancestorNode as XmlElement; if (ancestorElement != null) if (HasNamespace(ancestorElement, prefix, value)) return true; ancestorNode = ancestorNode.ParentNode; @@ -62,9 +62,9 @@ internal static bool IsRedundantNamespace(XmlElement element, string prefix, str return false; } - internal static string GetAttribute(XmlElement element, string localName, string namespaceURI) + internal static string? GetAttribute(XmlElement element, string localName, string namespaceURI) { - string s = (element.HasAttribute(localName) ? element.GetAttribute(localName) : null); + string? s = (element.HasAttribute(localName) ? element.GetAttribute(localName) : null); if (s == null && element.HasAttribute(localName, namespaceURI)) s = element.GetAttribute(localName, namespaceURI); return s; @@ -75,12 +75,12 @@ internal static bool HasAttribute(XmlElement element, string localName, string n return element.HasAttribute(localName) || element.HasAttribute(localName, namespaceURI); } - internal static bool VerifyAttributes(XmlElement element, string expectedAttrName) + internal static bool VerifyAttributes(XmlElement element, string? expectedAttrName) { return VerifyAttributes(element, expectedAttrName == null ? null : new string[] { expectedAttrName }); } - internal static bool VerifyAttributes(XmlElement element, string[] expectedAttrNames) + internal static bool VerifyAttributes(XmlElement element, string[]? expectedAttrNames) { foreach (XmlAttribute attr in element.Attributes) { @@ -118,7 +118,7 @@ internal static bool IsDefaultNamespaceNode(XmlNode n) internal static bool IsEmptyDefaultNamespaceNode(XmlNode n) { - return IsDefaultNamespaceNode(n) && n.Value.Length == 0; + return IsDefaultNamespaceNode(n) && n.Value!.Length == 0; } internal static string GetNamespacePrefix(XmlAttribute a) @@ -132,7 +132,7 @@ internal static bool HasNamespacePrefix(XmlAttribute a, string nsPrefix) return GetNamespacePrefix(a).Equals(nsPrefix); } - internal static bool IsNonRedundantNamespaceDecl(XmlAttribute a, XmlAttribute nearestAncestorWithSamePrefix) + internal static bool IsNonRedundantNamespaceDecl(XmlAttribute a, XmlAttribute? nearestAncestorWithSamePrefix) { if (nearestAncestorWithSamePrefix == null) return !IsEmptyDefaultNamespaceNode(a); @@ -183,14 +183,14 @@ internal static void SBReplaceCharWithString(StringBuilder sb, char oldChar, str } } - internal static XmlReader PreProcessStreamInput(Stream inputStream, XmlResolver xmlResolver, string baseUri) + internal static XmlReader PreProcessStreamInput(Stream inputStream, XmlResolver? xmlResolver, string? baseUri) { XmlReaderSettings settings = GetSecureXmlReaderSettings(xmlResolver); XmlReader reader = XmlReader.Create(inputStream, settings, baseUri); return reader; } - internal static XmlReaderSettings GetSecureXmlReaderSettings(XmlResolver xmlResolver) + internal static XmlReaderSettings GetSecureXmlReaderSettings(XmlResolver? xmlResolver) { XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = xmlResolver; @@ -224,7 +224,7 @@ internal static XmlDocument PreProcessDocumentInput(XmlDocument document, XmlRes return doc; } - internal static XmlDocument PreProcessElementInput(XmlElement elem, XmlResolver xmlResolver, string baseUri) + internal static XmlDocument PreProcessElementInput(XmlElement elem, XmlResolver xmlResolver, string? baseUri) { if (elem is null) { @@ -249,12 +249,12 @@ internal static XmlDocument PreProcessElementInput(XmlElement elem, XmlResolver internal static XmlDocument DiscardComments(XmlDocument document) { - XmlNodeList nodeList = document.SelectNodes("//comment()"); + XmlNodeList? nodeList = document.SelectNodes("//comment()"); if (nodeList != null) { foreach (XmlNode node1 in nodeList) { - node1.ParentNode.RemoveChild(node1); + node1.ParentNode!.RemoveChild(node1); } } return document; @@ -272,7 +272,7 @@ internal static XmlNodeList AllDescendantNodes(XmlNode node, bool includeComment do { - XmlNode rootNode = (XmlNode)elementList[index]; + XmlNode rootNode = (XmlNode)elementList[index]!; // Add the children nodes XmlNodeList childNodes = rootNode.ChildNodes; if (childNodes != null) @@ -286,10 +286,10 @@ internal static XmlNodeList AllDescendantNodes(XmlNode node, bool includeComment } } // Add the attribute nodes - XmlAttributeCollection attribNodes = rootNode.Attributes; + XmlAttributeCollection? attribNodes = rootNode.Attributes; if (attribNodes != null) { - foreach (XmlNode attribNode in rootNode.Attributes) + foreach (XmlNode attribNode in rootNode.Attributes!) { if (attribNode.LocalName == "xmlns" || attribNode.Prefix == "xmlns") namespaceList.Add(attribNode); @@ -315,7 +315,7 @@ internal static XmlNodeList AllDescendantNodes(XmlNode node, bool includeComment return nodeList; } - internal static bool NodeInList(XmlNode node, XmlNodeList nodeList) + internal static bool NodeInList(XmlNode? node, XmlNodeList nodeList) { foreach (XmlNode nodeElem in nodeList) { @@ -345,9 +345,9 @@ internal static string GetIdFromLocalUri(string uri, out bool discardComments) return idref; } - internal static string ExtractIdFromLocalUri(string uri) + internal static string ExtractIdFromLocalUri(string? uri) { - string idref = uri.Substring(1); + string idref = uri!.Substring(1); // Deal with XPointer of type #xpointer(id("ID")). Other XPointer support isn't handled here and is anyway optional if (idref.StartsWith("xpointer(id(", StringComparison.Ordinal)) @@ -366,8 +366,8 @@ internal static string ExtractIdFromLocalUri(string uri) // This removes all children of an element. internal static void RemoveAllChildren(XmlElement inputElement) { - XmlNode child = inputElement.FirstChild; - XmlNode sibling; + XmlNode? child = inputElement.FirstChild; + XmlNode? sibling; while (child != null) { @@ -384,7 +384,7 @@ internal static void RemoveAllChildren(XmlElement inputElement) internal static long Pump(Stream input, Stream output) { // Use MemoryStream's WriteTo(Stream) method if possible - MemoryStream inputMS = input as MemoryStream; + MemoryStream? inputMS = input as MemoryStream; if (inputMS != null && inputMS.Position == 0) { inputMS.WriteTo(output); @@ -426,7 +426,7 @@ internal static Hashtable TokenizePrefixListString(string s) return set; } - internal static string EscapeWhitespaceData(string data) + internal static string EscapeWhitespaceData(string? data) { StringBuilder sb = new StringBuilder(); sb.Append(data); @@ -434,7 +434,7 @@ internal static string EscapeWhitespaceData(string data) return sb.ToString(); } - internal static string EscapeTextData(string data) + internal static string EscapeTextData(string? data) { StringBuilder sb = new StringBuilder(); sb.Append(data); @@ -463,7 +463,7 @@ internal static string EscapeAttributeValue(string value) return sb.ToString(); } - internal static XmlDocument GetOwnerDocument(XmlNodeList nodeList) + internal static XmlDocument? GetOwnerDocument(XmlNodeList nodeList) { foreach (XmlNode node in nodeList) { @@ -473,7 +473,7 @@ internal static XmlDocument GetOwnerDocument(XmlNodeList nodeList) return null; } - internal static void AddNamespaces(XmlElement elem, CanonicalXmlNodeList namespaces) + internal static void AddNamespaces(XmlElement elem, CanonicalXmlNodeList? namespaces) { if (namespaces != null) { @@ -504,18 +504,18 @@ internal static void AddNamespaces(XmlElement elem, Hashtable namespaces) } // This method gets the attributes that should be propagated - internal static CanonicalXmlNodeList GetPropagatedAttributes(XmlElement elem) + internal static CanonicalXmlNodeList? GetPropagatedAttributes(XmlElement? elem) { if (elem == null) return null; CanonicalXmlNodeList namespaces = new CanonicalXmlNodeList(); - XmlNode ancestorNode = elem; + XmlNode? ancestorNode = elem; bool bDefNamespaceToAdd = true; while (ancestorNode != null) { - XmlElement ancestorElement = ancestorNode as XmlElement; + XmlElement? ancestorElement = ancestorNode as XmlElement; if (ancestorElement == null) { ancestorNode = ancestorNode.ParentNode; @@ -625,7 +625,7 @@ internal static int GetHexArraySize(byte[] hex) } // Mimic the behavior of the X509IssuerSerial constructor with null and empty checks - internal static X509IssuerSerial CreateX509IssuerSerial(string issuerName, string serialNumber) + internal static X509IssuerSerial CreateX509IssuerSerial(string? issuerName, string? serialNumber) { if (issuerName == null || issuerName.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullString, nameof(issuerName)); @@ -642,7 +642,7 @@ internal static X509IssuerSerial CreateX509IssuerSerial(string issuerName, strin internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyInfoX509Data, CertUsageType certUsageType) { X509Certificate2Collection collection = new X509Certificate2Collection(); - ArrayList decryptionIssuerSerials = (certUsageType == CertUsageType.Decryption ? new ArrayList() : null); + ArrayList? decryptionIssuerSerials = (certUsageType == CertUsageType.Decryption ? new ArrayList() : null); if (keyInfoX509Data.Certificates != null) { foreach (X509Certificate2 certificate in keyInfoX509Data.Certificates) @@ -653,7 +653,7 @@ internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyIn collection.Add(certificate); break; case CertUsageType.Decryption: - decryptionIssuerSerials.Add(CreateX509IssuerSerial(certificate.IssuerName.Name, certificate.SerialNumber)); + decryptionIssuerSerials!.Add(CreateX509IssuerSerial(certificate.IssuerName.Name, certificate.SerialNumber)); break; } } @@ -674,7 +674,7 @@ internal static X509Certificate2Collection BuildBagOfCerts(KeyInfoX509Data keyIn { if (stores[index] != null) { - X509Certificate2Collection filters = null; + X509Certificate2Collection? filters = null; // We don't care if we can't open the store. try { @@ -756,9 +756,9 @@ internal static bool IsSelfSigned(X509Chain chain) return false; } - internal static AsymmetricAlgorithm GetAnyPublicKey(X509Certificate2 certificate) + internal static AsymmetricAlgorithm? GetAnyPublicKey(X509Certificate2 certificate) { - AsymmetricAlgorithm algorithm = (AsymmetricAlgorithm)certificate.GetRSAPublicKey() ?? certificate.GetECDsaPublicKey(); + AsymmetricAlgorithm? algorithm = (AsymmetricAlgorithm?)certificate.GetRSAPublicKey() ?? certificate.GetECDsaPublicKey(); #if NETCOREAPP if (algorithm is null && !OperatingSystem.IsTvOS() && !OperatingSystem.IsIOS()) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs index b31bf6a700365d..e12455290d3626 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs @@ -14,11 +14,11 @@ public class XmlDecryptionTransform : Transform { private readonly Type[] _inputTypes = { typeof(Stream), typeof(XmlDocument) }; private readonly Type[] _outputTypes = { typeof(XmlDocument) }; - private XmlNodeList _encryptedDataList; - private ArrayList _arrayListUri; // this ArrayList object represents the Uri's to be excluded - private EncryptedXml _exml; // defines the XML encryption processing rules - private XmlDocument _containingDocument; - private XmlNamespaceManager _nsm; + private XmlNodeList? _encryptedDataList; + private ArrayList? _arrayListUri; // this ArrayList object represents the Uri's to be excluded + private EncryptedXml? _exml; // defines the XML encryption processing rules + private XmlDocument? _containingDocument; + private XmlNamespaceManager? _nsm; private const string XmlDecryptionTransformNamespaceUrl = "http://www.w3.org/2002/07/decrypt#"; public XmlDecryptionTransform() @@ -28,7 +28,7 @@ public XmlDecryptionTransform() private ArrayList ExceptUris => _arrayListUri ??= new ArrayList(); - protected virtual bool IsTargetElement(XmlElement inputElement, string idValue) + protected virtual bool IsTargetElement(XmlElement? inputElement, string idValue) { if (inputElement == null) return false; @@ -46,10 +46,10 @@ public EncryptedXml EncryptedXml if (_exml != null) return _exml; - Reference reference = Reference; - SignedXml signedXml = (reference == null ? SignedXml : reference.SignedXml); + Reference? reference = Reference; + SignedXml? signedXml = (reference == null ? SignedXml : reference.SignedXml); if (signedXml == null || signedXml.EncryptedXml == null) - _exml = new EncryptedXml(_containingDocument); // default processing rules + _exml = new EncryptedXml(_containingDocument!); // default processing rules else _exml = signedXml.EncryptedXml; @@ -85,13 +85,13 @@ public override void LoadInnerXml(XmlNodeList nodeList) ExceptUris.Clear(); foreach (XmlNode node in nodeList) { - XmlElement elem = node as XmlElement; + XmlElement? elem = node as XmlElement; if (elem != null) { if (elem.LocalName == "Except" && elem.NamespaceURI == XmlDecryptionTransformNamespaceUrl) { // the Uri is required - string uri = Utils.GetAttribute(elem, "URI", XmlDecryptionTransformNamespaceUrl); + string? uri = Utils.GetAttribute(elem, "URI", XmlDecryptionTransformNamespaceUrl); if (uri == null || uri.Length == 0 || uri[0] != '#') throw new CryptographicException(SR.Cryptography_Xml_UriRequired); if (!Utils.VerifyAttributes(elem, "URI")) @@ -109,7 +109,7 @@ public override void LoadInnerXml(XmlNodeList nodeList) } } - protected override XmlNodeList GetInnerXml() + protected override XmlNodeList? GetInnerXml() { if (ExceptUris.Count == 0) return null; @@ -143,7 +143,7 @@ private void LoadStreamInput(Stream stream) XmlDocument document = new XmlDocument(); document.PreserveWhitespace = true; XmlResolver resolver = (ResolverSet ? _xmlResolver : XmlResolverHelper.GetThrowingResolver()); - XmlReader xmlReader = Utils.PreProcessStreamInput(stream, resolver, BaseURI); + XmlReader xmlReader = Utils.PreProcessStreamInput(stream, resolver, BaseURI!); document.Load(xmlReader); _containingDocument = document; _nsm = new XmlNamespaceManager(_containingDocument.NameTable); @@ -169,7 +169,7 @@ private void LoadXmlDocumentInput(XmlDocument document) // Replace the encrypted XML element with the decrypted data for signature verification private void ReplaceEncryptedData(XmlElement encryptedDataElement, byte[] decrypted) { - XmlNode parent = encryptedDataElement.ParentNode; + XmlNode parent = encryptedDataElement.ParentNode!; if (parent.NodeType == XmlNodeType.Document) { // We're replacing the root element. In order to correctly reflect the semantics of the @@ -194,13 +194,13 @@ private bool ProcessEncryptedDataItem(XmlElement encryptedDataElement) { for (int index = 0; index < ExceptUris.Count; index++) { - if (IsTargetElement(encryptedDataElement, (string)ExceptUris[index])) + if (IsTargetElement(encryptedDataElement, (string)ExceptUris[index]!)) return false; } } EncryptedData ed = new EncryptedData(); ed.LoadXml(encryptedDataElement); - SymmetricAlgorithm symAlg = EncryptedXml.GetDecryptionKey(ed, null); + SymmetricAlgorithm? symAlg = EncryptedXml.GetDecryptionKey(ed, null); if (symAlg == null) throw new CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey); byte[] decrypted = EncryptedXml.DecryptData(ed, symAlg); @@ -218,24 +218,24 @@ private void ProcessElementRecursively(XmlNodeList encryptedDatas) { encryptedDatasQueue.Enqueue(value); } - XmlNode node = encryptedDatasQueue.Dequeue() as XmlNode; + XmlNode? node = encryptedDatasQueue.Dequeue() as XmlNode; while (node != null) { - XmlElement encryptedDataElement = node as XmlElement; + XmlElement? encryptedDataElement = node as XmlElement; if (encryptedDataElement != null && encryptedDataElement.LocalName == "EncryptedData" && encryptedDataElement.NamespaceURI == EncryptedXml.XmlEncNamespaceUrl) { - XmlNode sibling = encryptedDataElement.NextSibling; - XmlNode parent = encryptedDataElement.ParentNode; + XmlNode sibling = encryptedDataElement.NextSibling!; + XmlNode parent = encryptedDataElement.ParentNode!; if (ProcessEncryptedDataItem(encryptedDataElement)) { // find the new decrypted element. - XmlNode child = parent.FirstChild; + XmlNode? child = parent.FirstChild; while (child != null && child.NextSibling != sibling) child = child.NextSibling; if (child != null) { - XmlNodeList nodes = child.SelectNodes("//enc:EncryptedData", _nsm); + XmlNodeList nodes = child.SelectNodes("//enc:EncryptedData", _nsm!)!; if (nodes.Count > 0) { foreach (XmlNode value in nodes) @@ -258,7 +258,7 @@ public override object GetOutput() if (_encryptedDataList != null) ProcessElementRecursively(_encryptedDataList); // propagate namespaces - Utils.AddNamespaces(_containingDocument.DocumentElement, PropagatedNamespaces); + Utils.AddNamespaces(_containingDocument!.DocumentElement!, PropagatedNamespaces); return _containingDocument; } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs index ed1b2b16db26ee..3cbb48b60bddee 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs @@ -12,7 +12,7 @@ public class XmlDsigBase64Transform : Transform { private readonly Type[] _inputTypes = { typeof(Stream), typeof(XmlNodeList), typeof(XmlDocument) }; private readonly Type[] _outputTypes = { typeof(Stream) }; - private CryptoStream _cs; + private CryptoStream? _cs; public XmlDsigBase64Transform() { @@ -33,7 +33,7 @@ public override void LoadInnerXml(XmlNodeList nodeList) { } - protected override XmlNodeList GetInnerXml() + protected override XmlNodeList? GetInnerXml() { return null; } @@ -52,7 +52,7 @@ public override void LoadInput(object obj) } if (obj is XmlDocument) { - LoadXmlNodeListInput(((XmlDocument)obj).SelectNodes("//.")); + LoadXmlNodeListInput(((XmlDocument)obj).SelectNodes("//.")!); return; } } @@ -93,7 +93,7 @@ private void LoadXmlNodeListInput(XmlNodeList nodeList) StringBuilder sb = new StringBuilder(); foreach (XmlNode node in nodeList) { - XmlNode result = node.SelectSingleNode("self::text()"); + XmlNode? result = node.SelectSingleNode("self::text()"); if (result != null) sb.Append(result.OuterXml); } @@ -118,14 +118,14 @@ private void LoadXmlNodeListInput(XmlNodeList nodeList) public override object GetOutput() { - return _cs; + return _cs!; } public override object GetOutput(Type type) { if (type != typeof(Stream) && !type.IsSubclassOf(typeof(Stream))) throw new ArgumentException(SR.Cryptography_Xml_TransformIncorrectInputType, nameof(type)); - return _cs; + return _cs!; } } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigC14NTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigC14NTransform.cs index d70778e8fcf370..ea087bdb0f72c3 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigC14NTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigC14NTransform.cs @@ -10,7 +10,7 @@ public class XmlDsigC14NTransform : Transform { private readonly Type[] _inputTypes = { typeof(Stream), typeof(XmlDocument), typeof(XmlNodeList) }; private readonly Type[] _outputTypes = { typeof(Stream) }; - private CanonicalXml _cXml; + private CanonicalXml? _cXml; private readonly bool _includeComments; public XmlDsigC14NTransform() @@ -40,17 +40,17 @@ public override void LoadInnerXml(XmlNodeList nodeList) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); } - protected override XmlNodeList GetInnerXml() + protected override XmlNodeList? GetInnerXml() { return null; } public override void LoadInput(object obj) { - XmlResolver resolver = (ResolverSet ? _xmlResolver : XmlResolverHelper.GetThrowingResolver()); + XmlResolver resolver = ResolverSet ? _xmlResolver : XmlResolverHelper.GetThrowingResolver(); if (obj is Stream) { - _cXml = new CanonicalXml((Stream)obj, _includeComments, resolver, BaseURI); + _cXml = new CanonicalXml((Stream)obj, _includeComments, resolver, BaseURI!); return; } if (obj is XmlDocument) @@ -70,19 +70,19 @@ public override void LoadInput(object obj) public override object GetOutput() { - return new MemoryStream(_cXml.GetBytes()); + return new MemoryStream(_cXml!.GetBytes()); } public override object GetOutput(Type type) { if (type != typeof(Stream) && !type.IsSubclassOf(typeof(Stream))) throw new ArgumentException(SR.Cryptography_Xml_TransformIncorrectInputType, nameof(type)); - return new MemoryStream(_cXml.GetBytes()); + return new MemoryStream(_cXml!.GetBytes()); } public override byte[] GetDigestedOutput(HashAlgorithm hash) { - return _cXml.GetDigestedBytes(hash); + return _cXml!.GetDigestedBytes(hash); } } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs index 3aa5b2b5cbb067..f9c7594c30dad0 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs @@ -10,10 +10,10 @@ public class XmlDsigEnvelopedSignatureTransform : Transform { private readonly Type[] _inputTypes = { typeof(Stream), typeof(XmlNodeList), typeof(XmlDocument) }; private readonly Type[] _outputTypes = { typeof(XmlNodeList), typeof(XmlDocument) }; - private XmlNodeList _inputNodeList; + private XmlNodeList? _inputNodeList; private readonly bool _includeComments; - private XmlNamespaceManager _nsm; - private XmlDocument _containingDocument; + private XmlNamespaceManager? _nsm; + private XmlDocument? _containingDocument; private int _signaturePosition; internal int SignaturePosition @@ -51,7 +51,7 @@ public override void LoadInnerXml(XmlNodeList nodeList) } // An enveloped signature has no inner XML elements - protected override XmlNodeList GetInnerXml() + protected override XmlNodeList? GetInnerXml() { return null; } @@ -79,8 +79,8 @@ private void LoadStreamInput(Stream stream) { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; - XmlResolver resolver = (ResolverSet ? _xmlResolver : XmlResolverHelper.GetThrowingResolver()); - XmlReader xmlReader = Utils.PreProcessStreamInput(stream, resolver, BaseURI); + XmlResolver resolver = ResolverSet ? _xmlResolver : XmlResolverHelper.GetThrowingResolver(); + XmlReader xmlReader = Utils.PreProcessStreamInput(stream, resolver, BaseURI!); doc.Load(xmlReader); _containingDocument = doc; if (_containingDocument == null) @@ -127,11 +127,11 @@ public override object GetOutput() { // If the position has not been set, then we don't want to remove any signature tags if (_signaturePosition == 0) return _inputNodeList; - XmlNodeList signatureList = _containingDocument.SelectNodes("//dsig:Signature", _nsm); + XmlNodeList? signatureList = _containingDocument.SelectNodes("//dsig:Signature", _nsm!); if (signatureList == null) return _inputNodeList; CanonicalXmlNodeList resultNodeList = new CanonicalXmlNodeList(); - foreach (XmlNode node in _inputNodeList) + foreach (XmlNode? node in _inputNodeList) { if (node == null) continue; // keep namespaces @@ -145,7 +145,7 @@ public override object GetOutput() try { // Find the nearest signature ancestor tag - XmlNode result = node.SelectSingleNode("ancestor-or-self::dsig:Signature[1]", _nsm); + XmlNode result = node.SelectSingleNode("ancestor-or-self::dsig:Signature[1]", _nsm!)!; int position = 0; foreach (XmlNode node1 in signatureList) { @@ -165,12 +165,12 @@ public override object GetOutput() // Else we have received either a stream or a document as input else { - XmlNodeList signatureList = _containingDocument.SelectNodes("//dsig:Signature", _nsm); + XmlNodeList? signatureList = _containingDocument.SelectNodes("//dsig:Signature", _nsm!); if (signatureList == null) return _containingDocument; if (signatureList.Count < _signaturePosition || _signaturePosition <= 0) return _containingDocument; // Remove the signature node with all its children nodes - signatureList[_signaturePosition - 1].ParentNode.RemoveChild(signatureList[_signaturePosition - 1]); + signatureList[_signaturePosition - 1]!.ParentNode!.RemoveChild(signatureList[_signaturePosition - 1]!); return _containingDocument; } } @@ -179,7 +179,7 @@ public override object GetOutput(Type type) { if (type == typeof(XmlNodeList) || type.IsSubclassOf(typeof(XmlNodeList))) { - _inputNodeList ??= Utils.AllDescendantNodes(_containingDocument, true); + _inputNodeList ??= Utils.AllDescendantNodes(_containingDocument!, true); return (XmlNodeList)GetOutput(); } else if (type == typeof(XmlDocument) || type.IsSubclassOf(typeof(XmlDocument))) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigExcC14NTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigExcC14NTransform.cs index e0007c207fc25b..844601a0adcac7 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigExcC14NTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigExcC14NTransform.cs @@ -11,8 +11,8 @@ public class XmlDsigExcC14NTransform : Transform private readonly Type[] _inputTypes = { typeof(Stream), typeof(XmlDocument), typeof(XmlNodeList) }; private readonly Type[] _outputTypes = { typeof(Stream) }; private readonly bool _includeComments; - private string _inclusiveNamespacesPrefixList; - private ExcCanonicalXml _excCanonicalXml; + private string? _inclusiveNamespacesPrefixList; + private ExcCanonicalXml? _excCanonicalXml; public XmlDsigExcC14NTransform() : this(false, null) { } @@ -20,14 +20,14 @@ public XmlDsigExcC14NTransform(bool includeComments) : this(includeComments, nul public XmlDsigExcC14NTransform(string inclusiveNamespacesPrefixList) : this(false, inclusiveNamespacesPrefixList) { } - public XmlDsigExcC14NTransform(bool includeComments, string inclusiveNamespacesPrefixList) + public XmlDsigExcC14NTransform(bool includeComments, string? inclusiveNamespacesPrefixList) { _includeComments = includeComments; _inclusiveNamespacesPrefixList = inclusiveNamespacesPrefixList; Algorithm = (includeComments ? SignedXml.XmlDsigExcC14NWithCommentsTransformUrl : SignedXml.XmlDsigExcC14NTransformUrl); } - public string InclusiveNamespacesPrefixList + public string? InclusiveNamespacesPrefixList { get { return _inclusiveNamespacesPrefixList; } set { _inclusiveNamespacesPrefixList = value; } @@ -49,7 +49,7 @@ public override void LoadInnerXml(XmlNodeList nodeList) { foreach (XmlNode n in nodeList) { - XmlElement e = n as XmlElement; + XmlElement? e = n as XmlElement; if (e != null) { if (e.LocalName.Equals("InclusiveNamespaces") @@ -77,21 +77,21 @@ public override void LoadInput(object obj) XmlResolver resolver = (ResolverSet ? _xmlResolver : XmlResolverHelper.GetThrowingResolver()); if (obj is Stream) { - _excCanonicalXml = new ExcCanonicalXml((Stream)obj, _includeComments, _inclusiveNamespacesPrefixList, resolver, BaseURI); + _excCanonicalXml = new ExcCanonicalXml((Stream)obj, _includeComments, _inclusiveNamespacesPrefixList!, resolver, BaseURI!); } else if (obj is XmlDocument) { - _excCanonicalXml = new ExcCanonicalXml((XmlDocument)obj, _includeComments, _inclusiveNamespacesPrefixList, resolver); + _excCanonicalXml = new ExcCanonicalXml((XmlDocument)obj, _includeComments, _inclusiveNamespacesPrefixList!, resolver); } else if (obj is XmlNodeList) { - _excCanonicalXml = new ExcCanonicalXml((XmlNodeList)obj, _includeComments, _inclusiveNamespacesPrefixList, resolver); + _excCanonicalXml = new ExcCanonicalXml((XmlNodeList)obj, _includeComments, _inclusiveNamespacesPrefixList!, resolver); } else throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(obj)); } - protected override XmlNodeList GetInnerXml() + protected override XmlNodeList? GetInnerXml() { if (InclusiveNamespacesPrefixList == null) return null; @@ -107,19 +107,19 @@ protected override XmlNodeList GetInnerXml() public override object GetOutput() { - return new MemoryStream(_excCanonicalXml.GetBytes()); + return new MemoryStream(_excCanonicalXml!.GetBytes()); } public override object GetOutput(Type type) { if (type != typeof(Stream) && !type.IsSubclassOf(typeof(Stream))) throw new ArgumentException(SR.Cryptography_Xml_TransformIncorrectInputType, nameof(type)); - return new MemoryStream(_excCanonicalXml.GetBytes()); + return new MemoryStream(_excCanonicalXml!.GetBytes()); } public override byte[] GetDigestedOutput(HashAlgorithm hash) { - return _excCanonicalXml.GetDigestedBytes(hash); + return _excCanonicalXml!.GetDigestedBytes(hash); } } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXPathTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXPathTransform.cs index bd5675c3640fae..136cb3285f9a5c 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXPathTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXPathTransform.cs @@ -13,9 +13,9 @@ public class XmlDsigXPathTransform : Transform { private readonly Type[] _inputTypes = { typeof(Stream), typeof(XmlNodeList), typeof(XmlDocument) }; private readonly Type[] _outputTypes = { typeof(XmlNodeList) }; - private string _xpathexpr; - private XmlDocument _document; - private XmlNamespaceManager _nsm; + private string? _xpathexpr; + private XmlDocument? _document; + private XmlNamespaceManager? _nsm; public XmlDsigXPathTransform() { @@ -40,9 +40,9 @@ public override void LoadInnerXml(XmlNodeList nodeList) foreach (XmlNode node in nodeList) { - string prefix = null; - string namespaceURI = null; - XmlElement elem = node as XmlElement; + string? prefix = null; + string? namespaceURI = null; + XmlElement? elem = node as XmlElement; if (elem != null) { if (elem.LocalName == "XPath") @@ -51,7 +51,7 @@ public override void LoadInnerXml(XmlNodeList nodeList) XmlNodeReader nr = new XmlNodeReader(elem); XmlNameTable nt = nr.NameTable; _nsm = new XmlNamespaceManager(nt); - if (!Utils.VerifyAttributes(elem, (string)null)) + if (!Utils.VerifyAttributes(elem, (string?)null)) { throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); } @@ -83,7 +83,7 @@ public override void LoadInnerXml(XmlNodeList nodeList) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); } - protected override XmlNodeList GetInnerXml() + protected override XmlNodeList? GetInnerXml() { XmlDocument document = new XmlDocument(); XmlElement element = document.CreateElement(null, "XPath", SignedXml.XmlDsigNamespaceUrl); @@ -110,7 +110,7 @@ protected override XmlNodeList GetInnerXml() } } // Add the XPath as the inner xml of the element - element.InnerXml = _xpathexpr; + element.InnerXml = _xpathexpr!; document.AppendChild(element); return document.ChildNodes; } @@ -134,7 +134,7 @@ public override void LoadInput(object obj) private void LoadStreamInput(Stream stream) { XmlResolver resolver = (ResolverSet ? _xmlResolver : XmlResolverHelper.GetThrowingResolver()); - XmlReader valReader = Utils.PreProcessStreamInput(stream, resolver, BaseURI); + XmlReader valReader = Utils.PreProcessStreamInput(stream, resolver, BaseURI!); _document = new XmlDocument(); _document.PreserveWhitespace = true; _document.Load(valReader); @@ -161,15 +161,15 @@ public override object GetOutput() CanonicalXmlNodeList resultNodeList = new CanonicalXmlNodeList(); if (!string.IsNullOrEmpty(_xpathexpr)) { - XPathNavigator navigator = _document.CreateNavigator(); + XPathNavigator navigator = _document!.CreateNavigator()!; XPathNodeIterator it = navigator.Select("//. | //@*"); XPathExpression xpathExpr = navigator.Compile("boolean(" + _xpathexpr + ")"); - xpathExpr.SetContext(_nsm); + xpathExpr.SetContext(_nsm!); while (it.MoveNext()) { - XmlNode node = ((IHasXmlNode)it.Current).GetNode(); + XmlNode node = ((IHasXmlNode)it.Current!).GetNode(); bool include = (bool)it.Current.Evaluate(xpathExpr); if (include) @@ -180,7 +180,7 @@ public override object GetOutput() it = navigator.Select("//namespace::*"); while (it.MoveNext()) { - XmlNode node = ((IHasXmlNode)it.Current).GetNode(); + XmlNode node = ((IHasXmlNode)it.Current!).GetNode(); resultNodeList.Add(node); } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs index 486888f48f13da..d536c2894f4590 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs @@ -12,9 +12,9 @@ public class XmlDsigXsltTransform : Transform { private readonly Type[] _inputTypes = { typeof(Stream), typeof(XmlDocument), typeof(XmlNodeList) }; private readonly Type[] _outputTypes = { typeof(Stream) }; - private XmlNodeList _xslNodes; - private string _xslFragment; - private Stream _inputStream; + private XmlNodeList? _xslNodes; + private string? _xslFragment; + private Stream? _inputStream; private readonly bool _includeComments; public XmlDsigXsltTransform() @@ -49,7 +49,7 @@ public override void LoadInnerXml(XmlNodeList nodeList) if (nodeList == null) throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform); // check that the XSLT element is well formed - XmlElement firstDataElement = null; + XmlElement? firstDataElement = null; int count = 0; foreach (XmlNode node in nodeList) { @@ -72,7 +72,7 @@ public override void LoadInnerXml(XmlNodeList nodeList) _xslFragment = firstDataElement.OuterXml.Trim(null); } - protected override XmlNodeList GetInnerXml() + protected override XmlNodeList? GetInnerXml() { return _xslNodes; } @@ -87,7 +87,7 @@ public override void LoadInput(object obj) } else if (obj is XmlNodeList) { - CanonicalXml xmlDoc = new CanonicalXml((XmlNodeList)obj, null, _includeComments); + CanonicalXml xmlDoc = new CanonicalXml((XmlNodeList)obj, null!, _includeComments); byte[] buffer = xmlDoc.GetBytes(); if (buffer == null) return; _inputStream.Write(buffer, 0, buffer.Length); @@ -96,7 +96,7 @@ public override void LoadInput(object obj) } else if (obj is XmlDocument) { - CanonicalXml xmlDoc = new CanonicalXml((XmlDocument)obj, null, _includeComments); + CanonicalXml xmlDoc = new CanonicalXml((XmlDocument)obj, null!, _includeComments); byte[] buffer = xmlDoc.GetBytes(); if (buffer == null) return; _inputStream.Write(buffer, 0, buffer.Length); @@ -118,13 +118,13 @@ public override object GetOutput() settings.XmlResolver = null; settings.MaxCharactersFromEntities = Utils.MaxCharactersFromEntities; settings.MaxCharactersInDocument = Utils.MaxCharactersInDocument; - using (StringReader sr = new StringReader(_xslFragment)) + using (StringReader sr = new StringReader(_xslFragment!)) { - XmlReader readerXsl = XmlReader.Create(sr, settings, (string)null); + XmlReader readerXsl = XmlReader.Create(sr, settings, (string)null!); xslt.Load(readerXsl, XsltSettings.Default, null); // Now load the input stream, XmlDocument can be used but is less efficient - XmlReader reader = XmlReader.Create(_inputStream, settings, BaseURI); + XmlReader reader = XmlReader.Create(_inputStream!, settings, BaseURI); XPathDocument inputData = new XPathDocument(reader, XmlSpace.Preserve); // Create an XmlTextWriter diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs index 5d4ec348f7288b..b19de95bb0141d 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs @@ -10,9 +10,9 @@ public class XmlLicenseTransform : Transform { private readonly Type[] _inputTypes = { typeof(XmlDocument) }; private readonly Type[] _outputTypes = { typeof(XmlDocument) }; - private XmlNamespaceManager _namespaceManager; - private XmlDocument _license; - private IRelDecryptor _relDecryptor; + private XmlNamespaceManager? _namespaceManager; + private XmlDocument? _license; + private IRelDecryptor? _relDecryptor; private const string ElementIssuer = "issuer"; private const string NamespaceUriCore = "urn:mpeg:mpeg21:2003:01-REL-R-NS"; @@ -31,7 +31,7 @@ public override Type[] OutputTypes get { return _outputTypes; } } - public IRelDecryptor Decryptor + public IRelDecryptor? Decryptor { get { return _relDecryptor; } set { _relDecryptor = value; } @@ -39,18 +39,18 @@ public IRelDecryptor Decryptor private void DecryptEncryptedGrants(XmlNodeList encryptedGrantList, IRelDecryptor decryptor) { - XmlElement encryptionMethod; - XmlElement keyInfo; - XmlElement cipherData; + XmlElement? encryptionMethod; + XmlElement? keyInfo; + XmlElement? cipherData; EncryptionMethod encryptionMethodObj; KeyInfo keyInfoObj; CipherData cipherDataObj; for (int i = 0, count = encryptedGrantList.Count; i < count; i++) { - encryptionMethod = encryptedGrantList[i].SelectSingleNode("//r:encryptedGrant/enc:EncryptionMethod", _namespaceManager) as XmlElement; - keyInfo = encryptedGrantList[i].SelectSingleNode("//r:encryptedGrant/dsig:KeyInfo", _namespaceManager) as XmlElement; - cipherData = encryptedGrantList[i].SelectSingleNode("//r:encryptedGrant/enc:CipherData", _namespaceManager) as XmlElement; + encryptionMethod = encryptedGrantList[i]!.SelectSingleNode("//r:encryptedGrant/enc:EncryptionMethod", _namespaceManager!) as XmlElement; + keyInfo = encryptedGrantList[i]!.SelectSingleNode("//r:encryptedGrant/dsig:KeyInfo", _namespaceManager!) as XmlElement; + cipherData = encryptedGrantList[i]!.SelectSingleNode("//r:encryptedGrant/enc:CipherData", _namespaceManager!) as XmlElement; if ((encryptionMethod != null) && (keyInfo != null) && (cipherData != null)) @@ -63,14 +63,14 @@ private void DecryptEncryptedGrants(XmlNodeList encryptedGrantList, IRelDecrypto keyInfoObj.LoadXml(keyInfo); cipherDataObj.LoadXml(cipherData); - MemoryStream toDecrypt = null; - Stream decryptedContent = null; - StreamReader streamReader = null; + MemoryStream? toDecrypt = null; + Stream? decryptedContent = null; + StreamReader? streamReader = null; try { - toDecrypt = new MemoryStream(cipherDataObj.CipherValue); - decryptedContent = _relDecryptor.Decrypt(encryptionMethodObj, + toDecrypt = new MemoryStream(cipherDataObj.CipherValue!); + decryptedContent = _relDecryptor!.Decrypt(encryptionMethodObj, keyInfoObj, toDecrypt); if ((decryptedContent == null) || (decryptedContent.Length == 0)) @@ -79,7 +79,8 @@ private void DecryptEncryptedGrants(XmlNodeList encryptedGrantList, IRelDecrypto streamReader = new StreamReader(decryptedContent); string clearContent = streamReader.ReadToEnd(); - encryptedGrantList[i].ParentNode.InnerXml = clearContent; + // red flag + encryptedGrantList[i]!.ParentNode!.InnerXml = clearContent; } finally { @@ -92,14 +93,14 @@ private void DecryptEncryptedGrants(XmlNodeList encryptedGrantList, IRelDecrypto } // License transform has no inner XML elements - protected override XmlNodeList GetInnerXml() + protected override XmlNodeList? GetInnerXml() { return null; } public override object GetOutput() { - return _license; + return _license!; } public override object GetOutput(Type type) @@ -130,9 +131,9 @@ public override void LoadInput(object obj) _namespaceManager.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); _namespaceManager.AddNamespace("r", NamespaceUriCore); - XmlElement currentIssuerContext; - XmlElement currentLicenseContext; - XmlNode signatureNode; + XmlElement? currentIssuerContext; + XmlElement? currentLicenseContext; + XmlNode? signatureNode; // Get the nearest issuer node currentIssuerContext = Context.SelectSingleNode("ancestor-or-self::r:issuer[1]", _namespaceManager) as XmlElement; @@ -140,27 +141,27 @@ public override void LoadInput(object obj) throw new CryptographicException(SR.Cryptography_Xml_XrmlMissingIssuer); signatureNode = currentIssuerContext.SelectSingleNode("descendant-or-self::dsig:Signature[1]", _namespaceManager) as XmlElement; - signatureNode?.ParentNode.RemoveChild(signatureNode); + signatureNode?.ParentNode!.RemoveChild(signatureNode); // Get the nearest license node currentLicenseContext = currentIssuerContext.SelectSingleNode("ancestor-or-self::r:license[1]", _namespaceManager) as XmlElement; if (currentLicenseContext == null) throw new CryptographicException(SR.Cryptography_Xml_XrmlMissingLicence); - XmlNodeList issuerList = currentLicenseContext.SelectNodes("descendant-or-self::r:license[1]/r:issuer", _namespaceManager); + XmlNodeList issuerList = currentLicenseContext.SelectNodes("descendant-or-self::r:license[1]/r:issuer", _namespaceManager)!; // Remove all issuer nodes except current for (int i = 0, count = issuerList.Count; i < count; i++) { - if (issuerList[i] == currentIssuerContext) + if (issuerList[i]! == currentIssuerContext) continue; - if ((issuerList[i].LocalName == ElementIssuer) && - (issuerList[i].NamespaceURI == NamespaceUriCore)) - issuerList[i].ParentNode.RemoveChild(issuerList[i]); + if ((issuerList[i]!.LocalName == ElementIssuer) && + (issuerList[i]!.NamespaceURI == NamespaceUriCore)) + issuerList[i]!.ParentNode!.RemoveChild(issuerList[i]!); } - XmlNodeList encryptedGrantList = currentLicenseContext.SelectNodes("/r:license/r:grant/r:encryptedGrant", _namespaceManager); + XmlNodeList encryptedGrantList = currentLicenseContext.SelectNodes("/r:license/r:grant/r:encryptedGrant", _namespaceManager)!; if (encryptedGrantList.Count > 0) { diff --git a/src/libraries/System.Security.Cryptography.Xml/tests/System.Security.Cryptography.Xml.Tests.csproj b/src/libraries/System.Security.Cryptography.Xml/tests/System.Security.Cryptography.Xml.Tests.csproj index 1d31bc399da7e2..57c47b0787b65b 100644 --- a/src/libraries/System.Security.Cryptography.Xml/tests/System.Security.Cryptography.Xml.Tests.csproj +++ b/src/libraries/System.Security.Cryptography.Xml/tests/System.Security.Cryptography.Xml.Tests.csproj @@ -1,6 +1,7 @@ $(NetCoreAppCurrent);$(NetFrameworkMinimum) + annotations