Decompiled source of System Security Cryptography Xml v8.0.100
BepInEx/core/System.Security.Cryptography.Xml/netstandard2.0/System.Security.Cryptography.Xml.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
#define TRACE using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Net; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Security.Policy; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; using FxResources.System.Security.Cryptography.Xml; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Security.Cryptography.Xml")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: UnsupportedOSPlatform("browser")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("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/.\r\n\r\nCommonly Used Types:\r\nSystem.Security.Cryptography.Xml.CipherData\r\nSystem.Security.Cryptography.Xml.CipherReference\r\nSystem.Security.Cryptography.Xml.DataObject\r\nSystem.Security.Cryptography.Xml.DataReference\r\nSystem.Security.Cryptography.Xml.DSAKeyValue\r\nSystem.Security.Cryptography.Xml.EncryptedData\r\nSystem.Security.Cryptography.Xml.EncryptedKey\r\nSystem.Security.Cryptography.Xml.EncryptedReference\r\nSystem.Security.Cryptography.Xml.EncryptedType\r\nSystem.Security.Cryptography.Xml.EncryptedXml\r\nSystem.Security.Cryptography.Xml.EncryptionMethod\r\nSystem.Security.Cryptography.Xml.EncryptionProperty\r\nSystem.Security.Cryptography.Xml.EncryptionPropertyCollection\r\nSystem.Security.Cryptography.Xml.KeyInfo\r\nSystem.Security.Cryptography.Xml.KeyInfoClause\r\nSystem.Security.Cryptography.Xml.KeyInfoEncryptedKey\r\nSystem.Security.Cryptography.Xml.KeyInfoName\r\nSystem.Security.Cryptography.Xml.KeyInfoNode\r\nSystem.Security.Cryptography.Xml.KeyInfoRetrievalMethod\r\nSystem.Security.Cryptography.Xml.KeyInfoX509Data\r\nSystem.Security.Cryptography.Xml.KeyReference\r\nSystem.Security.Cryptography.Xml.Reference\r\nSystem.Security.Cryptography.Xml.ReferenceList\r\nSystem.Security.Cryptography.Xml.RSAKeyValue\r\nSystem.Security.Cryptography.Xml.Signature\r\nSystem.Security.Cryptography.Xml.SignedInfo\r\nSystem.Security.Cryptography.Xml.SignedXml\r\nSystem.Security.Cryptography.Xml.Transform\r\nSystem.Security.Cryptography.Xml.TransformChain\r\nSystem.Security.Cryptography.Xml.XmlDecryptionTransform\r\nSystem.Security.Cryptography.Xml.XmlDsigBase64Transform\r\nSystem.Security.Cryptography.Xml.XmlDsigC14NTransform\r\nSystem.Security.Cryptography.Xml.XmlDsigC14NWithCommentsTransform\r\nSystem.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform\r\nSystem.Security.Cryptography.Xml.XmlDsigExcC14NTransform\r\nSystem.Security.Cryptography.Xml.XmlDsigExcC14NWithCommentsTransform\r\nSystem.Security.Cryptography.Xml.XmlDsigXPathTransform\r\nSystem.Security.Cryptography.Xml.XmlDsigXsltTransform\r\nSystem.Security.Cryptography.Xml.XmlLicenseTransform")] [assembly: AssemblyFileVersion("8.0.524.21615")] [assembly: AssemblyInformationalVersion("8.0.5+087e15321bb712ef6fe8b0ba6f8bd12facf92629")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Security.Cryptography.Xml")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("8.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FxResources.System.Security.Cryptography.Xml { internal static class SR { } } namespace System { internal static class HexConverter { public enum Casing : uint { Upper = 0u, Lower = 8224u } public static ReadOnlySpan<byte> CharToHexLookup => new byte[256] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (byte)num2; buffer[startingIndex] = (byte)(num2 >> 8); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper) { uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209); uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing; buffer[startingIndex + 1] = (char)(num2 & 0xFFu); buffer[startingIndex] = (char)(num2 >> 8); } public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper) { for (int i = 0; i < bytes.Length; i++) { ToCharsBuffer(bytes[i], chars, i * 2, casing); } } public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper) { Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan()); Span<char> buffer = span; int num = 0; ReadOnlySpan<byte> readOnlySpan = bytes; for (int i = 0; i < readOnlySpan.Length; i++) { byte value = readOnlySpan[i]; ToCharsBuffer(value, buffer, num, casing); num += 2; } return buffer.ToString(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharUpper(int value) { value &= 0xF; value += 48; if (value > 57) { value += 7; } return (char)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToCharLower(int value) { value &= 0xF; value += 48; if (value > 57) { value += 39; } return (char)value; } public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes) { int charsProcessed; return TryDecodeFromUtf16(chars, bytes, out charsProcessed); } public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed) { int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; while (num2 < bytes.Length) { num3 = FromChar(chars[num + 1]); num4 = FromChar(chars[num]); if ((num3 | num4) == 255) { break; } bytes[num2++] = (byte)((num4 << 4) | num3); num += 2; } if (num3 == 255) { num++; } charsProcessed = num; return (num3 | num4) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromChar(int c) { if (c < CharToHexLookup.Length) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromUpperChar(int c) { if (c <= 71) { return CharToHexLookup[c]; } return 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FromLowerChar(int c) { switch (c) { case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return c - 48; case 97: case 98: case 99: case 100: case 101: case 102: return c - 97 + 10; default: return 255; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexChar(int c) { if (IntPtr.Size == 8) { ulong num = (uint)(c - 48); ulong num2 = (ulong)(-17875860044349952L << (int)num); ulong num3 = num - 64; return (long)(num2 & num3) < 0L; } return FromChar(c) != 255; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexUpperChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 65) <= 5u; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHexLowerChar(int c) { if ((uint)(c - 48) > 9u) { return (uint)(c - 97) <= 5u; } return true; } } internal static class Obsoletions { internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}"; internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead."; internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001"; internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used."; internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002"; internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime."; internal const string CodeAccessSecurityDiagId = "SYSLIB0003"; internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported."; internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004"; internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported."; internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005"; internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException."; internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException."; internal const string ThreadAbortDiagId = "SYSLIB0006"; internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported."; internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007"; internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException."; internal const string CreatePdbGeneratorDiagId = "SYSLIB0008"; internal const string AuthenticationManagerMessage = "The AuthenticationManager Authenticate and PreAuthenticate methods are not supported and throw PlatformNotSupportedException."; internal const string AuthenticationManagerDiagId = "SYSLIB0009"; internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException."; internal const string RemotingApisDiagId = "SYSLIB0010"; internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information."; internal const string BinaryFormatterDiagId = "SYSLIB0011"; internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead."; internal const string CodeBaseDiagId = "SYSLIB0012"; internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead."; internal const string EscapeUriStringDiagId = "SYSLIB0013"; internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead."; internal const string WebRequestDiagId = "SYSLIB0014"; internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+."; internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015"; internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations."; internal const string GetContextInfoDiagId = "SYSLIB0016"; internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException."; internal const string StrongNameKeyPairDiagId = "SYSLIB0017"; internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException."; internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018"; internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException."; internal const string RuntimeEnvironmentDiagId = "SYSLIB0019"; internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull."; internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020"; internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead."; internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021"; internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead."; internal const string RijndaelDiagId = "SYSLIB0022"; internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead."; internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023"; internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception."; internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024"; internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+."; internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025"; internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use the appropriate constructor to create a new certificate."; internal const string X509CertificateImmutableDiagId = "SYSLIB0026"; internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey."; internal const string PublicKeyPropertyDiagId = "SYSLIB0027"; internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key."; internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028"; internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported."; internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029"; internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter."; internal const string UseManagedSha1DiagId = "SYSLIB0030"; internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1."; internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031"; internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored."; internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032"; internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead."; internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033"; internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead."; internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034"; internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner."; internal const string SignerInfoCounterSigDiagId = "SYSLIB0035"; internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead."; internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036"; internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported."; internal const string AssemblyNameMembersDiagId = "SYSLIB0037"; internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information."; internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038"; internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults."; internal const string TlsVersion10and11DiagId = "SYSLIB0039"; internal const string EncryptionPolicyMessage = "EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code."; internal const string EncryptionPolicyDiagId = "SYSLIB0040"; internal const string Rfc2898OutdatedCtorMessage = "The default hash algorithm and iteration counts in Rfc2898DeriveBytes constructors are outdated and insecure. Use a constructor that accepts the hash algorithm and the number of iterations."; internal const string Rfc2898OutdatedCtorDiagId = "SYSLIB0041"; internal const string EccXmlExportImportMessage = "ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys."; internal const string EccXmlExportImportDiagId = "SYSLIB0042"; internal const string EcDhPublicKeyBlobMessage = "ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead."; internal const string EcDhPublicKeyBlobDiagId = "SYSLIB0043"; internal const string AssemblyNameCodeBaseMessage = "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported."; internal const string AssemblyNameCodeBaseDiagId = "SYSLIB0044"; internal const string CryptoStringFactoryMessage = "Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead."; internal const string CryptoStringFactoryDiagId = "SYSLIB0045"; internal const string ControlledExecutionRunMessage = "ControlledExecution.Run method may corrupt the process and should not be used in production code."; internal const string ControlledExecutionRunDiagId = "SYSLIB0046"; internal const string XmlSecureResolverMessage = "XmlSecureResolver is obsolete. Use XmlResolver.ThrowingResolver instead when attempting to forbid XML external entity resolution."; internal const string XmlSecureResolverDiagId = "SYSLIB0047"; internal const string RsaEncryptDecryptValueMessage = "RSA.EncryptValue and DecryptValue are not supported and throw NotSupportedException. Use RSA.Encrypt and RSA.Decrypt instead."; internal const string RsaEncryptDecryptDiagId = "SYSLIB0048"; internal const string JsonSerializerOptionsAddContextMessage = "JsonSerializerOptions.AddContext is obsolete. To register a JsonSerializerContext, use either the TypeInfoResolver or TypeInfoResolverChain properties."; internal const string JsonSerializerOptionsAddContextDiagId = "SYSLIB0049"; internal const string LegacyFormatterMessage = "Formatter-based serialization is obsolete and should not be used."; internal const string LegacyFormatterDiagId = "SYSLIB0050"; internal const string LegacyFormatterImplMessage = "This API supports obsolete formatter-based serialization. It should not be called or extended by application code."; internal const string LegacyFormatterImplDiagId = "SYSLIB0051"; internal const string RegexExtensibilityImplMessage = "This API supports obsolete mechanisms for Regex extensibility. It is not supported."; internal const string RegexExtensibilityDiagId = "SYSLIB0052"; internal const string AesGcmTagConstructorMessage = "AesGcm should indicate the required tag size for encryption and decryption. Use a constructor that accepts the tag size."; internal const string AesGcmTagConstructorDiagId = "SYSLIB0053"; } internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string ArgumentOutOfRange_IndexMustBeLess => GetResourceString("ArgumentOutOfRange_IndexMustBeLess"); internal static string ArgumentOutOfRange_IndexMustBeLessOrEqual => GetResourceString("ArgumentOutOfRange_IndexMustBeLessOrEqual"); internal static string Arg_EmptyOrNullString => GetResourceString("Arg_EmptyOrNullString"); internal static string Cryptography_Partial_Chain => GetResourceString("Cryptography_Partial_Chain"); internal static string Cryptography_Xml_BadWrappedKeySize => GetResourceString("Cryptography_Xml_BadWrappedKeySize"); internal static string Cryptography_Xml_CipherValueElementRequired => GetResourceString("Cryptography_Xml_CipherValueElementRequired"); internal static string Cryptography_Xml_CreateHashAlgorithmFailed => GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed"); internal static string Cryptography_Xml_CreateTransformFailed => GetResourceString("Cryptography_Xml_CreateTransformFailed"); internal static string Cryptography_Xml_CreatedKeyFailed => GetResourceString("Cryptography_Xml_CreatedKeyFailed"); internal static string Cryptography_Xml_DigestMethodRequired => GetResourceString("Cryptography_Xml_DigestMethodRequired"); internal static string Cryptography_Xml_DigestValueRequired => GetResourceString("Cryptography_Xml_DigestValueRequired"); internal static string Cryptography_Xml_EnvelopedSignatureRequiresContext => GetResourceString("Cryptography_Xml_EnvelopedSignatureRequiresContext"); internal static string Cryptography_Xml_InvalidElement => GetResourceString("Cryptography_Xml_InvalidElement"); internal static string Cryptography_Xml_InvalidEncryptionProperty => GetResourceString("Cryptography_Xml_InvalidEncryptionProperty"); internal static string Cryptography_Xml_InvalidKeySize => GetResourceString("Cryptography_Xml_InvalidKeySize"); internal static string Cryptography_Xml_InvalidReference => GetResourceString("Cryptography_Xml_InvalidReference"); internal static string Cryptography_Xml_InvalidSignatureLength => GetResourceString("Cryptography_Xml_InvalidSignatureLength"); internal static string Cryptography_Xml_InvalidSignatureLength2 => GetResourceString("Cryptography_Xml_InvalidSignatureLength2"); internal static string Cryptography_Xml_InvalidX509IssuerSerialNumber => GetResourceString("Cryptography_Xml_InvalidX509IssuerSerialNumber"); internal static string Cryptography_Xml_KeyInfoRequired => GetResourceString("Cryptography_Xml_KeyInfoRequired"); internal static string Cryptography_Xml_KW_BadKeySize => GetResourceString("Cryptography_Xml_KW_BadKeySize"); internal static string Cryptography_Xml_LoadKeyFailed => GetResourceString("Cryptography_Xml_LoadKeyFailed"); internal static string Cryptography_Xml_MissingAlgorithm => GetResourceString("Cryptography_Xml_MissingAlgorithm"); internal static string Cryptography_Xml_MissingCipherData => GetResourceString("Cryptography_Xml_MissingCipherData"); internal static string Cryptography_Xml_MissingDecryptionKey => GetResourceString("Cryptography_Xml_MissingDecryptionKey"); internal static string Cryptography_Xml_MissingEncryptionKey => GetResourceString("Cryptography_Xml_MissingEncryptionKey"); internal static string Cryptography_Xml_NotSupportedCryptographicTransform => GetResourceString("Cryptography_Xml_NotSupportedCryptographicTransform"); internal static string Cryptography_Xml_ReferenceElementRequired => GetResourceString("Cryptography_Xml_ReferenceElementRequired"); internal static string Cryptography_Xml_ReferenceTypeRequired => GetResourceString("Cryptography_Xml_ReferenceTypeRequired"); internal static string Cryptography_Xml_SelfReferenceRequiresContext => GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"); internal static string Cryptography_Xml_SignatureDescriptionNotCreated => GetResourceString("Cryptography_Xml_SignatureDescriptionNotCreated"); internal static string Cryptography_Xml_SignatureMethodKeyMismatch => GetResourceString("Cryptography_Xml_SignatureMethodKeyMismatch"); internal static string Cryptography_Xml_SignatureMethodRequired => GetResourceString("Cryptography_Xml_SignatureMethodRequired"); internal static string Cryptography_Xml_SignatureValueRequired => GetResourceString("Cryptography_Xml_SignatureValueRequired"); internal static string Cryptography_Xml_SignedInfoRequired => GetResourceString("Cryptography_Xml_SignedInfoRequired"); internal static string Cryptography_Xml_TransformIncorrectInputType => GetResourceString("Cryptography_Xml_TransformIncorrectInputType"); internal static string Cryptography_Xml_IncorrectObjectType => GetResourceString("Cryptography_Xml_IncorrectObjectType"); internal static string Cryptography_Xml_UnknownTransform => GetResourceString("Cryptography_Xml_UnknownTransform"); internal static string Cryptography_Xml_UriNotResolved => GetResourceString("Cryptography_Xml_UriNotResolved"); internal static string Cryptography_Xml_UriNotSupported => GetResourceString("Cryptography_Xml_UriNotSupported"); internal static string Cryptography_Xml_UriRequired => GetResourceString("Cryptography_Xml_UriRequired"); internal static string Cryptography_Xml_XrmlMissingContext => GetResourceString("Cryptography_Xml_XrmlMissingContext"); internal static string Cryptography_Xml_XrmlMissingIRelDecryptor => GetResourceString("Cryptography_Xml_XrmlMissingIRelDecryptor"); internal static string Cryptography_Xml_XrmlMissingIssuer => GetResourceString("Cryptography_Xml_XrmlMissingIssuer"); internal static string Cryptography_Xml_XrmlMissingLicence => GetResourceString("Cryptography_Xml_XrmlMissingLicence"); internal static string Cryptography_Xml_XrmlUnableToDecryptGrant => GetResourceString("Cryptography_Xml_XrmlUnableToDecryptGrant"); internal static string NotSupported_KeyAlgorithm => GetResourceString("NotSupported_KeyAlgorithm"); internal static string Log_ActualHashValue => GetResourceString("Log_ActualHashValue"); internal static string Log_BeginCanonicalization => GetResourceString("Log_BeginCanonicalization"); internal static string Log_BeginSignatureComputation => GetResourceString("Log_BeginSignatureComputation"); internal static string Log_BeginSignatureVerification => GetResourceString("Log_BeginSignatureVerification"); internal static string Log_BuildX509Chain => GetResourceString("Log_BuildX509Chain"); internal static string Log_CanonicalizationSettings => GetResourceString("Log_CanonicalizationSettings"); internal static string Log_CanonicalizedOutput => GetResourceString("Log_CanonicalizedOutput"); internal static string Log_CertificateChain => GetResourceString("Log_CertificateChain"); internal static string Log_CheckSignatureFormat => GetResourceString("Log_CheckSignatureFormat"); internal static string Log_CheckSignedInfo => GetResourceString("Log_CheckSignedInfo"); internal static string Log_FormatValidationSuccessful => GetResourceString("Log_FormatValidationSuccessful"); internal static string Log_FormatValidationNotSuccessful => GetResourceString("Log_FormatValidationNotSuccessful"); internal static string Log_KeyUsages => GetResourceString("Log_KeyUsages"); internal static string Log_NoNamespacesPropagated => GetResourceString("Log_NoNamespacesPropagated"); internal static string Log_PropagatingNamespace => GetResourceString("Log_PropagatingNamespace"); internal static string Log_RawSignatureValue => GetResourceString("Log_RawSignatureValue"); internal static string Log_ReferenceHash => GetResourceString("Log_ReferenceHash"); internal static string Log_RevocationMode => GetResourceString("Log_RevocationMode"); internal static string Log_RevocationFlag => GetResourceString("Log_RevocationFlag"); internal static string Log_SigningAsymmetric => GetResourceString("Log_SigningAsymmetric"); internal static string Log_SigningHmac => GetResourceString("Log_SigningHmac"); internal static string Log_SigningReference => GetResourceString("Log_SigningReference"); internal static string Log_TransformedReferenceContents => GetResourceString("Log_TransformedReferenceContents"); internal static string Log_UnsafeCanonicalizationMethod => GetResourceString("Log_UnsafeCanonicalizationMethod"); internal static string Log_UrlTimeout => GetResourceString("Log_UrlTimeout"); internal static string Log_VerificationFailed => GetResourceString("Log_VerificationFailed"); internal static string Log_VerificationFailed_References => GetResourceString("Log_VerificationFailed_References"); internal static string Log_VerificationFailed_SignedInfo => GetResourceString("Log_VerificationFailed_SignedInfo"); internal static string Log_VerificationFailed_X509Chain => GetResourceString("Log_VerificationFailed_X509Chain"); internal static string Log_VerificationFailed_X509KeyUsage => GetResourceString("Log_VerificationFailed_X509KeyUsage"); internal static string Log_VerificationFlag => GetResourceString("Log_VerificationFlag"); internal static string Log_VerificationTime => GetResourceString("Log_VerificationTime"); internal static string Log_VerificationWithKeySuccessful => GetResourceString("Log_VerificationWithKeySuccessful"); internal static string Log_VerificationWithKeyNotSuccessful => GetResourceString("Log_VerificationWithKeyNotSuccessful"); internal static string Log_VerifyReference => GetResourceString("Log_VerifyReference"); internal static string Log_VerifySignedInfoAsymmetric => GetResourceString("Log_VerifySignedInfoAsymmetric"); internal static string Log_VerifySignedInfoHmac => GetResourceString("Log_VerifySignedInfoHmac"); internal static string Log_X509ChainError => GetResourceString("Log_X509ChainError"); internal static string Log_XmlContext => GetResourceString("Log_XmlContext"); internal static string Log_SignedXmlRecursionLimit => GetResourceString("Log_SignedXmlRecursionLimit"); internal static string Log_UnsafeTransformMethod => GetResourceString("Log_UnsafeTransformMethod"); internal static string ElementCombinationMissing => GetResourceString("ElementCombinationMissing"); internal static string ElementMissing => GetResourceString("ElementMissing"); internal static string MustContainChildElement => GetResourceString("MustContainChildElement"); internal static string WrongRootElement => GetResourceString("WrongRootElement"); internal static string Cryptography_Xml_EntityResolutionNotSupported => GetResourceString("Cryptography_Xml_EntityResolutionNotSupported"); internal static string Cryptography_Xml_XsltRequiresDynamicCode => GetResourceString("Cryptography_Xml_XsltRequiresDynamicCode"); internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } } namespace System.Runtime.Versioning { internal abstract class OSPlatformAttribute : Attribute { public string PlatformName { get; } private protected OSPlatformAttribute(string platformName) { PlatformName = platformName; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetPlatformAttribute : OSPlatformAttribute { public TargetPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformAttribute : OSPlatformAttribute { public SupportedOSPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute { public string Message { get; } public UnsupportedOSPlatformAttribute(string platformName) : base(platformName) { } public UnsupportedOSPlatformAttribute(string platformName, string message) : base(platformName) { Message = message; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class ObsoletedOSPlatformAttribute : OSPlatformAttribute { public string Message { get; } public string Url { get; set; } public ObsoletedOSPlatformAttribute(string platformName) : base(platformName) { } public ObsoletedOSPlatformAttribute(string platformName, string message) : base(platformName) { Message = message; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute { public SupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute { public UnsupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresUnreferencedCodeAttribute : Attribute { public string Message { get; } public string Url { get; set; } public RequiresUnreferencedCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] internal sealed class UnconditionalSuppressMessageAttribute : Attribute { public string Category { get; } public string CheckId { get; } public string Scope { get; set; } public string Target { get; set; } public string MessageId { get; set; } public string Justification { get; set; } public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresDynamicCodeAttribute : Attribute { public string Message { get; } public string Url { get; set; } public RequiresDynamicCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace System.Security.Cryptography.Xml { internal abstract class AncestralNamespaceContextManager { internal ArrayList _ancestorStack = new ArrayList(); internal NamespaceFrame GetScopeAt(int i) { return (NamespaceFrame)_ancestorStack[i]; } internal NamespaceFrame GetCurrentScope() { return GetScopeAt(_ancestorStack.Count - 1); } protected XmlAttribute GetNearestRenderedNamespaceWithMatchingPrefix(string nsPrefix, out int depth) { depth = -1; for (int num = _ancestorStack.Count - 1; num >= 0; num--) { XmlAttribute rendered; if ((rendered = GetScopeAt(num).GetRendered(nsPrefix)) != null) { depth = num; return rendered; } } return null; } protected XmlAttribute GetNearestUnrenderedNamespaceWithMatchingPrefix(string nsPrefix, out int depth) { depth = -1; for (int num = _ancestorStack.Count - 1; num >= 0; num--) { XmlAttribute unrendered; if ((unrendered = GetScopeAt(num).GetUnrendered(nsPrefix)) != null) { depth = num; return unrendered; } } return null; } internal void EnterElementContext() { _ancestorStack.Add(new NamespaceFrame()); } internal void ExitElementContext() { _ancestorStack.RemoveAt(_ancestorStack.Count - 1); } internal abstract void TrackNamespaceNode(XmlAttribute attr, SortedList nsListToRender, Hashtable nsLocallyDeclared); internal abstract void TrackXmlNamespaceNode(XmlAttribute attr, SortedList nsListToRender, SortedList attrListToRender, Hashtable nsLocallyDeclared); internal abstract void GetNamespacesToRender(XmlElement element, SortedList attrListToRender, SortedList nsListToRender, Hashtable nsLocallyDeclared); internal void LoadUnrenderedNamespaces(Hashtable nsLocallyDeclared) { object[] array = new object[nsLocallyDeclared.Count]; nsLocallyDeclared.Values.CopyTo(array, 0); object[] array2 = array; foreach (object obj in array2) { AddUnrendered((XmlAttribute)obj); } } internal void LoadRenderedNamespaces(SortedList nsRenderedList) { foreach (object key in nsRenderedList.GetKeyList()) { AddRendered((XmlAttribute)key); } } internal void AddRendered(XmlAttribute attr) { GetCurrentScope().AddRendered(attr); } internal void AddUnrendered(XmlAttribute attr) { GetCurrentScope().AddUnrendered(attr); } } internal sealed class AttributeSortOrder : IComparer { internal AttributeSortOrder() { } public int Compare(object a, object b) { XmlNode xmlNode = a as XmlNode; XmlNode xmlNode2 = b as XmlNode; if (xmlNode == null || xmlNode2 == null) { throw new ArgumentException(); } int num = string.CompareOrdinal(xmlNode.NamespaceURI, xmlNode2.NamespaceURI); if (num != 0) { return num; } return string.CompareOrdinal(xmlNode.LocalName, xmlNode2.LocalName); } } internal sealed class C14NAncestralNamespaceContextManager : AncestralNamespaceContextManager { internal C14NAncestralNamespaceContextManager() { } private void GetNamespaceToRender(string nsPrefix, SortedList attrListToRender, SortedList nsListToRender, Hashtable nsLocallyDeclared) { foreach (object key in nsListToRender.GetKeyList()) { if (Utils.HasNamespacePrefix((XmlAttribute)key, nsPrefix)) { return; } } foreach (object key2 in attrListToRender.GetKeyList()) { if (((XmlAttribute)key2).LocalName.Equals(nsPrefix)) { return; } } XmlAttribute xmlAttribute = (XmlAttribute)nsLocallyDeclared[nsPrefix]; int depth; XmlAttribute nearestRenderedNamespaceWithMatchingPrefix = GetNearestRenderedNamespaceWithMatchingPrefix(nsPrefix, out depth); if (xmlAttribute != null) { if (Utils.IsNonRedundantNamespaceDecl(xmlAttribute, nearestRenderedNamespaceWithMatchingPrefix)) { nsLocallyDeclared.Remove(nsPrefix); if (Utils.IsXmlNamespaceNode(xmlAttribute)) { attrListToRender.Add(xmlAttribute, null); } else { nsListToRender.Add(xmlAttribute, null); } } return; } int depth2; XmlAttribute nearestUnrenderedNamespaceWithMatchingPrefix = GetNearestUnrenderedNamespaceWithMatchingPrefix(nsPrefix, out depth2); if (nearestUnrenderedNamespaceWithMatchingPrefix != null && depth2 > depth && Utils.IsNonRedundantNamespaceDecl(nearestUnrenderedNamespaceWithMatchingPrefix, nearestRenderedNamespaceWithMatchingPrefix)) { if (Utils.IsXmlNamespaceNode(nearestUnrenderedNamespaceWithMatchingPrefix)) { attrListToRender.Add(nearestUnrenderedNamespaceWithMatchingPrefix, null); } else { nsListToRender.Add(nearestUnrenderedNamespaceWithMatchingPrefix, null); } } } internal override void GetNamespacesToRender(XmlElement element, SortedList attrListToRender, SortedList nsListToRender, Hashtable nsLocallyDeclared) { object[] array = new object[nsLocallyDeclared.Count]; nsLocallyDeclared.Values.CopyTo(array, 0); object[] array2 = array; foreach (object obj in array2) { XmlAttribute xmlAttribute = (XmlAttribute)obj; int depth; XmlAttribute nearestRenderedNamespaceWithMatchingPrefix = GetNearestRenderedNamespaceWithMatchingPrefix(Utils.GetNamespacePrefix(xmlAttribute), out depth); if (Utils.IsNonRedundantNamespaceDecl(xmlAttribute, nearestRenderedNamespaceWithMatchingPrefix)) { nsLocallyDeclared.Remove(Utils.GetNamespacePrefix(xmlAttribute)); if (Utils.IsXmlNamespaceNode(xmlAttribute)) { attrListToRender.Add(xmlAttribute, null); } else { nsListToRender.Add(xmlAttribute, null); } } } for (int num = _ancestorStack.Count - 1; num >= 0; num--) { foreach (object value in GetScopeAt(num).GetUnrendered().Values) { XmlAttribute xmlAttribute = (XmlAttribute)value; if (xmlAttribute != null) { GetNamespaceToRender(Utils.GetNamespacePrefix(xmlAttribute), attrListToRender, nsListToRender, nsLocallyDeclared); } } } } internal override void TrackNamespaceNode(XmlAttribute attr, SortedList nsListToRender, Hashtable nsLocallyDeclared) { nsLocallyDeclared.Add(Utils.GetNamespacePrefix(attr), attr); } internal override void TrackXmlNamespaceNode(XmlAttribute attr, SortedList nsListToRender, SortedList attrListToRender, Hashtable nsLocallyDeclared) { nsLocallyDeclared.Add(Utils.GetNamespacePrefix(attr), attr); } } internal static class CanonicalizationDispatcher { public static void Write(XmlNode node, StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (node is ICanonicalizableNode) { ((ICanonicalizableNode)node).Write(strBuilder, docPos, anc); } else { WriteGenericNode(node, strBuilder, docPos, anc); } } public static void WriteGenericNode(XmlNode node, StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (node == null) { throw new ArgumentNullException("node"); } XmlNodeList childNodes = node.ChildNodes; foreach (XmlNode item in childNodes) { Write(item, strBuilder, docPos, anc); } } public static void WriteHash(XmlNode node, HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (node is ICanonicalizableNode) { ((ICanonicalizableNode)node).WriteHash(hash, docPos, anc); } else { WriteHashGenericNode(node, hash, docPos, anc); } } public static void WriteHashGenericNode(XmlNode node, HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (node == null) { throw new ArgumentNullException("node"); } XmlNodeList childNodes = node.ChildNodes; foreach (XmlNode item in childNodes) { WriteHash(item, hash, docPos, anc); } } } internal sealed class CanonicalXml { private readonly CanonicalXmlDocument _c14nDoc; private readonly C14NAncestralNamespaceContextManager _ancMgr; internal CanonicalXml(Stream inputStream, bool includeComments, XmlResolver resolver, string strBaseUri) { if (inputStream == null) { throw new ArgumentNullException("inputStream"); } _c14nDoc = new CanonicalXmlDocument(defaultNodeSetInclusionState: true, includeComments); _c14nDoc.XmlResolver = resolver; _c14nDoc.Load(Utils.PreProcessStreamInput(inputStream, resolver, strBaseUri)); _ancMgr = new C14NAncestralNamespaceContextManager(); } internal CanonicalXml(XmlDocument document, XmlResolver resolver) : this(document, resolver, includeComments: false) { } internal CanonicalXml(XmlDocument document, XmlResolver resolver, bool includeComments) { if (document == null) { throw new ArgumentNullException("document"); } _c14nDoc = new CanonicalXmlDocument(defaultNodeSetInclusionState: true, includeComments); _c14nDoc.XmlResolver = resolver; _c14nDoc.Load(new XmlNodeReader(document)); _ancMgr = new C14NAncestralNamespaceContextManager(); } internal CanonicalXml(XmlNodeList nodeList, XmlResolver resolver, bool includeComments) { if (nodeList == null) { throw new ArgumentNullException("nodeList"); } XmlDocument ownerDocument = Utils.GetOwnerDocument(nodeList); if (ownerDocument == null) { throw new ArgumentException("nodeList"); } _c14nDoc = new CanonicalXmlDocument(defaultNodeSetInclusionState: false, includeComments); _c14nDoc.XmlResolver = resolver; _c14nDoc.Load(new XmlNodeReader(ownerDocument)); _ancMgr = new C14NAncestralNamespaceContextManager(); MarkInclusionStateForNodes(nodeList, ownerDocument, _c14nDoc); } private static void MarkNodeAsIncluded(XmlNode node) { if (node is ICanonicalizableNode) { ((ICanonicalizableNode)node).IsInNodeSet = true; } } private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument inputRoot, XmlDocument root) { CanonicalXmlNodeList canonicalXmlNodeList = new CanonicalXmlNodeList(); CanonicalXmlNodeList canonicalXmlNodeList2 = new CanonicalXmlNodeList(); canonicalXmlNodeList.Add(inputRoot); canonicalXmlNodeList2.Add(root); int num = 0; do { XmlNode xmlNode = canonicalXmlNodeList[num]; XmlNode xmlNode2 = canonicalXmlNodeList2[num]; XmlNodeList childNodes = xmlNode.ChildNodes; XmlNodeList childNodes2 = xmlNode2.ChildNodes; for (int i = 0; i < childNodes.Count; i++) { canonicalXmlNodeList.Add(childNodes[i]); canonicalXmlNodeList2.Add(childNodes2[i]); if (Utils.NodeInList(childNodes[i], nodeList)) { MarkNodeAsIncluded(childNodes2[i]); } XmlAttributeCollection attributes = childNodes[i].Attributes; if (attributes == null) { continue; } for (int j = 0; j < attributes.Count; j++) { if (Utils.NodeInList(attributes[j], nodeList)) { MarkNodeAsIncluded(childNodes2[i].Attributes.Item(j)); } } } num++; } while (num < canonicalXmlNodeList.Count); } internal byte[] GetBytes() { StringBuilder stringBuilder = new StringBuilder(); _c14nDoc.Write(stringBuilder, DocPosition.BeforeRootElement, _ancMgr); return Encoding.UTF8.GetBytes(stringBuilder.ToString()); } internal byte[] GetDigestedBytes(HashAlgorithm hash) { _c14nDoc.WriteHash(hash, DocPosition.BeforeRootElement, _ancMgr); hash.TransformFinalBlock(Array.Empty<byte>(), 0, 0); byte[] result = (byte[])hash.Hash.Clone(); hash.Initialize(); return result; } } internal sealed class CanonicalXmlAttribute : XmlAttribute, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlAttribute(string prefix, string localName, string namespaceURI, XmlDocument doc, bool defaultNodeSetInclusionState) : base(prefix, localName, namespaceURI, doc) { IsInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { strBuilder.Append(" " + Name + "=\""); strBuilder.Append(Utils.EscapeAttributeValue(Value)); strBuilder.Append('"'); } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { byte[] bytes = Encoding.UTF8.GetBytes(" " + Name + "=\""); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); bytes = Encoding.UTF8.GetBytes(Utils.EscapeAttributeValue(Value)); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); bytes = "\""u8.ToArray(); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } internal sealed class CanonicalXmlCDataSection : XmlCDataSection, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlCDataSection(string data, XmlDocument doc, bool defaultNodeSetInclusionState) : base(data, doc) { _isInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { strBuilder.Append(Utils.EscapeCData(Data)); } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { byte[] bytes = Encoding.UTF8.GetBytes(Utils.EscapeCData(Data)); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } } internal sealed class CanonicalXmlComment : XmlComment, ICanonicalizableNode { private bool _isInNodeSet; private readonly bool _includeComments; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public bool IncludeComments => _includeComments; public CanonicalXmlComment(string comment, XmlDocument doc, bool defaultNodeSetInclusionState, bool includeComments) : base(comment, doc) { _isInNodeSet = defaultNodeSetInclusionState; _includeComments = includeComments; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet && IncludeComments) { if (docPos == DocPosition.AfterRootElement) { strBuilder.Append('\n'); } strBuilder.Append("<!--"); strBuilder.Append(Value); strBuilder.Append("-->"); if (docPos == DocPosition.BeforeRootElement) { strBuilder.Append('\n'); } } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet && IncludeComments) { byte[] array; if (docPos == DocPosition.AfterRootElement) { array = "(char) 10"u8.ToArray(); hash.TransformBlock(array, 0, array.Length, array, 0); } array = "<!--"u8.ToArray(); hash.TransformBlock(array, 0, array.Length, array, 0); array = Encoding.UTF8.GetBytes(Value); hash.TransformBlock(array, 0, array.Length, array, 0); array = "-->"u8.ToArray(); hash.TransformBlock(array, 0, array.Length, array, 0); if (docPos == DocPosition.BeforeRootElement) { array = "(char) 10"u8.ToArray(); hash.TransformBlock(array, 0, array.Length, array, 0); } } } } internal sealed class CanonicalXmlDocument : XmlDocument, ICanonicalizableNode { private readonly bool _defaultNodeSetInclusionState; private readonly bool _includeComments; private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlDocument(bool defaultNodeSetInclusionState, bool includeComments) { base.PreserveWhitespace = true; _includeComments = includeComments; _isInNodeSet = (_defaultNodeSetInclusionState = defaultNodeSetInclusionState); } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { docPos = DocPosition.BeforeRootElement; foreach (XmlNode childNode in ChildNodes) { if (childNode.NodeType == XmlNodeType.Element) { CanonicalizationDispatcher.Write(childNode, strBuilder, DocPosition.InRootElement, anc); docPos = DocPosition.AfterRootElement; } else { CanonicalizationDispatcher.Write(childNode, strBuilder, docPos, anc); } } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { docPos = DocPosition.BeforeRootElement; foreach (XmlNode childNode in ChildNodes) { if (childNode.NodeType == XmlNodeType.Element) { CanonicalizationDispatcher.WriteHash(childNode, hash, DocPosition.InRootElement, anc); docPos = DocPosition.AfterRootElement; } else { CanonicalizationDispatcher.WriteHash(childNode, hash, docPos, anc); } } } 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) { return new CanonicalXmlAttribute(prefix, localName, namespaceURI, this, _defaultNodeSetInclusionState); } protected override XmlAttribute CreateDefaultAttribute(string prefix, string localName, string namespaceURI) { return new CanonicalXmlAttribute(prefix, localName, namespaceURI, this, _defaultNodeSetInclusionState); } public override XmlText CreateTextNode(string text) { return new CanonicalXmlText(text, this, _defaultNodeSetInclusionState); } public override XmlWhitespace CreateWhitespace(string prefix) { return new CanonicalXmlWhitespace(prefix, this, _defaultNodeSetInclusionState); } public override XmlSignificantWhitespace CreateSignificantWhitespace(string text) { return new CanonicalXmlSignificantWhitespace(text, this, _defaultNodeSetInclusionState); } public override XmlProcessingInstruction CreateProcessingInstruction(string target, string data) { return new CanonicalXmlProcessingInstruction(target, data, this, _defaultNodeSetInclusionState); } public override XmlComment CreateComment(string data) { return new CanonicalXmlComment(data, this, _defaultNodeSetInclusionState, _includeComments); } public override XmlEntityReference CreateEntityReference(string name) { return new CanonicalXmlEntityReference(name, this, _defaultNodeSetInclusionState); } public override XmlCDataSection CreateCDataSection(string data) { return new CanonicalXmlCDataSection(data, this, _defaultNodeSetInclusionState); } } internal sealed class CanonicalXmlElement : XmlElement, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlElement(string prefix, string localName, string namespaceURI, XmlDocument doc, bool defaultNodeSetInclusionState) : base(prefix, localName, namespaceURI, doc) { _isInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { Hashtable nsLocallyDeclared = new Hashtable(); SortedList sortedList = new SortedList(new NamespaceSortOrder()); SortedList sortedList2 = new SortedList(new AttributeSortOrder()); XmlAttributeCollection attributes = Attributes; if (attributes != null) { foreach (XmlAttribute item in attributes) { if (((CanonicalXmlAttribute)item).IsInNodeSet || Utils.IsNamespaceNode(item) || Utils.IsXmlNamespaceNode(item)) { if (Utils.IsNamespaceNode(item)) { anc.TrackNamespaceNode(item, sortedList, nsLocallyDeclared); } else if (Utils.IsXmlNamespaceNode(item)) { anc.TrackXmlNamespaceNode(item, sortedList, sortedList2, nsLocallyDeclared); } else if (IsInNodeSet) { sortedList2.Add(item, null); } } } } if (!Utils.IsCommittedNamespace(this, Prefix, NamespaceURI)) { string name = ((Prefix.Length > 0) ? ("xmlns:" + Prefix) : "xmlns"); XmlAttribute xmlAttribute2 = OwnerDocument.CreateAttribute(name); xmlAttribute2.Value = NamespaceURI; anc.TrackNamespaceNode(xmlAttribute2, sortedList, nsLocallyDeclared); } if (IsInNodeSet) { anc.GetNamespacesToRender(this, sortedList2, sortedList, nsLocallyDeclared); strBuilder.Append('<').Append(Name); foreach (object key in sortedList.GetKeyList()) { (key as CanonicalXmlAttribute).Write(strBuilder, docPos, anc); } foreach (object key2 in sortedList2.GetKeyList()) { (key2 as CanonicalXmlAttribute).Write(strBuilder, docPos, anc); } strBuilder.Append('>'); } anc.EnterElementContext(); anc.LoadUnrenderedNamespaces(nsLocallyDeclared); anc.LoadRenderedNamespaces(sortedList); XmlNodeList childNodes = ChildNodes; foreach (XmlNode item2 in childNodes) { CanonicalizationDispatcher.Write(item2, strBuilder, docPos, anc); } anc.ExitElementContext(); if (IsInNodeSet) { strBuilder.Append("</" + Name + ">"); } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { Hashtable nsLocallyDeclared = new Hashtable(); SortedList sortedList = new SortedList(new NamespaceSortOrder()); SortedList sortedList2 = new SortedList(new AttributeSortOrder()); XmlAttributeCollection attributes = Attributes; if (attributes != null) { foreach (XmlAttribute item in attributes) { if (((CanonicalXmlAttribute)item).IsInNodeSet || Utils.IsNamespaceNode(item) || Utils.IsXmlNamespaceNode(item)) { if (Utils.IsNamespaceNode(item)) { anc.TrackNamespaceNode(item, sortedList, nsLocallyDeclared); } else if (Utils.IsXmlNamespaceNode(item)) { anc.TrackXmlNamespaceNode(item, sortedList, sortedList2, nsLocallyDeclared); } else if (IsInNodeSet) { sortedList2.Add(item, null); } } } } if (!Utils.IsCommittedNamespace(this, Prefix, NamespaceURI)) { string name = ((Prefix.Length > 0) ? ("xmlns:" + Prefix) : "xmlns"); XmlAttribute xmlAttribute2 = OwnerDocument.CreateAttribute(name); xmlAttribute2.Value = NamespaceURI; anc.TrackNamespaceNode(xmlAttribute2, sortedList, nsLocallyDeclared); } if (IsInNodeSet) { anc.GetNamespacesToRender(this, sortedList2, sortedList, nsLocallyDeclared); byte[] bytes = Encoding.UTF8.GetBytes("<" + Name); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); foreach (object key in sortedList.GetKeyList()) { (key as CanonicalXmlAttribute).WriteHash(hash, docPos, anc); } foreach (object key2 in sortedList2.GetKeyList()) { (key2 as CanonicalXmlAttribute).WriteHash(hash, docPos, anc); } bytes = ">"u8.ToArray(); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } anc.EnterElementContext(); anc.LoadUnrenderedNamespaces(nsLocallyDeclared); anc.LoadRenderedNamespaces(sortedList); XmlNodeList childNodes = ChildNodes; foreach (XmlNode item2 in childNodes) { CanonicalizationDispatcher.WriteHash(item2, hash, docPos, anc); } anc.ExitElementContext(); if (IsInNodeSet) { byte[] bytes = Encoding.UTF8.GetBytes("</" + Name + ">"); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } } internal sealed class CanonicalXmlEntityReference : XmlEntityReference, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlEntityReference(string name, XmlDocument doc, bool defaultNodeSetInclusionState) : base(name, doc) { _isInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { CanonicalizationDispatcher.WriteGenericNode(this, strBuilder, docPos, anc); } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { CanonicalizationDispatcher.WriteHashGenericNode(this, hash, docPos, anc); } } } internal sealed class CanonicalXmlNodeList : XmlNodeList, IList, ICollection, IEnumerable { private readonly ArrayList _nodeArray; public override int Count => _nodeArray.Count; public bool IsFixedSize => _nodeArray.IsFixedSize; public bool IsReadOnly => _nodeArray.IsReadOnly; object IList.this[int index] { get { return _nodeArray[index]; } set { if (!(value is XmlNode)) { throw new ArgumentException(System.SR.Cryptography_Xml_IncorrectObjectType, "value"); } _nodeArray[index] = value; } } public object SyncRoot => _nodeArray.SyncRoot; public bool IsSynchronized => _nodeArray.IsSynchronized; internal CanonicalXmlNodeList() { _nodeArray = new ArrayList(); } public override XmlNode Item(int index) { return (XmlNode)_nodeArray[index]; } public override IEnumerator GetEnumerator() { return _nodeArray.GetEnumerator(); } public int Add(object value) { if (!(value is XmlNode)) { throw new ArgumentException(System.SR.Cryptography_Xml_IncorrectObjectType, "node"); } return _nodeArray.Add(value); } public void Clear() { _nodeArray.Clear(); } public bool Contains(object value) { return _nodeArray.Contains(value); } public int IndexOf(object value) { return _nodeArray.IndexOf(value); } public void Insert(int index, object value) { if (!(value is XmlNode)) { throw new ArgumentException(System.SR.Cryptography_Xml_IncorrectObjectType, "value"); } _nodeArray.Insert(index, value); } public void Remove(object value) { _nodeArray.Remove(value); } public void RemoveAt(int index) { _nodeArray.RemoveAt(index); } public void CopyTo(Array array, int index) { _nodeArray.CopyTo(array, index); } } internal sealed class CanonicalXmlProcessingInstruction : XmlProcessingInstruction, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlProcessingInstruction(string target, string data, XmlDocument doc, bool defaultNodeSetInclusionState) : base(target, data, doc) { _isInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { if (docPos == DocPosition.AfterRootElement) { strBuilder.Append('\n'); } strBuilder.Append("<?"); strBuilder.Append(Name); if (Value != null && Value.Length > 0) { strBuilder.Append(' ').Append(Value); } strBuilder.Append("?>"); if (docPos == DocPosition.BeforeRootElement) { strBuilder.Append('\n'); } } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { byte[] array; if (docPos == DocPosition.AfterRootElement) { array = "(char) 10"u8.ToArray(); hash.TransformBlock(array, 0, array.Length, array, 0); } array = "<?"u8.ToArray(); hash.TransformBlock(array, 0, array.Length, array, 0); array = Encoding.UTF8.GetBytes(Name); hash.TransformBlock(array, 0, array.Length, array, 0); if (Value != null && Value.Length > 0) { array = Encoding.UTF8.GetBytes(" " + Value); hash.TransformBlock(array, 0, array.Length, array, 0); } array = "?>"u8.ToArray(); hash.TransformBlock(array, 0, array.Length, array, 0); if (docPos == DocPosition.BeforeRootElement) { array = "(char) 10"u8.ToArray(); hash.TransformBlock(array, 0, array.Length, array, 0); } } } } internal sealed class CanonicalXmlSignificantWhitespace : XmlSignificantWhitespace, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlSignificantWhitespace(string strData, XmlDocument doc, bool defaultNodeSetInclusionState) : base(strData, doc) { _isInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet && docPos == DocPosition.InRootElement) { strBuilder.Append(Utils.EscapeWhitespaceData(Value)); } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet && docPos == DocPosition.InRootElement) { byte[] bytes = Encoding.UTF8.GetBytes(Utils.EscapeWhitespaceData(Value)); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } } internal sealed class CanonicalXmlText : XmlText, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlText(string strData, XmlDocument doc, bool defaultNodeSetInclusionState) : base(strData, doc) { _isInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { strBuilder.Append(Utils.EscapeTextData(Value)); } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet) { byte[] bytes = Encoding.UTF8.GetBytes(Utils.EscapeTextData(Value)); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } } internal sealed class CanonicalXmlWhitespace : XmlWhitespace, ICanonicalizableNode { private bool _isInNodeSet; public bool IsInNodeSet { get { return _isInNodeSet; } set { _isInNodeSet = value; } } public CanonicalXmlWhitespace(string strData, XmlDocument doc, bool defaultNodeSetInclusionState) : base(strData, doc) { _isInNodeSet = defaultNodeSetInclusionState; } public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet && docPos == DocPosition.InRootElement) { strBuilder.Append(Utils.EscapeWhitespaceData(Value)); } } public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { if (IsInNodeSet && docPos == DocPosition.InRootElement) { byte[] bytes = Encoding.UTF8.GetBytes(Utils.EscapeWhitespaceData(Value)); hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0); } } } internal enum CertUsageType { Verification, Decryption } public sealed class CipherData { private XmlElement _cachedXml; private CipherReference _cipherReference; private byte[] _cipherValue; [MemberNotNullWhen(true, "_cachedXml")] private bool CacheValid { [MemberNotNullWhen(true, "_cachedXml")] get { return _cachedXml != null; } } public CipherReference? CipherReference { get { return _cipherReference; } [param: DisallowNull] set { if (value == null) { throw new ArgumentNullException("value"); } if (CipherValue != null) { throw new CryptographicException(System.SR.Cryptography_Xml_CipherValueElementRequired); } _cipherReference = value; _cachedXml = null; } } public byte[]? CipherValue { get { return _cipherValue; } [param: DisallowNull] set { if (value == null) { throw new ArgumentNullException("value"); } if (CipherReference != null) { throw new CryptographicException(System.SR.Cryptography_Xml_CipherValueElementRequired); } _cipherValue = (byte[])value.Clone(); _cachedXml = null; } } public CipherData() { } public CipherData(byte[] cipherValue) { CipherValue = cipherValue; } public CipherData(CipherReference cipherReference) { CipherReference = cipherReference; } public XmlElement GetXml() { if (CacheValid) { return _cachedXml; } XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; return GetXml(xmlDocument); } internal XmlElement GetXml(XmlDocument document) { XmlElement xmlElement = document.CreateElement("CipherData", "http://www.w3.org/2001/04/xmlenc#"); if (CipherValue != null) { XmlElement xmlElement2 = document.CreateElement("CipherValue", "http://www.w3.org/2001/04/xmlenc#"); xmlElement2.AppendChild(document.CreateTextNode(Convert.ToBase64String(CipherValue))); xmlElement.AppendChild(xmlElement2); } else { if (CipherReference == null) { throw new CryptographicException(System.SR.Cryptography_Xml_CipherValueElementRequired); } xmlElement.AppendChild(CipherReference.GetXml(document)); } return xmlElement; } [RequiresDynamicCode("XmlDsigXsltTransform uses XslCompiledTransform which requires dynamic code.")] [RequiresUnreferencedCode("The algorithm implementations referenced in the XML payload might be removed. Ensure the required algorithm implementations are preserved in your application.")] public void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(value.OwnerDocument.NameTable); xmlNamespaceManager.AddNamespace("enc", "http://www.w3.org/2001/04/xmlenc#"); XmlNode xmlNode = value.SelectSingleNode("enc:CipherValue", xmlNamespaceManager); XmlNode xmlNode2 = value.SelectSingleNode("enc:CipherReference", xmlNamespaceManager); if (xmlNode != null) { if (xmlNode2 != null) { throw new CryptographicException(System.SR.Cryptography_Xml_CipherValueElementRequired); } _cipherValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(xmlNode.InnerText)); } else { if (xmlNode2 == null) { throw new CryptographicException(System.SR.Cryptography_Xml_CipherValueElementRequired); } _cipherReference = new CipherReference(); _cipherReference.LoadXml((XmlElement)xmlNode2); } _cachedXml = value; } } public sealed class CipherReference : EncryptedReference { private byte[] _cipherValue; internal byte[]? CipherValue { get { if (!base.CacheValid) { return null; } return _cipherValue; } set { _cipherValue = value; } } public CipherReference() { base.ReferenceType = "CipherReference"; } public CipherReference(string uri) : base(uri) { base.ReferenceType = "CipherReference"; } public CipherReference(string uri, TransformChain transformChain) : base(uri, transformChain) { base.ReferenceType = "CipherReference"; } public override XmlElement GetXml() { if (base.CacheValid) { return _cachedXml; } XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; return GetXml(xmlDocument); } internal new XmlElement GetXml(XmlDocument document) { if (base.ReferenceType == null) { throw new CryptographicException(System.SR.Cryptography_Xml_ReferenceTypeRequired); } XmlElement xmlElement = document.CreateElement(base.ReferenceType, "http://www.w3.org/2001/04/xmlenc#"); if (!string.IsNullOrEmpty(base.Uri)) { xmlElement.SetAttribute("URI", base.Uri); } if (base.TransformChain.Count > 0) { xmlElement.AppendChild(base.TransformChain.GetXml(document, "http://www.w3.org/2001/04/xmlenc#")); } return xmlElement; } [RequiresDynamicCode("XmlDsigXsltTransform uses XslCompiledTransform which requires dynamic code.")] [RequiresUnreferencedCode("The algorithm implementations referenced in the XML payload might be removed. Ensure the required algorithm implementations are preserved in your application.")] public override void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } base.ReferenceType = value.LocalName; string attribute = Utils.GetAttribute(value, "URI", "http://www.w3.org/2001/04/xmlenc#"); base.Uri = attribute ?? throw new CryptographicException(System.SR.Cryptography_Xml_UriRequired); XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(value.OwnerDocument.NameTable); xmlNamespaceManager.AddNamespace("enc", "http://www.w3.org/2001/04/xmlenc#"); XmlNode xmlNode = value.SelectSingleNode("enc:Transforms", xmlNamespaceManager); if (xmlNode != null) { base.TransformChain.LoadXml(xmlNode as XmlElement); } _cachedXml = value; } } [Serializable] [TypeForwardedFrom("System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public class CryptoSignedXmlRecursionException : XmlException { public CryptoSignedXmlRecursionException() { } public CryptoSignedXmlRecursionException(string message) : base(message) { } public CryptoSignedXmlRecursionException(string message, Exception inner) : base(message, inner) { } protected CryptoSignedXmlRecursionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class DataObject { private string _id; private string _mimeType; private string _encoding; private CanonicalXmlNodeList _elData; private XmlElement _cachedXml; public string? Id { get { return _id; } set { _id = value; _cachedXml = null; } } public string? MimeType { get { return _mimeType; } set { _mimeType = value; _cachedXml = null; } } public string? Encoding { get { return _encoding; } set { _encoding = value; _cachedXml = null; } } public XmlNodeList Data { get { return _elData; } set { if (value == null) { throw new ArgumentNullException("value"); } _elData = new CanonicalXmlNodeList(); foreach (XmlNode item in value) { _elData.Add(item); } _cachedXml = null; } } [MemberNotNullWhen(true, "_cachedXml")] private bool CacheValid { [MemberNotNullWhen(true, "_cachedXml")] get { return _cachedXml != null; } } public DataObject() { _cachedXml = null; _elData = new CanonicalXmlNodeList(); } public DataObject(string id, string mimeType, string encoding, XmlElement data) { if (data == null) { throw new ArgumentNullException("data"); } _id = id; _mimeType = mimeType; _encoding = encoding; _elData = new CanonicalXmlNodeList(); _elData.Add(data); _cachedXml = null; } public XmlElement GetXml() { if (CacheValid) { return _cachedXml; } XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; return GetXml(xmlDocument); } internal XmlElement GetXml(XmlDocument document) { XmlElement xmlElement = document.CreateElement("Object", "http://www.w3.org/2000/09/xmldsig#"); if (!string.IsNullOrEmpty(_id)) { xmlElement.SetAttribute("Id", _id); } if (!string.IsNullOrEmpty(_mimeType)) { xmlElement.SetAttribute("MimeType", _mimeType); } if (!string.IsNullOrEmpty(_encoding)) { xmlElement.SetAttribute("Encoding", _encoding); } if (_elData != null) { foreach (XmlNode elDatum in _elData) { xmlElement.AppendChild(document.ImportNode(elDatum, deep: true)); } } return xmlElement; } public void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } _id = Utils.GetAttribute(value, "Id", "http://www.w3.org/2000/09/xmldsig#"); _mimeType = Utils.GetAttribute(value, "MimeType", "http://www.w3.org/2000/09/xmldsig#"); _encoding = Utils.GetAttribute(value, "Encoding", "http://www.w3.org/2000/09/xmldsig#"); foreach (XmlNode childNode in value.ChildNodes) { _elData.Add(childNode); } _cachedXml = value; } } public sealed class DataReference : EncryptedReference { public DataReference() { base.ReferenceType = "DataReference"; } public DataReference(string uri) : base(uri) { base.ReferenceType = "DataReference"; } public DataReference(string uri, TransformChain transformChain) : base(uri, transformChain) { base.ReferenceType = "DataReference"; } } internal enum DocPosition { BeforeRootElement, InRootElement, AfterRootElement } public class DSAKeyValue : KeyInfoClause { private DSA _key; private const string KeyValueElementName = "KeyValue"; private const string DSAKeyValueElementName = "DSAKeyValue"; private const string PElementName = "P"; private const string QElementName = "Q"; private const string GElementName = "G"; private const string JElementName = "J"; private const string YElementName = "Y"; private const string SeedElementName = "Seed"; private const string PgenCounterElementName = "PgenCounter"; public DSA Key { get { return _key; } set { if (value == null) { throw new ArgumentNullException("value"); } _key = value; } } [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] public DSAKeyValue() { _key = DSA.Create(); } public DSAKeyValue(DSA key) { if (key == null) { throw new ArgumentNullException("key"); } _key = key; } public override XmlElement GetXml() { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; return GetXml(xmlDocument); } internal override XmlElement GetXml(XmlDocument xmlDocument) { DSAParameters dSAParameters = _key.ExportParameters(includePrivateParameters: false); XmlElement xmlElement = xmlDocument.CreateElement("KeyValue", "http://www.w3.org/2000/09/xmldsig#"); XmlElement xmlElement2 = xmlDocument.CreateElement("DSAKeyValue", "http://www.w3.org/2000/09/xmldsig#"); XmlElement xmlElement3 = xmlDocument.CreateElement("P", "http://www.w3.org/2000/09/xmldsig#"); xmlElement3.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.P))); xmlElement2.AppendChild(xmlElement3); XmlElement xmlElement4 = xmlDocument.CreateElement("Q", "http://www.w3.org/2000/09/xmldsig#"); xmlElement4.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.Q))); xmlElement2.AppendChild(xmlElement4); XmlElement xmlElement5 = xmlDocument.CreateElement("G", "http://www.w3.org/2000/09/xmldsig#"); xmlElement5.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.G))); xmlElement2.AppendChild(xmlElement5); XmlElement xmlElement6 = xmlDocument.CreateElement("Y", "http://www.w3.org/2000/09/xmldsig#"); xmlElement6.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.Y))); xmlElement2.AppendChild(xmlElement6); if (dSAParameters.J != null) { XmlElement xmlElement7 = xmlDocument.CreateElement("J", "http://www.w3.org/2000/09/xmldsig#"); xmlElement7.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.J))); xmlElement2.AppendChild(xmlElement7); } if (dSAParameters.Seed != null) { XmlElement xmlElement8 = xmlDocument.CreateElement("Seed", "http://www.w3.org/2000/09/xmldsig#"); xmlElement8.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.Seed))); xmlElement2.AppendChild(xmlElement8); XmlElement xmlElement9 = xmlDocument.CreateElement("PgenCounter", "http://www.w3.org/2000/09/xmldsig#"); xmlElement9.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(Utils.ConvertIntToByteArray(dSAParameters.Counter)))); xmlElement2.AppendChild(xmlElement9); } xmlElement.AppendChild(xmlElement2); return xmlElement; } public override void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } if (value.Name != "KeyValue" || value.NamespaceURI != "http://www.w3.org/2000/09/xmldsig#") { throw new CryptographicException(System.SR.Format(System.SR.WrongRootElement, "KeyValue", "http://www.w3.org/2000/09/xmldsig#")); } XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(value.OwnerDocument.NameTable); xmlNamespaceManager.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#"); XmlNode xmlNode = value.SelectSingleNode("dsig:DSAKeyValue", xmlNamespaceManager); if (xmlNode == null) { throw new CryptographicException(System.SR.Format(System.SR.MustContainChildElement, "KeyValue", "DSAKeyValue")); } XmlNode xmlNode2 = xmlNode.SelectSingleNode("dsig:Y", xmlNamespaceManager); if (xmlNode2 == null) { throw new CryptographicException(System.SR.Format(System.SR.ElementMissing, "Y")); } XmlNode xmlNode3 = xmlNode.SelectSingleNode("dsig:P", xmlNamespaceManager); XmlNode xmlNode4 = xmlNode.SelectSingleNode("dsig:Q", xmlNamespaceManager); if ((xmlNode3 == null && xmlNode4 != null) || (xmlNode3 != null && xmlNode4 == null)) { throw new CryptographicException(System.SR.Format(System.SR.ElementCombinationMissing, "P", "Q")); } XmlNode xmlNode5 = xmlNode.SelectSingleNode("dsig:G", xmlNamespaceManager); XmlNode xmlNode6 = xmlNode.SelectSingleNode("dsig:J", xmlNamespaceManager); XmlNode xmlNode7 = xmlNode.SelectSingleNode("dsig:Seed", xmlNamespaceManager); XmlNode xmlNode8 = xmlNode.SelectSingleNode("dsig:PgenCounter", xmlNamespaceManager); if ((xmlNode7 == null && xmlNode8 != null) || (xmlNode7 != null && xmlNode8 == null)) { throw new CryptographicException(System.SR.Format(System.SR.ElementCombinationMissing, "Seed", "PgenCounter")); } try { Key.ImportParameters(new DSAParameters { P = ((xmlNode3 != null) ? Convert.FromBase64String(xmlNode3.InnerText) : null), Q = ((xmlNode4 != null) ? Convert.FromBase64String(xmlNode4.InnerText) : null), G = ((xmlNode5 != null) ? Convert.FromBase64String(xmlNode5.InnerText) : null), Y = Convert.FromBase64String(xmlNode2.InnerText), J = ((xmlNode6 != null) ? Convert.FromBase64String(xmlNode6.InnerText) : null), Seed = ((xmlNode7 != null) ? Convert.FromBase64String(xmlNode7.InnerText) : null), Counter = ((xmlNode8 != null) ? Utils.ConvertByteArrayToInt(Convert.FromBase64String(xmlNode8.InnerText)) : 0) }); } catch (Exception inner) { throw new CryptographicException("An error occurred parsing the key components", inner); } } } internal sealed class DSASignatureDescription : SignatureDescription { private const string HashAlgorithm = "SHA1"; public DSASignatureDescription() { base.KeyAlgorithm = typeof(DSA).AssemblyQualifiedName; base.FormatterAlgorithm = typeof(DSASignatureFormatter).AssemblyQualifiedName; base.DeformatterAlgorithm = typeof(DSASignatureDeformatter).AssemblyQualifiedName; base.DigestAlgorithm = "SHA1"; } public sealed override AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key) { AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = (AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(base.DeformatterAlgorithm); asymmetricSignatureDeformatter.SetKey(key); asymmetricSignatureDeformatter.SetHashAlgorithm("SHA1"); return asymmetricSignatureDeformatter; } public sealed override AsymmetricSignatureFormatter CreateFormatter(AsymmetricAlgorithm key) { AsymmetricSignatureFormatter asymmetricSignatureFormatter = (AsymmetricSignatureFormatter)CryptoConfig.CreateFromName(base.FormatterAlgorithm); asymmetricSignatureFormatter.SetKey(key); asymmetricSignatureFormatter.SetHashAlgorithm("SHA1"); return asymmetricSignatureFormatter; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2046:AnnotationsMustMatchBase", Justification = "This derived implementation doesn't require unreferenced code, like the base does.")] public sealed override HashAlgorithm CreateDigest() { return SHA1.Create(); } } public sealed class EncryptedData : EncryptedType { [RequiresDynamicCode("XmlDsigXsltTransform uses XslCompiledTransform which requires dynamic code.")] [RequiresUnreferencedCode("The algorithm implementations referenced in the XML payload might be removed. Ensure the required algorithm implementations are preserved in your application.")] public override void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(value.OwnerDocument.NameTable); xmlNamespaceManager.AddNamespace("enc", "http://www.w3.org/2001/04/xmlenc#"); xmlNamespaceManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#"); Id = Utils.GetAttribute(value, "Id", "http://www.w3.org/2001/04/xmlenc#"); Type = Utils.GetAttribute(value, "Type", "http://www.w3.org/2001/04/xmlenc#"); MimeType = Utils.GetAttribute(value, "MimeType", "http://www.w3.org/2001/04/xmlenc#"); Encoding = Utils.GetAttribute(value, "Encoding", "http://www.w3.org/2001/04/xmlenc#"); XmlNode xmlNode = value.SelectSingleNode("enc:EncryptionMethod", xmlNamespaceManager); EncryptionMethod = new EncryptionMethod(); if (xmlNode != null) { EncryptionMethod.LoadXml(xmlNode as XmlElement); } base.KeyInfo = new KeyInfo(); XmlNode xmlNode2 = value.SelectSingleNode("ds:KeyInfo", xmlNamespaceManager); if (xmlNode2 != null) { base.KeyInfo.LoadXml(xmlNode2 as XmlElement); } XmlNode xmlNode3 = value.SelectSingleNode("enc:CipherData", xmlNamespaceManager); if (xmlNode3 == null) { throw new CryptographicException(System.SR.Cryptography_Xml_MissingCipherData); } CipherData = new CipherData(); CipherData.LoadXml(xmlNode3 as XmlElement); XmlNode xmlNode4 = value.SelectSingleNode("enc:EncryptionProperties", xmlNamespaceManager); if (xmlNode4 != null) { XmlNodeList xmlNodeList = xmlNode4.SelectNodes("enc:EncryptionProperty", xmlNamespaceManager); if (xmlNodeList != null) { foreach (XmlNode item in xmlNodeList) { EncryptionProperty encryptionProperty = new EncryptionProperty(); encryptionProperty.LoadXml(item as XmlElement); EncryptionProperties.Add(encryptionProperty); } } } _cachedXml = value; } public override XmlElement GetXml() { if (base.CacheValid) { return _cachedXml; } XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; return GetXml(xmlDocument); } internal XmlElement GetXml(XmlDocument document) { XmlElement xmlElement = document.CreateElement("EncryptedData", "http://www.w3.org/2001/04/xmlenc#"); if (!string.IsNullOrEmpty(Id)) { xmlElement.SetAttribute("Id", Id); } if (!string.IsNullOrEmpty(Type)) { xmlElement.SetAttribute("Type", Type); } if (!string.IsNullOrEmpty(MimeType)) { xmlElement.SetAttribute("MimeType", MimeType); } if (!string.IsNullOrEmpty(Encoding)) { xmlElement.SetAttribute("Encoding", Encoding); } if (EncryptionMethod != null) { xmlElement.AppendChild(EncryptionMethod.GetXml(document)); } if (base.KeyInfo.Count > 0) { xmlElement.AppendChild(base.KeyInfo.GetXml(document)); } if (CipherData == null) { throw new CryptographicException(System.SR.Cryptography_Xml_MissingCipherData); } xmlElement.AppendChild(CipherData.GetXml(document)); if (EncryptionProperties.Count > 0) { XmlElement xmlElement2 = document.CreateElement("EncryptionProperties", "http://www.w3.org/2001/04/xmlenc#"); for (int i = 0; i < EncryptionProperties.Count; i++) { EncryptionProperty encryptionProperty = EncryptionProperties.Item(i); xmlElement2.AppendChild(encryptionProperty.GetXml(document)); } xmlElement.AppendChild(xmlElement2); } return xmlElement; } } public sealed class EncryptedKey : EncryptedType { private string _recipient; private string _carriedKeyName; private ReferenceList _referenceList; public string Recipient { get { return _recipient ?? (_recipient = string.Empty); } [param: AllowNull] set { _recipient = value; _cachedXml = null; } } public string? CarriedKeyName { get { return _carriedKeyName; } set { _carriedKeyName = value; _cachedXml = null; } } public ReferenceList ReferenceList => _referenceList ?? (_referenceList = new ReferenceList()); public void AddReference(DataReference dataReference) { ReferenceList.Add(dataReference); } public void AddReference(KeyReference keyReference) { ReferenceList.Add(keyReference); } [RequiresDynamicCode("XmlDsigXsltTransform uses XslCompiledTransform which requires dynamic code.")] [RequiresUnreferencedCode("The algorithm implementations referenced in the XML payload might be removed. Ensure the required algorithm implementations are preserved in your application.")] public override void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(value.OwnerDocument.NameTable); xmlNamespaceManager.AddNamespace("enc", "http://www.w3.org/2001/04/xmlenc#"); xmlNamespaceManager.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#"); Id = Utils.GetAttribute(value, "Id", "http://www.w3.org/2001/04/xmlenc#"); Type = Utils.GetAttribute(value, "Type", "http://www.w3.org/2001/04/xmlenc#"); MimeType = Utils.GetAttribute(value, "MimeType", "http://www.w3.org/2001/04/xmlenc#"); Encoding = Utils.GetAttribute(value, "Encoding", "http://www.w3.org/2001/04/xmlenc#"); Recipient = Utils.GetAttribute(value, "Recipient", "http://www.w3.org/2001/04/xmlenc#"); XmlNode xmlNode = value.SelectSingleNode("enc:EncryptionMethod", xmlNamespaceManager); EncryptionMethod = new EncryptionMethod(); if (xmlNode != null) { EncryptionMethod.LoadXml(xmlNode as XmlElement); } base.KeyInfo = new KeyInfo(); XmlNode xmlNode2 = value.SelectSingleNode("ds:KeyInfo", xmlNamespaceManager); if (xmlNode2 != null) { base.KeyInfo.LoadXml(xmlNode2 as XmlElement); } XmlNode xmlNode3 = value.SelectSingleNode("enc:CipherData", xmlNamespaceManager); if (xmlNode3 == null) { throw new CryptographicException(System.SR.Cryptography_Xml_MissingCipherData); } CipherData = new CipherData(); CipherData.LoadXml(xmlNode3 as XmlElement); XmlNode xmlNode4 = value.SelectSingleNode("enc:EncryptionProperties", xmlNamespaceManager); if (xmlNode4 != null) { XmlNodeList xmlNodeList = xmlNode4.SelectNodes("enc:EncryptionProperty", xmlNamespaceManager); if (xmlNodeList != null) { foreach (XmlNode item in xmlNodeList) { EncryptionProperty encryptionProperty = ne