Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of System Security Cryptography Pkcs v8.0.0
BepInEx/core/System.Security.Cryptography.Pkcs/netstandard2.1/System.Security.Cryptography.Pkcs.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Formats.Asn1; using System.IO; using System.Linq; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.Asn1; using System.Security.Cryptography.Asn1.Pkcs12; using System.Security.Cryptography.Asn1.Pkcs7; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.Pkcs.Asn1; using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.Xml; using System.Security.Permissions; using System.Text; using System.Threading; using FxResources.System.Security.Cryptography.Pkcs; using Internal.Cryptography; using Internal.Cryptography.Pal.AnyOS; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("System.Security.Cryptography.Pkcs")] [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 support for PKCS and CMS algorithms.\r\n\r\nCommonly Used Types:\r\nSystem.Security.Cryptography.Pkcs.EnvelopedCms")] [assembly: AssemblyFileVersion("8.0.23.53103")] [assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Security.Cryptography.Pkcs")] [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.Pkcs { internal static class SR { } } namespace Internal.Cryptography { internal abstract class DecryptorPal : IDisposable { public RecipientInfoCollection RecipientInfos { get; } internal DecryptorPal(RecipientInfoCollection recipientInfos) { RecipientInfos = recipientInfos; } public abstract ContentInfo TryDecrypt(RecipientInfo recipientInfo, X509Certificate2 cert, AsymmetricAlgorithm privateKey, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore, out Exception exception); public abstract void Dispose(); } internal abstract class KeyAgreeRecipientInfoPal : RecipientInfoPal { public abstract DateTime Date { get; } public abstract SubjectIdentifierOrKey OriginatorIdentifierOrKey { get; } public abstract CryptographicAttributeObject OtherKeyAttribute { get; } internal KeyAgreeRecipientInfoPal() { } } internal static class KeyLengths { public const int Rc2_40Bit = 40; public const int Rc2_56Bit = 56; public const int Rc2_64Bit = 64; public const int Rc2_128Bit = 128; public const int Rc4Max_128Bit = 128; public const int Des_64Bit = 64; public const int TripleDes_192Bit = 192; public const int DefaultKeyLengthForRc2AndRc4 = 128; } internal abstract class KeyTransRecipientInfoPal : RecipientInfoPal { internal KeyTransRecipientInfoPal() { } } internal static class PkcsHelpers { private static readonly bool s_oidIsInitOnceOnly = DetectInitOnlyOid(); private static bool DetectInitOnlyOid() { Oid oid = new Oid("2.16.840.1.101.3.4.2.1", null); try { oid.Value = "2.16.840.1.101.3.4.2.2"; return false; } catch (PlatformNotSupportedException) { return true; } } internal static HashAlgorithmName GetDigestAlgorithm(Oid oid) { return GetDigestAlgorithm(oid.Value); } internal static HashAlgorithmName GetDigestAlgorithm(string oidValue, bool forVerification = false) { switch (oidValue) { case "1.2.840.113549.1.1.4": if (!forVerification) { break; } goto case "1.2.840.113549.2.5"; case "1.2.840.113549.2.5": return HashAlgorithmName.MD5; case "1.2.840.113549.1.1.5": if (!forVerification) { break; } goto case "1.3.14.3.2.26"; case "1.3.14.3.2.26": return HashAlgorithmName.SHA1; case "1.2.840.113549.1.1.11": if (!forVerification) { break; } goto case "2.16.840.1.101.3.4.2.1"; case "2.16.840.1.101.3.4.2.1": return HashAlgorithmName.SHA256; case "1.2.840.113549.1.1.12": if (!forVerification) { break; } goto case "2.16.840.1.101.3.4.2.2"; case "2.16.840.1.101.3.4.2.2": return HashAlgorithmName.SHA384; case "1.2.840.113549.1.1.13": if (!forVerification) { break; } goto case "2.16.840.1.101.3.4.2.3"; case "2.16.840.1.101.3.4.2.3": return HashAlgorithmName.SHA512; } throw new CryptographicException(System.SR.Cryptography_UnknownHashAlgorithm, oidValue); } internal static string GetOidFromHashAlgorithm(HashAlgorithmName algName) { if (algName == HashAlgorithmName.MD5) { return "1.2.840.113549.2.5"; } if (algName == HashAlgorithmName.SHA1) { return "1.3.14.3.2.26"; } if (algName == HashAlgorithmName.SHA256) { return "2.16.840.1.101.3.4.2.1"; } if (algName == HashAlgorithmName.SHA384) { return "2.16.840.1.101.3.4.2.2"; } if (algName == HashAlgorithmName.SHA512) { return "2.16.840.1.101.3.4.2.3"; } throw new CryptographicException(System.SR.Cryptography_Cms_UnknownAlgorithm, algName.Name); } public static byte[] Resize(this byte[] a, int size) { Array.Resize(ref a, size); return a; } public static void RemoveAt<T>(ref T[] arr, int idx) { if (arr.Length == 1) { arr = Array.Empty<T>(); return; } T[] array = new T[arr.Length - 1]; if (idx != 0) { Array.Copy(arr, array, idx); } if (idx < array.Length) { Array.Copy(arr, idx + 1, array, idx, array.Length - idx); } arr = array; } public static System.Security.Cryptography.Asn1.AttributeAsn[] NormalizeAttributeSet(System.Security.Cryptography.Asn1.AttributeAsn[] setItems, Action<byte[]> encodedValueProcessor = null) { AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.DER); asnWriter.PushSetOf(); foreach (System.Security.Cryptography.Asn1.AttributeAsn attributeAsn in setItems) { attributeAsn.Encode(asnWriter); } asnWriter.PopSetOf(); byte[] array = asnWriter.Encode(); encodedValueProcessor?.Invoke(array); try { System.Formats.Asn1.AsnValueReader reader = new System.Formats.Asn1.AsnValueReader(array, AsnEncodingRules.DER).ReadSetOf(); System.Security.Cryptography.Asn1.AttributeAsn[] array2 = new System.Security.Cryptography.Asn1.AttributeAsn[setItems.Length]; int num = 0; while (reader.HasData) { System.Security.Cryptography.Asn1.AttributeAsn.Decode(ref reader, array, out var decoded); array2[num] = decoded; num++; } return array2; } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } internal static byte[] EncodeContentInfo(ReadOnlyMemory<byte> content, string contentType, AsnEncodingRules ruleSet = AsnEncodingRules.DER) { System.Security.Cryptography.Asn1.Pkcs7.ContentInfoAsn contentInfoAsn = default(System.Security.Cryptography.Asn1.Pkcs7.ContentInfoAsn); contentInfoAsn.ContentType = contentType; contentInfoAsn.Content = content; System.Security.Cryptography.Asn1.Pkcs7.ContentInfoAsn contentInfoAsn2 = contentInfoAsn; AsnWriter asnWriter = new AsnWriter(ruleSet); contentInfoAsn2.Encode(asnWriter); return asnWriter.Encode(); } public static CmsRecipientCollection DeepCopy(this CmsRecipientCollection recipients) { CmsRecipientCollection cmsRecipientCollection = new CmsRecipientCollection(); CmsRecipientEnumerator enumerator = recipients.GetEnumerator(); while (enumerator.MoveNext()) { CmsRecipient current = enumerator.Current; X509Certificate2 certificate = current.Certificate; X509Certificate2 certificate2 = new X509Certificate2(certificate.Handle); CmsRecipient recipient = (((object)current.RSAEncryptionPadding != null) ? new CmsRecipient(current.RecipientIdentifierType, certificate2, current.RSAEncryptionPadding) : new CmsRecipient(current.RecipientIdentifierType, certificate2)); cmsRecipientCollection.Add(recipient); GC.KeepAlive(certificate); } return cmsRecipientCollection; } public static byte[] UnicodeToOctetString(this string s) { byte[] array = new byte[2 * (s.Length + 1)]; Encoding.Unicode.GetBytes(s, 0, s.Length, array, 0); return array; } public static string OctetStringToUnicode(this byte[] octets) { if (octets.Length < 2) { return string.Empty; } int num = octets.Length; int num2 = num - 1; for (int i = 0; i < num2; i += 2) { if (octets[i] == 0 && octets[i + 1] == 0) { num = i; break; } } return Encoding.Unicode.GetString(octets, 0, num); } public static X509Certificate2Collection GetStoreCertificates(StoreName storeName, StoreLocation storeLocation, bool openExistingOnly) { using X509Store x509Store = new X509Store(storeName, storeLocation); OpenFlags openFlags = OpenFlags.IncludeArchived; if (openExistingOnly) { openFlags |= OpenFlags.OpenExistingOnly; } x509Store.Open(openFlags); return x509Store.Certificates; } public static X509Certificate2 TryFindMatchingCertificate(this X509Certificate2Collection certs, SubjectIdentifier recipientIdentifier) { switch (recipientIdentifier.Type) { case SubjectIdentifierType.IssuerAndSerialNumber: { X509IssuerSerial x509IssuerSerial = (X509IssuerSerial)recipientIdentifier.Value; byte[] ba2 = x509IssuerSerial.SerialNumber.ToSerialBytes(); string issuerName = x509IssuerSerial.IssuerName; X509Certificate2Enumerator enumerator2 = certs.GetEnumerator(); while (enumerator2.MoveNext()) { X509Certificate2 current2 = enumerator2.Current; byte[] serialNumber = current2.GetSerialNumber(); if (AreByteArraysEqual(serialNumber, ba2) && current2.Issuer == issuerName) { return current2; } } break; } case SubjectIdentifierType.SubjectKeyIdentifier: { string skiString = (string)recipientIdentifier.Value; byte[] ba = skiString.ToSkiBytes(); X509Certificate2Enumerator enumerator = certs.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate2 current = enumerator.Current; byte[] subjectKeyIdentifier = PkcsPal.Instance.GetSubjectKeyIdentifier(current); if (AreByteArraysEqual(ba, subjectKeyIdentifier)) { return current; } } break; } default: throw new CryptographicException(); } return null; } internal static bool AreByteArraysEqual(byte[] ba1, byte[] ba2) { return ba1.AsSpan().SequenceEqual(ba2.AsSpan()); } internal static byte[] ToSkiBytes(this string skiString) { return skiString.UpperHexStringToByteArray(); } public static string ToSkiString(this byte[] skiBytes) { return ToUpperHexString(skiBytes); } public static string ToBigEndianHex(this ReadOnlySpan<byte> bytes) { return ToUpperHexString(bytes); } internal static byte[] ToSerialBytes(this string serialString) { byte[] array = serialString.UpperHexStringToByteArray(); Array.Reverse(array); return array; } public static string ToSerialString(this byte[] serialBytes) { serialBytes = serialBytes.CloneByteArray(); Array.Reverse(serialBytes); return ToUpperHexString(serialBytes); } private static string ToUpperHexString(ReadOnlySpan<byte> ba) { return System.HexConverter.ToString(ba); } private static byte[] UpperHexStringToByteArray(this string normalizedString) { byte[] array = new byte[normalizedString.Length / 2]; for (int i = 0; i < array.Length; i++) { char c = normalizedString[i * 2]; byte b = (byte)(UpperHexCharToNybble(c) << 4); c = normalizedString[i * 2 + 1]; b |= UpperHexCharToNybble(c); array[i] = b; } return array; } private static byte UpperHexCharToNybble(char c) { if (c >= '0' && c <= '9') { return (byte)(c - 48); } if (c >= 'A' && c <= 'F') { return (byte)(c - 65 + 10); } throw new CryptographicException(); } public static Pkcs9AttributeObject CreateBestPkcs9AttributeObjectAvailable(Oid oid, ReadOnlySpan<byte> encodedAttribute) { return oid.Value switch { "1.3.6.1.4.1.311.88.2.1" => new Pkcs9DocumentName(encodedAttribute), "1.3.6.1.4.1.311.88.2.2" => new Pkcs9DocumentDescription(encodedAttribute), "1.2.840.113549.1.9.5" => new Pkcs9SigningTime(encodedAttribute), "1.2.840.113549.1.9.3" => new Pkcs9ContentType(encodedAttribute), "1.2.840.113549.1.9.4" => new Pkcs9MessageDigest(encodedAttribute), "1.2.840.113549.1.9.21" => new Pkcs9LocalKeyId { RawData = encodedAttribute.ToArray() }, _ => new Pkcs9AttributeObject(oid, encodedAttribute), }; } internal static byte[] OneShot(this ICryptoTransform transform, byte[] data) { return transform.OneShot(data, 0, data.Length); } internal static byte[] OneShot(this ICryptoTransform transform, byte[] data, int offset, int length) { if (transform.CanTransformMultipleBlocks) { return transform.TransformFinalBlock(data, offset, length); } using MemoryStream memoryStream = new MemoryStream(length); using (CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write)) { cryptoStream.Write(data, offset, length); } return memoryStream.ToArray(); } public static void EnsureSingleBerValue(ReadOnlySpan<byte> source) { if (!AsnDecoder.TryReadEncodedValue(source, AsnEncodingRules.BER, out var _, out var _, out var _, out var bytesConsumed) || bytesConsumed != source.Length) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } } public static int FirstBerValueLength(ReadOnlySpan<byte> source) { if (!AsnDecoder.TryReadEncodedValue(source, AsnEncodingRules.BER, out var _, out var _, out var _, out var bytesConsumed)) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } return bytesConsumed; } public static ReadOnlyMemory<byte> DecodeOctetStringAsMemory(ReadOnlyMemory<byte> encodedOctetString) { try { ReadOnlySpan<byte> span = encodedOctetString.Span; if (AsnDecoder.TryReadPrimitiveOctetString(span, AsnEncodingRules.BER, out var value, out var bytesConsumed)) { if (bytesConsumed != span.Length) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } if (span.Overlaps(value, out var elementOffset)) { return encodedOctetString.Slice(elementOffset, value.Length); } } byte[] array = AsnDecoder.ReadOctetString(span, AsnEncodingRules.BER, out bytesConsumed); if (bytesConsumed != span.Length) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } return array; } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } public static byte[] DecodeOctetString(ReadOnlyMemory<byte> encodedOctets) { try { int bytesConsumed; byte[] result = AsnDecoder.ReadOctetString(encodedOctets.Span, AsnEncodingRules.BER, out bytesConsumed); if (bytesConsumed != encodedOctets.Length) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } return result; } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } public static byte[] EncodeOctetString(byte[] octets) { AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.DER); asnWriter.WriteOctetString(octets); return asnWriter.Encode(); } public static byte[] EncodeUtcTime(DateTime utcTime) { AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.DER); try { if (utcTime.Kind == DateTimeKind.Unspecified) { asnWriter.WriteUtcTime(utcTime.ToLocalTime(), 2049); } else { asnWriter.WriteUtcTime(utcTime, 2049); } return asnWriter.Encode(); } catch (ArgumentException ex) { throw new CryptographicException(ex.Message, ex); } } public static DateTime DecodeUtcTime(byte[] encodedUtcTime) { try { int bytesConsumed; DateTimeOffset dateTimeOffset = AsnDecoder.ReadUtcTime(encodedUtcTime, AsnEncodingRules.BER, out bytesConsumed); if (bytesConsumed != encodedUtcTime.Length) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } return dateTimeOffset.UtcDateTime; } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } public static string DecodeOid(ReadOnlySpan<byte> encodedOid) { if (encodedOid.Length == 2 && encodedOid[0] == 6 && encodedOid[1] == 0) { return string.Empty; } try { int bytesConsumed; string result = AsnDecoder.ReadObjectIdentifier(encodedOid, AsnEncodingRules.BER, out bytesConsumed); if (bytesConsumed != encodedOid.Length) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } return result; } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } public static bool TryGetRsaOaepEncryptionPadding(ReadOnlyMemory<byte>? parameters, [NotNullWhen(true)] out RSAEncryptionPadding rsaEncryptionPadding, [NotNullWhen(false)] out Exception exception) { exception = null; rsaEncryptionPadding = null; if (!parameters.HasValue || parameters.Value.IsEmpty) { exception = new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); return false; } try { OaepParamsAsn oaepParamsAsn = OaepParamsAsn.Decode(parameters.Value, AsnEncodingRules.DER); if (oaepParamsAsn.MaskGenFunc.Algorithm != "1.2.840.113549.1.1.8" || !oaepParamsAsn.MaskGenFunc.Parameters.HasValue || oaepParamsAsn.PSourceFunc.Algorithm != "1.2.840.113549.1.1.9") { exception = new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); return false; } if (System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn.Decode(oaepParamsAsn.MaskGenFunc.Parameters.Value, AsnEncodingRules.DER).Algorithm != oaepParamsAsn.HashFunc.Algorithm) { exception = new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); return false; } ReadOnlySpan<byte> other = new byte[2] { 4, 0 }; if (oaepParamsAsn.PSourceFunc.Parameters.HasValue && !oaepParamsAsn.PSourceFunc.Parameters.Value.Span.SequenceEqual(other)) { exception = new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); return false; } switch (oaepParamsAsn.HashFunc.Algorithm) { case "1.3.14.3.2.26": rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA1; return true; case "2.16.840.1.101.3.4.2.1": rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA256; return true; case "2.16.840.1.101.3.4.2.2": rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA384; return true; case "2.16.840.1.101.3.4.2.3": rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA512; return true; default: exception = new CryptographicException(System.SR.Cryptography_Cms_UnknownAlgorithm, oaepParamsAsn.HashFunc.Algorithm); return false; } } catch (CryptographicException ex) { exception = ex; return false; } } [return: NotNullIfNotNull("oid")] public static Oid CopyOid(this Oid oid) { if (s_oidIsInitOnceOnly) { return oid; } if (oid != null) { return new Oid(oid); } return null; } } internal abstract class PkcsPal { private protected static readonly byte[] s_rsaOaepSha1Parameters = new byte[2] { 48, 0 }; private protected static readonly byte[] s_rsaOaepSha256Parameters = new byte[49] { 48, 47, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0 }; private protected static readonly byte[] s_rsaOaepSha384Parameters = new byte[49] { 48, 47, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0 }; private protected static readonly byte[] s_rsaOaepSha512Parameters = new byte[49] { 48, 47, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0 }; private protected static readonly byte[] s_rsaPkcsParameters = new byte[2] { 5, 0 }; private static readonly PkcsPal s_instance = new ManagedPkcsPal(); public static PkcsPal Instance => s_instance; public abstract byte[] Encrypt(CmsRecipientCollection recipients, ContentInfo contentInfo, AlgorithmIdentifier contentEncryptionAlgorithm, X509Certificate2Collection originatorCerts, CryptographicAttributeObjectCollection unprotectedAttributes); public abstract DecryptorPal Decode(ReadOnlySpan<byte> encodedMessage, out int version, out ContentInfo contentInfo, out AlgorithmIdentifier contentEncryptionAlgorithm, out X509Certificate2Collection originatorCerts, out CryptographicAttributeObjectCollection unprotectedAttributes); public abstract Oid GetEncodedMessageType(ReadOnlySpan<byte> encodedMessage); public abstract void AddCertsFromStoreForDecryption(X509Certificate2Collection certs); public abstract Exception CreateRecipientsNotFoundException(); public abstract Exception CreateRecipientInfosAfterEncryptException(); public abstract Exception CreateDecryptAfterEncryptException(); public abstract Exception CreateDecryptTwiceException(); public abstract byte[] GetSubjectKeyIdentifier(X509Certificate2 certificate); public abstract T GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent) where T : AsymmetricAlgorithm; public abstract T GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent) where T : AsymmetricAlgorithm; } internal abstract class RecipientInfoPal { public abstract byte[] EncryptedKey { get; } public abstract AlgorithmIdentifier KeyEncryptionAlgorithm { get; } public abstract SubjectIdentifier RecipientIdentifier { get; } public abstract int Version { get; } internal RecipientInfoPal() { } } internal static class Helpers { [UnsupportedOSPlatformGuard("browser")] internal static bool HasSymmetricEncryption { get; } = true; public static bool IsDSASupported => true; public static bool IsRC2Supported => true; [UnsupportedOSPlatformGuard("browser")] internal static bool HasMD5 { get; } = true; [return: NotNullIfNotNull("src")] public static byte[] CloneByteArray(this byte[] src) { if (src == null) { return null; } return (byte[])src.Clone(); } internal static bool TryCopyToDestination(this ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten) { if (source.TryCopyTo(destination)) { bytesWritten = source.Length; return true; } bytesWritten = 0; return false; } internal static int HashOidToByteLength(string hashOid) { return hashOid switch { "2.16.840.1.101.3.4.2.1" => 32, "2.16.840.1.101.3.4.2.2" => 48, "2.16.840.1.101.3.4.2.3" => 64, "1.3.14.3.2.26" => 20, "1.2.840.113549.2.5" => 16, _ => throw new CryptographicException(System.SR.Format(System.SR.Cryptography_UnknownHashAlgorithm, hashOid)), }; } } } namespace Internal.Cryptography.Pal.AnyOS { internal static class AsnHelpers { internal static SubjectIdentifierOrKey ToSubjectIdentifierOrKey(this OriginatorIdentifierOrKeyAsn originator) { if (originator.IssuerAndSerialNumber.HasValue) { X500DistinguishedName x500DistinguishedName = new X500DistinguishedName(originator.IssuerAndSerialNumber.Value.Issuer.ToArray()); return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.IssuerAndSerialNumber, new X509IssuerSerial(x500DistinguishedName.Name, originator.IssuerAndSerialNumber.Value.SerialNumber.Span.ToBigEndianHex())); } if (originator.SubjectKeyIdentifier.HasValue) { return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.SubjectKeyIdentifier, originator.SubjectKeyIdentifier.Value.Span.ToBigEndianHex()); } if (originator.OriginatorKey.HasValue) { OriginatorPublicKeyAsn value = originator.OriginatorKey.Value; return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.PublicKeyInfo, new PublicKeyInfo(value.Algorithm.ToPresentationObject(), value.PublicKey.ToArray())); } return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.Unknown, string.Empty); } internal static AlgorithmIdentifier ToPresentationObject(this System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn asn) { byte[] parameters = Array.Empty<byte>(); int keyLength; switch (asn.Algorithm) { case "1.2.840.113549.3.2": { if (!asn.Parameters.HasValue) { keyLength = 0; break; } int effectiveKeyBits = System.Security.Cryptography.Asn1.Rc2CbcParameters.Decode(asn.Parameters.Value, AsnEncodingRules.BER).GetEffectiveKeyBits(); switch (effectiveKeyBits) { case 40: case 56: case 64: case 128: keyLength = effectiveKeyBits; break; default: keyLength = 0; break; } break; } case "1.2.840.113549.3.4": { if (!asn.Parameters.HasValue) { keyLength = 0; break; } int bytesWritten = 0; try { AsnReader asnReader = new AsnReader(asn.Parameters.Value, AsnEncodingRules.BER); if (asnReader.PeekTag() != Asn1Tag.Null) { if (asnReader.TryReadPrimitiveOctetString(out var contents)) { bytesWritten = contents.Length; } else { Span<byte> destination = stackalloc byte[16]; if (!asnReader.TryReadOctetString(destination, out bytesWritten)) { throw new CryptographicException(); } } } } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } keyLength = 128 - 8 * bytesWritten; break; } case "1.3.14.3.2.7": keyLength = 64; break; case "1.2.840.113549.3.7": keyLength = 192; break; case "1.2.840.113549.1.1.7": if (!asn.HasNullEquivalentParameters()) { keyLength = 0; parameters = asn.Parameters.Value.ToArray(); break; } goto default; default: keyLength = 0; break; } return new AlgorithmIdentifier(new Oid(asn.Algorithm), keyLength) { Parameters = parameters }; } } internal sealed class ManagedPkcsPal : PkcsPal { internal sealed class ManagedDecryptorPal : DecryptorPal { private readonly byte[] _dataCopy; private EnvelopedDataAsn _envelopedData; public ManagedDecryptorPal(byte[] dataCopy, EnvelopedDataAsn envelopedDataAsn, RecipientInfoCollection recipientInfos) : base(recipientInfos) { _dataCopy = dataCopy; _envelopedData = envelopedDataAsn; } public unsafe override ContentInfo TryDecrypt(RecipientInfo recipientInfo, X509Certificate2 cert, AsymmetricAlgorithm privateKey, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore, out Exception exception) { if (recipientInfo.Pal is ManagedKeyTransPal managedKeyTransPal) { RSA rSA = privateKey as RSA; if (privateKey != null && rSA == null) { exception = new CryptographicException(System.SR.Cryptography_Cms_Ktri_RSARequired); return null; } byte[] array = managedKeyTransPal.DecryptCek(cert, rSA, out exception); fixed (byte* ptr = array) { try { if (exception != null) { return null; } return TryDecryptCore(array, _envelopedData.EncryptedContentInfo.ContentType, _envelopedData.EncryptedContentInfo.EncryptedContent, _envelopedData.EncryptedContentInfo.ContentEncryptionAlgorithm, out exception); } finally { if (array != null) { Array.Clear(array, 0, array.Length); } } } } exception = new CryptographicException(System.SR.Cryptography_Cms_RecipientType_NotSupported, recipientInfo.Type.ToString()); return null; } public static ContentInfo TryDecryptCore(byte[] cek, string contentType, ReadOnlyMemory<byte>? content, System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn contentEncryptionAlgorithm, out Exception exception) { if (!content.HasValue) { exception = null; return new ContentInfo(new Oid(contentType), Array.Empty<byte>()); } byte[] array = DecryptContent(content.Value, cek, contentEncryptionAlgorithm, out exception); if (exception != null) { return null; } if (contentType != "1.2.840.113549.1.7.1") { array = GetAsnSequenceWithContentNoValidation(array); } exception = null; return new ContentInfo(new Oid(contentType), array); } private static byte[] GetAsnSequenceWithContentNoValidation(ReadOnlySpan<byte> content) { AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.BER); asnWriter.WriteOctetString(content); byte[] array = asnWriter.Encode(); array[0] = 48; return array; } private static byte[] DecryptContent(ReadOnlyMemory<byte> encryptedContent, byte[] cek, System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn contentEncryptionAlgorithm, out Exception exception) { exception = null; if (encryptedContent.IsEmpty) { return Array.Empty<byte>(); } int length = encryptedContent.Length; byte[] array = System.Security.Cryptography.CryptoPool.Rent(length); try { encryptedContent.CopyTo(array); using SymmetricAlgorithm symmetricAlgorithm = OpenAlgorithm(contentEncryptionAlgorithm); ICryptoTransform cryptoTransform; try { cryptoTransform = symmetricAlgorithm.CreateDecryptor(cek, symmetricAlgorithm.IV); } catch (ArgumentException inner) { throw new CryptographicException(System.SR.Cryptography_Cms_InvalidSymmetricKey, inner); } using (cryptoTransform) { return cryptoTransform.OneShot(array, 0, length); } } catch (CryptographicException ex) { exception = ex; return null; } finally { System.Security.Cryptography.CryptoPool.Return(array, length); } } public override void Dispose() { } } private sealed class ManagedKeyAgreePal : KeyAgreeRecipientInfoPal { private readonly KeyAgreeRecipientInfoAsn _asn; private readonly int _index; public override byte[] EncryptedKey => _asn.RecipientEncryptedKeys[_index].EncryptedKey.ToArray(); public override AlgorithmIdentifier KeyEncryptionAlgorithm => _asn.KeyEncryptionAlgorithm.ToPresentationObject(); public override SubjectIdentifier RecipientIdentifier => new SubjectIdentifier(_asn.RecipientEncryptedKeys[_index].Rid.IssuerAndSerialNumber, _asn.RecipientEncryptedKeys[_index].Rid.RKeyId?.SubjectKeyIdentifier); public override int Version => _asn.Version; public override DateTime Date { get { KeyAgreeRecipientIdentifierAsn rid = _asn.RecipientEncryptedKeys[_index].Rid; if (!rid.RKeyId.HasValue) { throw new InvalidOperationException(System.SR.Cryptography_Cms_Key_Agree_Date_Not_Available); } if (!rid.RKeyId.Value.Date.HasValue) { return DateTime.FromFileTimeUtc(0L); } return rid.RKeyId.Value.Date.Value.LocalDateTime; } } public override SubjectIdentifierOrKey OriginatorIdentifierOrKey => _asn.Originator.ToSubjectIdentifierOrKey(); public override CryptographicAttributeObject OtherKeyAttribute { get { KeyAgreeRecipientIdentifierAsn rid = _asn.RecipientEncryptedKeys[_index].Rid; if (!rid.RKeyId.HasValue) { throw new InvalidOperationException(System.SR.Cryptography_Cms_Key_Agree_Date_Not_Available); } if (!rid.RKeyId.Value.Other.HasValue) { return null; } Oid oid = new Oid(rid.RKeyId.Value.Other.Value.KeyAttrId); ReadOnlySpan<byte> encodedData = ReadOnlySpan<byte>.Empty; if (rid.RKeyId.Value.Other.Value.KeyAttr.HasValue) { encodedData = rid.RKeyId.Value.Other.Value.KeyAttr.Value.Span; } Pkcs9AttributeObject asnEncodedData = new Pkcs9AttributeObject(oid, encodedData); AsnEncodedDataCollection values = new AsnEncodedDataCollection(asnEncodedData); return new CryptographicAttributeObject(oid, values); } } internal ManagedKeyAgreePal(KeyAgreeRecipientInfoAsn asn, int index) { _asn = asn; _index = index; } } internal sealed class ManagedKeyTransPal : KeyTransRecipientInfoPal { private readonly KeyTransRecipientInfoAsn _asn; public override byte[] EncryptedKey => _asn.EncryptedKey.ToArray(); public override AlgorithmIdentifier KeyEncryptionAlgorithm => _asn.KeyEncryptionAlgorithm.ToPresentationObject(); public override SubjectIdentifier RecipientIdentifier => new SubjectIdentifier(_asn.Rid.IssuerAndSerialNumber, _asn.Rid.SubjectKeyIdentifier); public override int Version => _asn.Version; internal ManagedKeyTransPal(KeyTransRecipientInfoAsn asn) { _asn = asn; } internal byte[] DecryptCek(X509Certificate2 cert, RSA privateKey, out Exception exception) { ReadOnlyMemory<byte>? parameters = _asn.KeyEncryptionAlgorithm.Parameters; string algorithm = _asn.KeyEncryptionAlgorithm.Algorithm; if (!(algorithm == "1.2.840.113549.1.1.1")) { if (!(algorithm == "1.2.840.113549.1.1.7")) { exception = new CryptographicException(System.SR.Cryptography_Cms_UnknownAlgorithm, _asn.KeyEncryptionAlgorithm.Algorithm); return null; } } else if (parameters.HasValue && !parameters.Value.Span.SequenceEqual(PkcsPal.s_rsaPkcsParameters)) { exception = new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); return null; } return DecryptCekCore(cert, privateKey, _asn.EncryptedKey.Span, algorithm, parameters, out exception); } internal static byte[] DecryptCekCore(X509Certificate2 cert, RSA privateKey, ReadOnlySpan<byte> encryptedKey, string keyEncryptionAlgorithm, ReadOnlyMemory<byte>? algorithmParameters, out Exception exception) { RSAEncryptionPadding rsaEncryptionPadding; if (!(keyEncryptionAlgorithm == "1.2.840.113549.1.1.1")) { if (!(keyEncryptionAlgorithm == "1.2.840.113549.1.1.7")) { exception = new CryptographicException(System.SR.Cryptography_Cms_UnknownAlgorithm, keyEncryptionAlgorithm); return null; } if (!PkcsHelpers.TryGetRsaOaepEncryptionPadding(algorithmParameters, out rsaEncryptionPadding, out exception)) { return null; } } else { rsaEncryptionPadding = RSAEncryptionPadding.Pkcs1; } if (privateKey != null) { return DecryptKey(privateKey, rsaEncryptionPadding, encryptedKey, out exception); } using RSA privateKey2 = cert.GetRSAPrivateKey(); return DecryptKey(privateKey2, rsaEncryptionPadding, encryptedKey, out exception); } } public override void AddCertsFromStoreForDecryption(X509Certificate2Collection certs) { certs.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.CurrentUser, openExistingOnly: false)); try { certs.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.LocalMachine, openExistingOnly: false)); } catch (CryptographicException) { } } public override byte[] GetSubjectKeyIdentifier(X509Certificate2 certificate) { X509Extension x509Extension = certificate.Extensions["2.5.29.14"] ?? new X509SubjectKeyIdentifierExtension(certificate.PublicKey, X509SubjectKeyIdentifierHashAlgorithm.CapiSha1, critical: false); try { System.Formats.Asn1.AsnValueReader asnValueReader = new System.Formats.Asn1.AsnValueReader(x509Extension.RawData, AsnEncodingRules.DER); if (asnValueReader.TryReadPrimitiveOctetString(out var value)) { asnValueReader.ThrowIfNotEmpty(); return value.ToArray(); } throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } public override T GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent) { return GetPrivateKey<T>(certificate); } public override T GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent) { return GetPrivateKey<T>(certificate); } private static T GetPrivateKey<T>(X509Certificate2 certificate) where T : AsymmetricAlgorithm { if (typeof(T) == typeof(RSA)) { return (T)(AsymmetricAlgorithm)certificate.GetRSAPrivateKey(); } if (typeof(T) == typeof(ECDsa)) { return (T)(AsymmetricAlgorithm)certificate.GetECDsaPrivateKey(); } if (typeof(T) == typeof(DSA) && Internal.Cryptography.Helpers.IsDSASupported) { return (T)(AsymmetricAlgorithm)certificate.GetDSAPrivateKey(); } return null; } private static SymmetricAlgorithm OpenAlgorithm(System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn contentEncryptionAlgorithm) { SymmetricAlgorithm symmetricAlgorithm = OpenAlgorithm(contentEncryptionAlgorithm.Algorithm); if (symmetricAlgorithm is RC2) { if (!contentEncryptionAlgorithm.Parameters.HasValue) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } System.Security.Cryptography.Asn1.Rc2CbcParameters rc2CbcParameters = System.Security.Cryptography.Asn1.Rc2CbcParameters.Decode(contentEncryptionAlgorithm.Parameters.Value, AsnEncodingRules.BER); symmetricAlgorithm.KeySize = rc2CbcParameters.GetEffectiveKeyBits(); symmetricAlgorithm.IV = rc2CbcParameters.Iv.ToArray(); } else { if (!contentEncryptionAlgorithm.Parameters.HasValue) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } try { AsnReader asnReader = new AsnReader(contentEncryptionAlgorithm.Parameters.Value, AsnEncodingRules.BER); symmetricAlgorithm.IV = asnReader.ReadOctetString(); if (symmetricAlgorithm.IV.Length != symmetricAlgorithm.BlockSize / 8) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } return symmetricAlgorithm; } private static SymmetricAlgorithm OpenAlgorithm(AlgorithmIdentifier algorithmIdentifier) { SymmetricAlgorithm symmetricAlgorithm = OpenAlgorithm(algorithmIdentifier.Oid.Value); if (symmetricAlgorithm is RC2) { if (algorithmIdentifier.KeyLength != 0) { symmetricAlgorithm.KeySize = algorithmIdentifier.KeyLength; } else { symmetricAlgorithm.KeySize = 128; } } return symmetricAlgorithm; } private static SymmetricAlgorithm OpenAlgorithm(string algorithmIdentifier) { SymmetricAlgorithm symmetricAlgorithm; switch (algorithmIdentifier) { case "1.2.840.113549.3.2": if (!Internal.Cryptography.Helpers.IsRC2Supported) { throw new PlatformNotSupportedException(System.SR.Format(System.SR.Cryptography_AlgorithmNotSupported, "RC2")); } symmetricAlgorithm = RC2.Create(); break; case "1.3.14.3.2.7": symmetricAlgorithm = DES.Create(); break; case "1.2.840.113549.3.7": symmetricAlgorithm = TripleDES.Create(); break; case "2.16.840.1.101.3.4.1.2": symmetricAlgorithm = Aes.Create(); symmetricAlgorithm.KeySize = 128; break; case "2.16.840.1.101.3.4.1.22": symmetricAlgorithm = Aes.Create(); symmetricAlgorithm.KeySize = 192; break; case "2.16.840.1.101.3.4.1.42": symmetricAlgorithm = Aes.Create(); symmetricAlgorithm.KeySize = 256; break; default: throw new CryptographicException(System.SR.Cryptography_Cms_UnknownAlgorithm, algorithmIdentifier); } symmetricAlgorithm.Padding = PaddingMode.PKCS7; symmetricAlgorithm.Mode = CipherMode.CBC; return symmetricAlgorithm; } public unsafe override Oid GetEncodedMessageType(ReadOnlySpan<byte> encodedMessage) { fixed (byte* pointer = encodedMessage) { using System.Buffers.PointerMemoryManager<byte> pointerMemoryManager = new System.Buffers.PointerMemoryManager<byte>(pointer, encodedMessage.Length); System.Formats.Asn1.AsnValueReader reader = new System.Formats.Asn1.AsnValueReader(encodedMessage, AsnEncodingRules.BER); System.Security.Cryptography.Asn1.Pkcs7.ContentInfoAsn.Decode(ref reader, pointerMemoryManager.Memory, out var decoded); switch (decoded.ContentType) { case "1.2.840.113549.1.7.1": case "1.2.840.113549.1.7.2": case "1.2.840.113549.1.7.3": case "1.2.840.113549.1.7.4": case "1.2.840.113549.1.7.5": case "1.2.840.113549.1.7.6": return new Oid(decoded.ContentType); default: throw new CryptographicException(System.SR.Cryptography_Cms_InvalidMessageType); } } } public override DecryptorPal Decode(ReadOnlySpan<byte> encodedMessage, out int version, out ContentInfo contentInfo, out AlgorithmIdentifier contentEncryptionAlgorithm, out X509Certificate2Collection originatorCerts, out CryptographicAttributeObjectCollection unprotectedAttributes) { byte[] array = CopyContent(encodedMessage); EnvelopedDataAsn envelopedDataAsn = EnvelopedDataAsn.Decode(array, AsnEncodingRules.BER); version = envelopedDataAsn.Version; contentInfo = new ContentInfo(new Oid(envelopedDataAsn.EncryptedContentInfo.ContentType), envelopedDataAsn.EncryptedContentInfo.EncryptedContent?.ToArray() ?? Array.Empty<byte>()); contentEncryptionAlgorithm = envelopedDataAsn.EncryptedContentInfo.ContentEncryptionAlgorithm.ToPresentationObject(); originatorCerts = new X509Certificate2Collection(); if (envelopedDataAsn.OriginatorInfo.HasValue && envelopedDataAsn.OriginatorInfo.Value.CertificateSet != null) { CertificateChoiceAsn[] certificateSet = envelopedDataAsn.OriginatorInfo.Value.CertificateSet; for (int i = 0; i < certificateSet.Length; i++) { CertificateChoiceAsn certificateChoiceAsn = certificateSet[i]; if (certificateChoiceAsn.Certificate.HasValue) { originatorCerts.Add(new X509Certificate2(certificateChoiceAsn.Certificate.Value.ToArray())); } } } unprotectedAttributes = SignerInfo.MakeAttributeCollection(envelopedDataAsn.UnprotectedAttributes); List<RecipientInfo> list = new List<RecipientInfo>(); RecipientInfoAsn[] recipientInfos = envelopedDataAsn.RecipientInfos; for (int j = 0; j < recipientInfos.Length; j++) { RecipientInfoAsn recipientInfoAsn = recipientInfos[j]; if (recipientInfoAsn.Ktri.HasValue) { list.Add(new KeyTransRecipientInfo(new ManagedKeyTransPal(recipientInfoAsn.Ktri.Value))); continue; } if (recipientInfoAsn.Kari.HasValue) { for (int k = 0; k < recipientInfoAsn.Kari.Value.RecipientEncryptedKeys.Length; k++) { list.Add(new KeyAgreeRecipientInfo(new ManagedKeyAgreePal(recipientInfoAsn.Kari.Value, k))); } continue; } throw new CryptographicException(); } return new ManagedDecryptorPal(array, envelopedDataAsn, new RecipientInfoCollection(list)); } private unsafe static byte[] CopyContent(ReadOnlySpan<byte> encodedMessage) { fixed (byte* pointer = encodedMessage) { using System.Buffers.PointerMemoryManager<byte> pointerMemoryManager = new System.Buffers.PointerMemoryManager<byte>(pointer, encodedMessage.Length); System.Formats.Asn1.AsnValueReader reader = new System.Formats.Asn1.AsnValueReader(encodedMessage, AsnEncodingRules.BER); System.Security.Cryptography.Asn1.Pkcs7.ContentInfoAsn.Decode(ref reader, pointerMemoryManager.Memory, out var decoded); if (decoded.ContentType != "1.2.840.113549.1.7.3") { throw new CryptographicException(System.SR.Cryptography_Cms_InvalidMessageType); } return decoded.Content.ToArray(); } } public unsafe override byte[] Encrypt(CmsRecipientCollection recipients, ContentInfo contentInfo, AlgorithmIdentifier contentEncryptionAlgorithm, X509Certificate2Collection originatorCerts, CryptographicAttributeObjectCollection unprotectedAttributes) { byte[] cek; byte[] parameterBytes; byte[] encryptedContent = EncryptContent(contentInfo, contentEncryptionAlgorithm, out cek, out parameterBytes); fixed (byte* ptr = cek) { try { return Encrypt(recipients, contentInfo, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes, encryptedContent, cek, parameterBytes); } finally { Array.Clear(cek, 0, cek.Length); } } } private byte[] Encrypt(CmsRecipientCollection recipients, ContentInfo contentInfo, AlgorithmIdentifier contentEncryptionAlgorithm, X509Certificate2Collection originatorCerts, CryptographicAttributeObjectCollection unprotectedAttributes, byte[] encryptedContent, byte[] cek, byte[] parameterBytes) { EnvelopedDataAsn envelopedDataAsn = default(EnvelopedDataAsn); envelopedDataAsn.EncryptedContentInfo.ContentType = contentInfo.ContentType.Value; envelopedDataAsn.EncryptedContentInfo.ContentEncryptionAlgorithm.Algorithm = contentEncryptionAlgorithm.Oid.Value; envelopedDataAsn.EncryptedContentInfo.ContentEncryptionAlgorithm.Parameters = parameterBytes; envelopedDataAsn.EncryptedContentInfo.EncryptedContent = encryptedContent; EnvelopedDataAsn envelopedDataAsn2 = envelopedDataAsn; if (unprotectedAttributes != null && unprotectedAttributes.Count > 0) { List<System.Security.Cryptography.Asn1.AttributeAsn> list = CmsSigner.BuildAttributes(unprotectedAttributes); envelopedDataAsn2.UnprotectedAttributes = PkcsHelpers.NormalizeAttributeSet(list.ToArray()); } if (originatorCerts != null && originatorCerts.Count > 0) { CertificateChoiceAsn[] array = new CertificateChoiceAsn[originatorCerts.Count]; for (int i = 0; i < originatorCerts.Count; i++) { array[i].Certificate = originatorCerts[i].RawData; } envelopedDataAsn2.OriginatorInfo = new OriginatorInfoAsn { CertificateSet = array }; } envelopedDataAsn2.RecipientInfos = new RecipientInfoAsn[recipients.Count]; bool flag = true; for (int j = 0; j < recipients.Count; j++) { CmsRecipient cmsRecipient = recipients[j]; RecipientInfoAsn[] recipientInfos = envelopedDataAsn2.RecipientInfos; int num = j; _ = ref recipientInfos[num]; string keyAlgorithm = cmsRecipient.Certificate.GetKeyAlgorithm(); if (keyAlgorithm == "1.2.840.113549.1.1.1") { bool v0Recipient; KeyTransRecipientInfoAsn value = MakeKtri(cek, cmsRecipient, out v0Recipient); recipientInfos[num].Ktri = value; flag = flag && v0Recipient; continue; } throw new CryptographicException(System.SR.Cryptography_Cms_UnknownAlgorithm, cmsRecipient.Certificate.GetKeyAlgorithm()); } if (envelopedDataAsn2.OriginatorInfo.HasValue || !flag || envelopedDataAsn2.UnprotectedAttributes != null) { envelopedDataAsn2.Version = 2; } AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.DER); envelopedDataAsn2.Encode(asnWriter); return PkcsHelpers.EncodeContentInfo(asnWriter.Encode(), "1.2.840.113549.1.7.3"); } private static byte[] EncryptContent(ContentInfo contentInfo, AlgorithmIdentifier contentEncryptionAlgorithm, out byte[] cek, out byte[] parameterBytes) { using (SymmetricAlgorithm symmetricAlgorithm = OpenAlgorithm(contentEncryptionAlgorithm)) { cek = symmetricAlgorithm.Key; if (symmetricAlgorithm is RC2) { System.Security.Cryptography.Asn1.Rc2CbcParameters rc2CbcParameters = new System.Security.Cryptography.Asn1.Rc2CbcParameters(symmetricAlgorithm.IV, symmetricAlgorithm.KeySize); AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.DER); rc2CbcParameters.Encode(asnWriter); parameterBytes = asnWriter.Encode(); } else { parameterBytes = PkcsHelpers.EncodeOctetString(symmetricAlgorithm.IV); } byte[] content = contentInfo.Content; if (contentInfo.ContentType.Value == "1.2.840.113549.1.7.1" || contentInfo.Content.Length == 0) { return EncryptOneShot(symmetricAlgorithm, contentInfo.Content); } try { AsnDecoder.ReadEncodedValue(contentInfo.Content, AsnEncodingRules.BER, out var contentOffset, out var contentLength, out var _); ReadOnlySpan<byte> plaintext2 = contentInfo.Content.AsSpan(contentOffset, contentLength); return EncryptOneShot(symmetricAlgorithm, plaintext2); } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } static byte[] EncryptOneShot(SymmetricAlgorithm alg, ReadOnlySpan<byte> plaintext) { using ICryptoTransform transform = alg.CreateEncryptor(); return transform.OneShot(plaintext.ToArray()); } } public override Exception CreateRecipientsNotFoundException() { return new CryptographicException(System.SR.Cryptography_Cms_RecipientNotFound); } public override Exception CreateRecipientInfosAfterEncryptException() { return CreateInvalidMessageTypeException(); } public override Exception CreateDecryptAfterEncryptException() { return CreateInvalidMessageTypeException(); } public override Exception CreateDecryptTwiceException() { return CreateInvalidMessageTypeException(); } private static CryptographicException CreateInvalidMessageTypeException() { return new CryptographicException(System.SR.Cryptography_Cms_InvalidMessageType); } private KeyTransRecipientInfoAsn MakeKtri(byte[] cek, CmsRecipient recipient, out bool v0Recipient) { KeyTransRecipientInfoAsn result = default(KeyTransRecipientInfoAsn); if (recipient.RecipientIdentifierType == SubjectIdentifierType.SubjectKeyIdentifier) { result.Version = 2; result.Rid.SubjectKeyIdentifier = GetSubjectKeyIdentifier(recipient.Certificate); } else { if (recipient.RecipientIdentifierType != SubjectIdentifierType.IssuerAndSerialNumber) { throw new CryptographicException(System.SR.Cryptography_Cms_Invalid_Subject_Identifier_Type, recipient.RecipientIdentifierType.ToString()); } byte[] serialNumber = recipient.Certificate.GetSerialNumber(); Array.Reverse(serialNumber); IssuerAndSerialNumberAsn issuerAndSerialNumberAsn = default(IssuerAndSerialNumberAsn); issuerAndSerialNumberAsn.Issuer = recipient.Certificate.IssuerName.RawData; issuerAndSerialNumberAsn.SerialNumber = serialNumber; IssuerAndSerialNumberAsn value = issuerAndSerialNumberAsn; result.Rid.IssuerAndSerialNumber = value; } RSAEncryptionPadding rSAEncryptionPadding = recipient.RSAEncryptionPadding ?? RSAEncryptionPadding.Pkcs1; if (rSAEncryptionPadding == RSAEncryptionPadding.Pkcs1) { result.KeyEncryptionAlgorithm.Algorithm = "1.2.840.113549.1.1.1"; result.KeyEncryptionAlgorithm.Parameters = PkcsPal.s_rsaPkcsParameters; } else if (rSAEncryptionPadding == RSAEncryptionPadding.OaepSHA1) { result.KeyEncryptionAlgorithm.Algorithm = "1.2.840.113549.1.1.7"; result.KeyEncryptionAlgorithm.Parameters = PkcsPal.s_rsaOaepSha1Parameters; } else if (rSAEncryptionPadding == RSAEncryptionPadding.OaepSHA256) { result.KeyEncryptionAlgorithm.Algorithm = "1.2.840.113549.1.1.7"; result.KeyEncryptionAlgorithm.Parameters = PkcsPal.s_rsaOaepSha256Parameters; } else if (rSAEncryptionPadding == RSAEncryptionPadding.OaepSHA384) { result.KeyEncryptionAlgorithm.Algorithm = "1.2.840.113549.1.1.7"; result.KeyEncryptionAlgorithm.Parameters = PkcsPal.s_rsaOaepSha384Parameters; } else { if (!(rSAEncryptionPadding == RSAEncryptionPadding.OaepSHA512)) { throw new CryptographicException(System.SR.Cryptography_Cms_UnknownAlgorithm); } result.KeyEncryptionAlgorithm.Algorithm = "1.2.840.113549.1.1.7"; result.KeyEncryptionAlgorithm.Parameters = PkcsPal.s_rsaOaepSha512Parameters; } using (RSA rSA = recipient.Certificate.GetRSAPublicKey()) { result.EncryptedKey = rSA.Encrypt(cek, rSAEncryptionPadding); } v0Recipient = result.Version == 0; return result; } private static byte[] DecryptKey(RSA privateKey, RSAEncryptionPadding encryptionPadding, ReadOnlySpan<byte> encryptedKey, out Exception exception) { if (privateKey == null) { exception = new CryptographicException(System.SR.Cryptography_Cms_Signing_RequiresPrivateKey); return null; } byte[] array = null; int bytesWritten = 0; try { array = System.Security.Cryptography.CryptoPool.Rent(privateKey.KeySize / 8); if (!privateKey.TryDecrypt(encryptedKey, array, encryptionPadding, out bytesWritten)) { exception = new CryptographicException(); return null; } exception = null; return new Span<byte>(array, 0, bytesWritten).ToArray(); } catch (CryptographicException ex) { exception = ex; return null; } finally { if (array != null) { System.Security.Cryptography.CryptoPool.Return(array, bytesWritten); } } } } } 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 unsafe static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper) { return string.Create(bytes.Length * 2, ((IntPtr)(&bytes), casing), delegate(Span<char> chars, (IntPtr RosPtr, Casing casing) args) { EncodeToUtf16(*(ReadOnlySpan<byte>*)(void*)args.RosPtr, chars, args.casing); }); } [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 Arg_EmptyOrNullString_Named => GetResourceString("Arg_EmptyOrNullString_Named"); internal static string Arg_RankMultiDimNotSupported => GetResourceString("Arg_RankMultiDimNotSupported"); internal static string Argument_EncodeDestinationTooSmall => GetResourceString("Argument_EncodeDestinationTooSmall"); internal static string Argument_InvalidOffLen => GetResourceString("Argument_InvalidOffLen"); internal static string Argument_InvalidOidValue => GetResourceString("Argument_InvalidOidValue"); internal static string Argument_InvalidValue => GetResourceString("Argument_InvalidValue"); internal static string Argument_InvalidRsaSignaturePadding => GetResourceString("Argument_InvalidRsaSignaturePadding"); internal static string ArgumentOutOfRange_IndexMustBeLess => GetResourceString("ArgumentOutOfRange_IndexMustBeLess"); internal static string ArgumentOutOfRange_IndexMustBeLessOrEqual => GetResourceString("ArgumentOutOfRange_IndexMustBeLessOrEqual"); internal static string ArgumentOutOfRange_NeedPosNum => GetResourceString("ArgumentOutOfRange_NeedPosNum"); internal static string Cryptography_AlgKdfRequiresChars => GetResourceString("Cryptography_AlgKdfRequiresChars"); internal static string Cryptography_BadHashValue => GetResourceString("Cryptography_BadHashValue"); internal static string Cryptography_BadSignature => GetResourceString("Cryptography_BadSignature"); internal static string Cryptography_Cms_CannotDetermineSignatureAlgorithm => GetResourceString("Cryptography_Cms_CannotDetermineSignatureAlgorithm"); internal static string Cryptography_Cms_IncompleteCertChain => GetResourceString("Cryptography_Cms_IncompleteCertChain"); internal static string Cryptography_Cms_Invalid_Originator_Identifier_Choice => GetResourceString("Cryptography_Cms_Invalid_Originator_Identifier_Choice"); internal static string Cryptography_Cms_Invalid_Subject_Identifier_Type => GetResourceString("Cryptography_Cms_Invalid_Subject_Identifier_Type"); internal static string Cryptography_Cms_InvalidMessageType => GetResourceString("Cryptography_Cms_InvalidMessageType"); internal static string Cryptography_Cms_InvalidSignerHashForSignatureAlg => GetResourceString("Cryptography_Cms_InvalidSignerHashForSignatureAlg"); internal static string Cryptography_Cms_Key_Agree_Date_Not_Available => GetResourceString("Cryptography_Cms_Key_Agree_Date_Not_Available"); internal static string Cryptography_Cms_MessageNotEncrypted => GetResourceString("Cryptography_Cms_MessageNotEncrypted"); internal static string Cryptography_Cms_MessageNotSigned => GetResourceString("Cryptography_Cms_MessageNotSigned"); internal static string Cryptography_Cms_MissingAuthenticatedAttribute => GetResourceString("Cryptography_Cms_MissingAuthenticatedAttribute"); internal static string Cryptography_Cms_NoCounterCounterSigner => GetResourceString("Cryptography_Cms_NoCounterCounterSigner"); internal static string Cryptography_Cms_NoRecipients => GetResourceString("Cryptography_Cms_NoRecipients"); internal static string Cryptography_Cms_NoSignerCert => GetResourceString("Cryptography_Cms_NoSignerCert"); internal static string Cryptography_Cms_NoSignerCertSilent => GetResourceString("Cryptography_Cms_NoSignerCertSilent"); internal static string Cryptography_Cms_NoSignerAtIndex => GetResourceString("Cryptography_Cms_NoSignerAtIndex"); internal static string Cryptography_Cms_RecipientNotFound => GetResourceString("Cryptography_Cms_RecipientNotFound"); internal static string Cryptography_Cms_RecipientType_NotSupported => GetResourceString("Cryptography_Cms_RecipientType_NotSupported"); internal static string Cryptography_Cms_Sign_Empty_Content => GetResourceString("Cryptography_Cms_Sign_Empty_Content"); internal static string Cryptography_Cms_Sign_No_Signature_First_Signer => GetResourceString("Cryptography_Cms_Sign_No_Signature_First_Signer"); internal static string Cryptography_Cms_SignerNotFound => GetResourceString("Cryptography_Cms_SignerNotFound"); internal static string Cryptography_Cms_Signing_RequiresPrivateKey => GetResourceString("Cryptography_Cms_Signing_RequiresPrivateKey"); internal static string Cryptography_Cms_Ktri_RSARequired => GetResourceString("Cryptography_Cms_Ktri_RSARequired"); internal static string Cryptography_Cms_Recipient_RSARequired_RSAPaddingModeSupplied => GetResourceString("Cryptography_Cms_Recipient_RSARequired_RSAPaddingModeSupplied"); internal static string Cryptography_Cms_TrustFailure => GetResourceString("Cryptography_Cms_TrustFailure"); internal static string Cryptography_Cms_UnknownAlgorithm => GetResourceString("Cryptography_Cms_UnknownAlgorithm"); internal static string Cryptography_Cms_UnknownKeySpec => GetResourceString("Cryptography_Cms_UnknownKeySpec"); internal static string Cryptography_Cms_WrongKeyUsage => GetResourceString("Cryptography_Cms_WrongKeyUsage"); internal static string Cryptography_NotValidPublicOrPrivateKey => GetResourceString("Cryptography_NotValidPublicOrPrivateKey"); internal static string Cryptography_Pkcs12_CannotProcessEncryptedSafeContents => GetResourceString("Cryptography_Pkcs12_CannotProcessEncryptedSafeContents"); internal static string Cryptography_Pkcs12_CertBagNotX509 => GetResourceString("Cryptography_Pkcs12_CertBagNotX509"); internal static string Cryptography_Pkcs12_PfxIsSealed => GetResourceString("Cryptography_Pkcs12_PfxIsSealed"); internal static string Cryptography_Pkcs12_PfxMustBeSealed => GetResourceString("Cryptography_Pkcs12_PfxMustBeSealed"); internal static string Cryptography_Pkcs12_SafeContentsIsEncrypted => GetResourceString("Cryptography_Pkcs12_SafeContentsIsEncrypted"); internal static string Cryptography_Pkcs12_SafeContentsIsReadOnly => GetResourceString("Cryptography_Pkcs12_SafeContentsIsReadOnly"); internal static string Cryptography_Pkcs12_WrongModeForDecrypt => GetResourceString("Cryptography_Pkcs12_WrongModeForDecrypt"); internal static string Cryptography_Pkcs12_WrongModeForVerify => GetResourceString("Cryptography_Pkcs12_WrongModeForVerify"); internal static string Cryptography_Pkcs_InvalidSignatureParameters => GetResourceString("Cryptography_Pkcs_InvalidSignatureParameters"); internal static string Cryptography_Pkcs8_EncryptedReadFailed => GetResourceString("Cryptography_Pkcs8_EncryptedReadFailed"); internal static string Cryptography_Pkcs9_AttributeMismatch => GetResourceString("Cryptography_Pkcs9_AttributeMismatch"); internal static string Cryptography_Pkcs9_MultipleSigningTimeNotAllowed => GetResourceString("Cryptography_Pkcs9_MultipleSigningTimeNotAllowed"); internal static string Cryptography_Pkcs_PssParametersMissing => GetResourceString("Cryptography_Pkcs_PssParametersMissing"); internal static string Cryptography_Pkcs_PssParametersHashMismatch => GetResourceString("Cryptography_Pkcs_PssParametersHashMismatch"); internal static string Cryptography_Pkcs_PssParametersMgfHashMismatch => GetResourceString("Cryptography_Pkcs_PssParametersMgfHashMismatch"); internal static string Cryptography_Pkcs_PssParametersMgfNotSupported => GetResourceString("Cryptography_Pkcs_PssParametersMgfNotSupported"); internal static string Cryptography_Pkcs_PssParametersSaltMismatch => GetResourceString("Cryptography_Pkcs_PssParametersSaltMismatch"); internal static string Cryptography_TimestampReq_BadNonce => GetResourceString("Cryptography_TimestampReq_BadNonce"); internal static string Cryptography_TimestampReq_BadResponse => GetResourceString("Cryptography_TimestampReq_BadResponse"); internal static string Cryptography_TimestampReq_Failure => GetResourceString("Cryptography_TimestampReq_Failure"); internal static string Cryptography_TimestampReq_NoCertFound => GetResourceString("Cryptography_TimestampReq_NoCertFound"); internal static string Cryptography_TimestampReq_UnexpectedCertFound => GetResourceString("Cryptography_TimestampReq_UnexpectedCertFound"); internal static string InvalidOperation_DuplicateItemNotAllowed => GetResourceString("InvalidOperation_DuplicateItemNotAllowed"); internal static string InvalidOperation_WrongOidInAsnCollection => GetResourceString("InvalidOperation_WrongOidInAsnCollection"); internal static string PlatformNotSupported_CryptographyPkcs => GetResourceString("PlatformNotSupported_CryptographyPkcs"); internal static string Cryptography_AlgorithmNotSupported => GetResourceString("Cryptography_AlgorithmNotSupported"); internal static string Cryptography_Der_Invalid_Encoding => GetResourceString("Cryptography_Der_Invalid_Encoding"); internal static string Cryptography_Invalid_IA5String => GetResourceString("Cryptography_Invalid_IA5String"); internal static string Cryptography_UnknownAlgorithmIdentifier => GetResourceString("Cryptography_UnknownAlgorithmIdentifier"); internal static string Cryptography_UnknownHashAlgorithm => GetResourceString("Cryptography_UnknownHashAlgorithm"); internal static string Cryptography_Cms_NoAttributeFound => GetResourceString("Cryptography_Cms_NoAttributeFound"); internal static string Cryptography_Cms_NoCertificateFound => GetResourceString("Cryptography_Cms_NoCertificateFound"); internal static string Cryptography_Cms_CertificateAlreadyInCollection => GetResourceString("Cryptography_Cms_CertificateAlreadyInCollection"); internal static string Cryptography_Cms_InvalidSymmetricKey => GetResourceString("Cryptography_Cms_InvalidSymmetricKey"); internal static string Cryptography_X509_PfxWithoutPassword_MaxAllowedIterationsExceeded => GetResourceString("Cryptography_X509_PfxWithoutPassword_MaxAllowedIterationsExceeded"); internal static string Cryptography_X509_PfxWithoutPassword_ProblemFound => GetResourceString("Cryptography_X509_PfxWithoutPassword_ProblemFound"); 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.Diagnostics.CodeAnalysis { [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.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.Buffers { internal sealed class PointerMemoryManager<T> : MemoryManager<T> where T : struct { private unsafe readonly void* _pointer; private readonly int _length; internal unsafe PointerMemoryManager(void* pointer, int length) { _pointer = pointer; _length = length; } protected override void Dispose(bool disposing) { } public unsafe override Span<T> GetSpan() { return new Span<T>(_pointer, _length); } public override MemoryHandle Pin(int elementIndex = 0) { throw new NotSupportedException(); } public override void Unpin() { } } } namespace System.Security.Cryptography { public sealed class CryptographicAttributeObject { private readonly Oid _oid; public Oid Oid => _oid.CopyOid(); public AsnEncodedDataCollection Values { get; } public CryptographicAttributeObject(Oid oid) : this(oid, new AsnEncodedDataCollection()) { } public CryptographicAttributeObject(Oid oid, AsnEncodedDataCollection? values) { _oid = oid.CopyOid(); if (values == null) { Values = new AsnEncodedDataCollection(); return; } AsnEncodedDataEnumerator enumerator = values.GetEnumerator(); while (enumerator.MoveNext()) { AsnEncodedData current = enumerator.Current; if (current.Oid == null) { throw new ArgumentException(System.SR.Argument_InvalidOidValue, "values"); } if (!string.Equals(current.Oid.Value, oid.Value, StringComparison.Ordinal)) { throw new InvalidOperationException(System.SR.Format(System.SR.InvalidOperation_WrongOidInAsnCollection, oid.Value, current.Oid.Value)); } } Values = values; } } public sealed class CryptographicAttributeObjectCollection : ICollection, IEnumerable { private readonly List<CryptographicAttributeObject> _list; public CryptographicAttributeObject this[int index] => _list[index]; public int Count => _list.Count; public bool IsSynchronized => false; public object SyncRoot => this; public CryptographicAttributeObjectCollection() { _list = new List<CryptographicAttributeObject>(); } public CryptographicAttributeObjectCollection(CryptographicAttributeObject attribute) { _list = new List<CryptographicAttributeObject>(); _list.Add(attribute); } public int Add(AsnEncodedData asnEncodedData) { if (asnEncodedData == null) { throw new ArgumentNullException("asnEncodedData"); } return Add(new CryptographicAttributeObject(asnEncodedData.Oid, new AsnEncodedDataCollection(asnEncodedData))); } public int Add(CryptographicAttributeObject attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } string value = attribute.Oid.Value; for (int i = 0; i < _list.Count; i++) { CryptographicAttributeObject cryptographicAttributeObject = _list[i]; if (cryptographicAttributeObject.Values == attribute.Values) { throw new InvalidOperationException(System.SR.InvalidOperation_DuplicateItemNotAllowed); } string value2 = cryptographicAttributeObject.Oid.Value; if (string.Equals(value, value2, StringComparison.OrdinalIgnoreCase)) { if (string.Equals(value, "1.2.840.113549.1.9.5", StringComparison.OrdinalIgnoreCase)) { throw new CryptographicException(System.SR.Cryptography_Pkcs9_MultipleSigningTimeNotAllowed); } AsnEncodedDataEnumerator enumerator = attribute.Values.GetEnumerator(); while (enumerator.MoveNext()) { AsnEncodedData current = enumerator.Current; cryptographicAttributeObject.Values.Add(current); } return i; } } int count = _list.Count; _list.Add(attribute); return count; } internal void AddWithoutMerge(CryptographicAttributeObject attribute) { _list.Add(attribute); } public void Remove(CryptographicAttributeObject attribute) { if (attribute == null) { throw new ArgumentNullException("attribute"); } _list.Remove(attribute); } public CryptographicAttributeObjectEnumerator GetEnumerator() { return new CryptographicAttributeObjectEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new CryptographicAttributeObjectEnumerator(this); } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(System.SR.Arg_RankMultiDimNotSupported); } if (index < 0 || index >= array.Length) { throw new ArgumentOutOfRangeException("index", System.SR.ArgumentOutOfRange_IndexMustBeLess); } if (index > array.Length - Count) { throw new ArgumentException(System.SR.Argument_InvalidOffLen); } for (int i = 0; i < Count; i++) { array.SetValue(this[i], index); index++; } } public void CopyTo(CryptographicAttributeObject[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || index >= array.Length) { throw new ArgumentOutOfRangeException("index", System.SR.ArgumentOutOfRange_IndexMustBeLess); } if (index > array.Length - Count) { throw new ArgumentException(System.SR.Argument_InvalidOffLen); } _list.CopyTo(array, index); } } public sealed class CryptographicAttributeObjectEnumerator : IEnumerator { private readonly CryptographicAttributeObjectCollection _attributes; private int _current; public CryptographicAttributeObject Current => _attributes[_current]; object IEnumerator.Current => _attributes[_current]; internal CryptographicAttributeObjectEnumerator(CryptographicAttributeObjectCollection attributes) { _attributes = attributes; _current = -1; } public bool MoveNext() { if (_current >= _attributes.Count - 1) { return false; } _current++; return true; } public void Reset() { _current = -1; } } internal static class CryptoPool { internal const int ClearAll = -1; internal static byte[] Rent(int minimumLength) { return ArrayPool<byte>.Shared.Rent(minimumLength); } internal static void Return(ArraySegment<byte> arraySegment) { Return(arraySegment.Array, arraySegment.Count); } internal static void Return(byte[] array, int clearSize = -1) { bool flag = clearSize < 0; if (!flag && clearSize != 0) { CryptographicOperations.ZeroMemory(array.AsSpan(0, clearSize)); } ArrayPool<byte>.Shared.Return(array, flag); } } internal static class Oids { internal const string Rc2Cbc = "1.2.840.113549.3.2"; internal const string Rc4 = "1.2.840.113549.3.4"; internal const string TripleDesCbc = "1.2.840.113549.3.7"; internal const string DesCbc = "1.3.14.3.2.7"; internal const string Aes128Cbc = "2.16.840.1.101.3.4.1.2"; internal const string Aes192Cbc = "2.16.840.1.101.3.4.1.22"; internal const string Aes256Cbc = "2.16.840.1.101.3.4.1.42"; internal const string Dsa = "1.2.840.10040.4.1"; internal const string Rsa = "1.2.840.113549.1.1.1"; internal const string RsaOaep = "1.2.840.113549.1.1.7"; internal const string RsaPss = "1.2.840.113549.1.1.10"; internal const string RsaPkcs1Md5 = "1.2.840.113549.1.1.4"; internal const string RsaPkcs1Sha1 = "1.2.840.113549.1.1.5"; internal const string RsaPkcs1Sha256 = "1.2.840.113549.1.1.11"; internal const string RsaPkcs1Sha384 = "1.2.840.113549.1.1.12"; internal const string RsaPkcs1Sha512 = "1.2.840.113549.1.1.13"; internal const string RsaPkcs1Sha3_256 = "2.16.840.1.101.3.4.3.14"; internal const string RsaPkcs1Sha3_384 = "2.16.840.1.101.3.4.3.15"; internal const string RsaPkcs1Sha3_512 = "2.16.840.1.101.3.4.3.16"; internal const string Esdh = "1.2.840.113549.1.9.16.3.5"; internal const string EcDiffieHellman = "1.3.132.1.12"; internal const string DiffieHellman = "1.2.840.10046.2.1"; internal const string DiffieHellmanPkcs3 = "1.2.840.113549.1.3.1"; internal const string SigningTime = "1.2.840.113549.1.9.5"; internal const string ContentType = "1.2.840.113549.1.9.3"; internal const string DocumentDescription = "1.3.6.1.4.1.311.88.2.2"; internal const string MessageDigest = "1.2.840.113549.1.9.4"; internal const string CounterSigner = "1.2.840.113549.1.9.6"; internal const string SigningCertificate = "1.2.840.113549.1.9.16.2.12"; internal const string SigningCertificateV2 = "1.2.840.113549.1.9.16.2.47"; internal const string DocumentName = "1.3.6.1.4.1.311.88.2.1"; internal const string LocalKeyId = "1.2.840.113549.1.9.21"; internal const string EnrollCertTypeExtension = "1.3.6.1.4.1.311.20.2"; internal const string UserPrincipalName = "1.3.6.1.4.1.311.20.2.3"; internal const string CertificateTemplate = "1.3.6.1.4.1.311.21.7"; internal const string ApplicationCertPolicies = "1.3.6.1.4.1.311.21.10"; internal const string AuthorityInformationAccess = "1.3.6.1.5.5.7.1.1"; internal const string OcspEndpoint = "1.3.6.1.5.5.7.48.1"; internal const string CertificateAuthorityIssuers = "1.3.6.1.5.5.7.48.2"; internal const string Pkcs9ExtensionRequest = "1.2.840.113549.1.9.14"; internal const string CmsRc2Wrap = "1.2.840.113549.1.9.16.3.7"; internal const string Cms3DesWrap = "1.2.840.113549.1.9.16.3.6"; internal const string Pkcs7Data = "1.2.840.113549.1.7.1"; internal const string Pkcs