using System; using System.Buffers; using System.Buffers.Binary; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Formats.Asn1; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Security.Cryptography.Asn1; using System.Security.Cryptography.Pkcs; using System.Text; using FxResources.System.Security.Cryptography.Cng; using Internal.Cryptography; using Internal.NativeCrypto; using Microsoft.CodeAnalysis; using Microsoft.Win32.SafeHandles; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: CLSCompliant(true)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyDefaultAlias("System.Security.Cryptography.Cng")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Internal implementation package not meant for direct consumption. Please do not reference directly.")] [assembly: AssemblyFileVersion("6.0.722.32202")] [assembly: AssemblyInformationalVersion("6.0.7+0ec02c8c96e2eda06dc5b5edfdbdba0f36415082")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Security.Cryptography.Cng")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: TargetPlatform("Windows7.0")] [assembly: SupportedOSPlatform("Windows")] [assembly: AssemblyVersion("6.0.0.0")] [module: System.Runtime.CompilerServices.NullablePublicOnly(false)] [module: SkipLocalsInit] 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; } } } internal static class Interop { internal static class BCrypt { private struct BCRYPT_KEY_DATA_BLOB_HEADER { public uint dwMagic; public uint dwVersion; public uint cbKeyData; } internal enum NTSTATUS : uint { STATUS_SUCCESS = 0u, STATUS_NOT_FOUND = 3221226021u, STATUS_INVALID_PARAMETER = 3221225485u, STATUS_NO_MEMORY = 3221225495u, STATUS_AUTH_TAG_MISMATCH = 3221266434u } internal struct BCRYPT_OAEP_PADDING_INFO { internal IntPtr pszAlgId; internal IntPtr pbLabel; internal int cbLabel; } internal struct BCRYPT_PKCS1_PADDING_INFO { internal IntPtr pszAlgId; } internal struct BCRYPT_PSS_PADDING_INFO { internal IntPtr pszAlgId; internal int cbSalt; } internal enum KeyBlobMagicNumber { BCRYPT_DSA_PUBLIC_MAGIC = 1112560452, BCRYPT_DSA_PRIVATE_MAGIC = 1448104772, BCRYPT_DSA_PUBLIC_MAGIC_V2 = 843206724, BCRYPT_DSA_PRIVATE_MAGIC_V2 = 844517444, BCRYPT_ECDH_PUBLIC_P256_MAGIC = 827016005, BCRYPT_ECDH_PRIVATE_P256_MAGIC = 843793221, BCRYPT_ECDH_PUBLIC_P384_MAGIC = 860570437, BCRYPT_ECDH_PRIVATE_P384_MAGIC = 877347653, BCRYPT_ECDH_PUBLIC_P521_MAGIC = 894124869, BCRYPT_ECDH_PRIVATE_P521_MAGIC = 910902085, BCRYPT_ECDH_PUBLIC_GENERIC_MAGIC = 1347109701, BCRYPT_ECDH_PRIVATE_GENERIC_MAGIC = 1447772997, BCRYPT_ECDSA_PUBLIC_P256_MAGIC = 827540293, BCRYPT_ECDSA_PRIVATE_P256_MAGIC = 844317509, BCRYPT_ECDSA_PUBLIC_P384_MAGIC = 861094725, BCRYPT_ECDSA_PRIVATE_P384_MAGIC = 877871941, BCRYPT_ECDSA_PUBLIC_P521_MAGIC = 894649157, BCRYPT_ECDSA_PRIVATE_P521_MAGIC = 911426373, BCRYPT_ECDSA_PUBLIC_GENERIC_MAGIC = 1346650949, BCRYPT_ECDSA_PRIVATE_GENERIC_MAGIC = 1447314245, BCRYPT_RSAPUBLIC_MAGIC = 826364754, BCRYPT_RSAPRIVATE_MAGIC = 843141970, BCRYPT_RSAFULLPRIVATE_MAGIC = 859919186, BCRYPT_KEY_DATA_BLOB_MAGIC = 1296188491 } internal struct BCRYPT_RSAKEY_BLOB { internal KeyBlobMagicNumber Magic; internal int BitLength; internal int cbPublicExp; internal int cbModulus; internal int cbPrime1; internal int cbPrime2; } internal struct BCRYPT_DSA_KEY_BLOB { internal KeyBlobMagicNumber Magic; internal int cbKey; internal unsafe fixed byte Count[4]; internal unsafe fixed byte Seed[20]; internal unsafe fixed byte q[20]; } internal struct BCRYPT_DSA_KEY_BLOB_V2 { internal KeyBlobMagicNumber Magic; internal int cbKey; internal HASHALGORITHM_ENUM hashAlgorithm; internal DSAFIPSVERSION_ENUM standardVersion; internal int cbSeedLength; internal int cbGroupSize; internal unsafe fixed byte Count[4]; } public enum HASHALGORITHM_ENUM { DSA_HASH_ALGORITHM_SHA1, DSA_HASH_ALGORITHM_SHA256, DSA_HASH_ALGORITHM_SHA512 } public enum DSAFIPSVERSION_ENUM { DSA_FIPS186_2, DSA_FIPS186_3 } internal struct BCRYPT_ECCKEY_BLOB { internal KeyBlobMagicNumber Magic; internal int cbKey; } internal enum ECC_CURVE_TYPE_ENUM { BCRYPT_ECC_PRIME_SHORT_WEIERSTRASS_CURVE = 1, BCRYPT_ECC_PRIME_TWISTED_EDWARDS_CURVE, BCRYPT_ECC_PRIME_MONTGOMERY_CURVE } internal enum ECC_CURVE_ALG_ID_ENUM { BCRYPT_NO_CURVE_GENERATION_ALG_ID } internal struct BCRYPT_ECCFULLKEY_BLOB { internal KeyBlobMagicNumber Magic; internal int Version; internal ECC_CURVE_TYPE_ENUM CurveType; internal ECC_CURVE_ALG_ID_ENUM CurveGenerationAlgId; internal int cbFieldLength; internal int cbSubgroupOrder; internal int cbCofactor; internal int cbSeed; } internal enum CngBufferDescriptors { KDF_HASH_ALGORITHM = 0, KDF_SECRET_PREPEND = 1, KDF_SECRET_APPEND = 2, KDF_HMAC_KEY = 3, KDF_TLS_PRF_LABEL = 4, KDF_TLS_PRF_SEED = 5, KDF_SECRET_HANDLE = 6, KDF_TLS_PRF_PROTOCOL = 7, KDF_ALGORITHMID = 8, KDF_PARTYUINFO = 9, KDF_PARTYVINFO = 10, KDF_SUPPPUBINFO = 11, KDF_SUPPPRIVINFO = 12, KDF_LABEL = 13, KDF_CONTEXT = 14, KDF_SALT = 15, KDF_ITERATION_COUNT = 16, NCRYPTBUFFER_ECC_CURVE_NAME = 60 } internal struct BCryptBuffer { internal int cbBuffer; internal CngBufferDescriptors BufferType; internal IntPtr pvBuffer; } internal struct BCryptBufferDesc { internal int ulVersion; internal int cBuffers; internal IntPtr pBuffers; } internal struct BCRYPT_ECC_PARAMETER_HEADER { internal int Version; internal ECC_CURVE_TYPE_ENUM CurveType; internal ECC_CURVE_ALG_ID_ENUM CurveGenerationAlgId; internal int cbFieldLength; internal int cbSubgroupOrder; internal int cbCofactor; internal int cbSeed; } [Flags] internal enum BCryptOpenAlgorithmProviderFlags { None = 0, BCRYPT_ALG_HANDLE_HMAC_FLAG = 8 } [Flags] internal enum BCryptCreateHashFlags { None = 0, BCRYPT_HASH_REUSABLE_FLAG = 0x20 } internal static class BCryptAlgorithmCache { private struct Entry { public string HashAlgorithmId { get; private set; } public BCryptOpenAlgorithmProviderFlags Flags { get; private set; } public SafeBCryptAlgorithmHandle Handle { get; private set; } public int HashSizeInBytes { get; private set; } public unsafe Entry(string hashAlgorithmId, BCryptOpenAlgorithmProviderFlags flags, SafeBCryptAlgorithmHandle handle) { this = default(Entry); HashAlgorithmId = hashAlgorithmId; Flags = flags; Handle = handle; Unsafe.SkipInit(out int hashSizeInBytes); int pcbResult; NTSTATUS nTSTATUS = BCryptGetProperty(handle, "HashDigestLength", &hashSizeInBytes, 4, out pcbResult, 0); if (nTSTATUS != 0) { throw CreateCryptographicException(nTSTATUS); } HashSizeInBytes = hashSizeInBytes; } } private static volatile Entry[] _cache = Array.Empty(); public static SafeBCryptAlgorithmHandle GetCachedBCryptAlgorithmHandle(string hashAlgorithmId, BCryptOpenAlgorithmProviderFlags flags, out int hashSizeInBytes) { Entry[] array = _cache; Entry[] array2 = array; for (int i = 0; i < array2.Length; i++) { Entry entry = array2[i]; if (entry.HashAlgorithmId == hashAlgorithmId && entry.Flags == flags) { hashSizeInBytes = entry.HashSizeInBytes; return entry.Handle; } } SafeBCryptAlgorithmHandle phAlgorithm; NTSTATUS nTSTATUS = BCryptOpenAlgorithmProvider(out phAlgorithm, hashAlgorithmId, null, flags); if (nTSTATUS != 0) { throw CreateCryptographicException(nTSTATUS); } Array.Resize(ref array, array.Length + 1); Entry entry2 = new Entry(hashAlgorithmId, flags, phAlgorithm); array[^1] = new Entry(hashAlgorithmId, flags, phAlgorithm); _cache = array; hashSizeInBytes = entry2.HashSizeInBytes; return entry2.Handle; } } internal unsafe static SafeKeyHandle BCryptImportKey(SafeAlgorithmHandle hAlg, ReadOnlySpan key) { int length = key.Length; int num = sizeof(BCRYPT_KEY_DATA_BLOB_HEADER) + length; byte[] array = new byte[num]; fixed (byte* ptr = array) { BCRYPT_KEY_DATA_BLOB_HEADER* ptr2 = (BCRYPT_KEY_DATA_BLOB_HEADER*)ptr; ptr2->dwMagic = 1296188491u; ptr2->dwVersion = 1u; ptr2->cbKeyData = (uint)length; } key.CopyTo(array.AsSpan(sizeof(BCRYPT_KEY_DATA_BLOB_HEADER))); SafeKeyHandle hKey; NTSTATUS nTSTATUS = BCryptImportKey(hAlg, IntPtr.Zero, "KeyDataBlob", out hKey, IntPtr.Zero, 0, array, num, 0); if (nTSTATUS != 0) { throw CreateCryptographicException(nTSTATUS); } return hKey; } [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)] private static extern NTSTATUS BCryptImportKey(SafeAlgorithmHandle hAlgorithm, IntPtr hImportKey, string pszBlobType, out SafeKeyHandle hKey, IntPtr pbKeyObject, int cbKeyObject, byte[] pbInput, int cbInput, int dwFlags); internal unsafe static int BCryptEncrypt(SafeKeyHandle hKey, ReadOnlySpan input, byte[] iv, Span output) { fixed (byte* pbInput = input) { fixed (byte* pbOutput = output) { int cbResult; NTSTATUS nTSTATUS = BCryptEncrypt(hKey, pbInput, input.Length, IntPtr.Zero, iv, (iv != null) ? iv.Length : 0, pbOutput, output.Length, out cbResult, 0); if (nTSTATUS != 0) { throw CreateCryptographicException(nTSTATUS); } return cbResult; } } } internal unsafe static int BCryptDecrypt(SafeKeyHandle hKey, ReadOnlySpan input, byte[] iv, Span output) { fixed (byte* pbInput = input) { fixed (byte* pbOutput = output) { int cbResult; NTSTATUS nTSTATUS = BCryptDecrypt(hKey, pbInput, input.Length, IntPtr.Zero, iv, (iv != null) ? iv.Length : 0, pbOutput, output.Length, out cbResult, 0); if (nTSTATUS != 0) { throw CreateCryptographicException(nTSTATUS); } return cbResult; } } } [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)] public unsafe static extern NTSTATUS BCryptEncrypt(SafeKeyHandle hKey, byte* pbInput, int cbInput, IntPtr paddingInfo, [In][Out] byte[] pbIV, int cbIV, byte* pbOutput, int cbOutput, out int cbResult, int dwFlags); [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)] public unsafe static extern NTSTATUS BCryptDecrypt(SafeKeyHandle hKey, byte* pbInput, int cbInput, IntPtr paddingInfo, [In][Out] byte[] pbIV, int cbIV, byte* pbOutput, int cbOutput, out int cbResult, int dwFlags); internal static void Emit(byte[] blob, ref int offset, byte[] value) { Buffer.BlockCopy(value, 0, blob, offset, value.Length); offset += value.Length; } internal static void EmitByte(byte[] blob, ref int offset, byte value, int count = 1) { int num = offset + count; for (int i = offset; i < num; i++) { blob[i] = value; } offset = num; } internal static void EmitBigEndian(byte[] blob, ref int offset, int value) { blob[offset++] = (byte)(value >> 24); blob[offset++] = (byte)(value >> 16); blob[offset++] = (byte)(value >> 8); blob[offset++] = (byte)value; } internal static byte[] Consume(byte[] blob, ref int offset, int count) { byte[] array = new byte[count]; Buffer.BlockCopy(blob, offset, array, 0, count); offset += count; return array; } internal static Exception CreateCryptographicException(NTSTATUS ntStatus) { int hr = (int)(ntStatus | (NTSTATUS)16777216u); return hr.ToCryptographicException(); } [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)] internal static extern NTSTATUS BCryptOpenAlgorithmProvider(out SafeBCryptAlgorithmHandle phAlgorithm, string pszAlgId, string pszImplementation, BCryptOpenAlgorithmProviderFlags dwFlags); [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)] internal static extern NTSTATUS BCryptCloseAlgorithmProvider(IntPtr hAlgorithm, int dwFlags); internal static NTSTATUS BCryptCreateHash(SafeBCryptAlgorithmHandle hAlgorithm, out SafeBCryptHashHandle phHash, IntPtr pbHashObject, int cbHashObject, ReadOnlySpan secret, int cbSecret, BCryptCreateHashFlags dwFlags) { return BCryptCreateHash(hAlgorithm, out phHash, pbHashObject, cbHashObject, ref MemoryMarshal.GetReference(secret), cbSecret, dwFlags); } [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)] private static extern NTSTATUS BCryptCreateHash(SafeBCryptAlgorithmHandle hAlgorithm, out SafeBCryptHashHandle phHash, IntPtr pbHashObject, int cbHashObject, ref byte pbSecret, int cbSecret, BCryptCreateHashFlags dwFlags); [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)] internal static extern NTSTATUS BCryptDestroyHash(IntPtr hHash); internal static NTSTATUS BCryptHashData(SafeBCryptHashHandle hHash, ReadOnlySpan pbInput, int cbInput, int dwFlags) { return BCryptHashData(hHash, ref MemoryMarshal.GetReference(pbInput), cbInput, dwFlags); } [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)] private static extern NTSTATUS BCryptHashData(SafeBCryptHashHandle hHash, ref byte pbInput, int cbInput, int dwFlags); internal static NTSTATUS BCryptFinishHash(SafeBCryptHashHandle hHash, Span pbOutput, int cbOutput, int dwFlags) { return BCryptFinishHash(hHash, ref MemoryMarshal.GetReference(pbOutput), cbOutput, dwFlags); } [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)] private static extern NTSTATUS BCryptFinishHash(SafeBCryptHashHandle hHash, ref byte pbOutput, int cbOutput, int dwFlags); [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)] internal unsafe static extern NTSTATUS BCryptGetProperty(SafeBCryptHandle hObject, string pszProperty, void* pbOutput, int cbOutput, out int pcbResult, int dwFlags); } internal static class Crypt32 { internal struct CRYPT_OID_INFO { public int cbSize; public IntPtr pszOID; public IntPtr pwszName; public OidGroup dwGroupId; public int AlgId; public int cbData; public IntPtr pbData; public string Name => Marshal.PtrToStringUni(pwszName); } internal enum CryptOidInfoKeyType { CRYPT_OID_INFO_OID_KEY = 1, CRYPT_OID_INFO_NAME_KEY, CRYPT_OID_INFO_ALGID_KEY, CRYPT_OID_INFO_SIGN_KEY, CRYPT_OID_INFO_CNG_ALGID_KEY, CRYPT_OID_INFO_CNG_SIGN_KEY } internal static CRYPT_OID_INFO FindOidInfo(CryptOidInfoKeyType keyType, string key, OidGroup group, bool fallBackToAllGroups) { IntPtr intPtr = IntPtr.Zero; try { intPtr = keyType switch { CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY => Marshal.StringToCoTaskMemAnsi(key), CryptOidInfoKeyType.CRYPT_OID_INFO_NAME_KEY => Marshal.StringToCoTaskMemUni(key), _ => throw new NotSupportedException(), }; if (!OidGroupWillNotUseActiveDirectory(group)) { OidGroup group2 = group | (OidGroup)(-2147483648); IntPtr intPtr2 = CryptFindOIDInfo(keyType, intPtr, group2); if (intPtr2 != IntPtr.Zero) { return Marshal.PtrToStructure(intPtr2); } } IntPtr intPtr3 = CryptFindOIDInfo(keyType, intPtr, group); if (intPtr3 != IntPtr.Zero) { return Marshal.PtrToStructure(intPtr3); } if (fallBackToAllGroups && group != 0) { IntPtr intPtr4 = CryptFindOIDInfo(keyType, intPtr, OidGroup.All); if (intPtr4 != IntPtr.Zero) { return Marshal.PtrToStructure(intPtr4); } } CRYPT_OID_INFO result = default(CRYPT_OID_INFO); result.AlgId = -1; return result; } finally { if (intPtr != IntPtr.Zero) { Marshal.FreeCoTaskMem(intPtr); } } } private static bool OidGroupWillNotUseActiveDirectory(OidGroup group) { if (group != OidGroup.HashAlgorithm && group != OidGroup.EncryptionAlgorithm && group != OidGroup.PublicKeyAlgorithm && group != OidGroup.SignatureAlgorithm && group != OidGroup.Attribute && group != OidGroup.ExtensionOrAttribute) { return group == OidGroup.KeyDerivationFunction; } return true; } [DllImport("crypt32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr CryptFindOIDInfo(CryptOidInfoKeyType dwKeyType, IntPtr pvKey, OidGroup group); [DllImport("crypt32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr CryptFindOIDInfo(CryptOidInfoKeyType dwKeyType, ref int pvKey, OidGroup group); public static CRYPT_OID_INFO FindAlgIdOidInfo(BCrypt.ECC_CURVE_ALG_ID_ENUM algId) { int pvKey = (int)algId; IntPtr intPtr = CryptFindOIDInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_ALGID_KEY, ref pvKey, OidGroup.HashAlgorithm); if (intPtr != IntPtr.Zero) { return Marshal.PtrToStructure(intPtr); } CRYPT_OID_INFO result = default(CRYPT_OID_INFO); result.AlgId = -1; return result; } } internal static class NCrypt { internal enum AsymmetricPaddingMode { None = 0, NCRYPT_NO_PADDING_FLAG = 1, NCRYPT_PAD_PKCS1_FLAG = 2, NCRYPT_PAD_OAEP_FLAG = 4, NCRYPT_PAD_PSS_FLAG = 8 } internal enum ErrorCode { ERROR_SUCCESS = 0, NTE_BAD_SIGNATURE = -2146893818, NTE_NOT_FOUND = -2146893807, NTE_BAD_KEYSET = -2146893802, NTE_INVALID_PARAMETER = -2146893785, NTE_BUFFER_TOO_SMALL = -2146893784, NTE_NOT_SUPPORTED = -2146893783, NTE_NO_MORE_ITEMS = -2146893782, E_FAIL = -2147467259, STATUS_UNSUCCESSFUL = -1073741823 } internal struct CRYPT_PKCS12_PBE_PARAMS { internal int iIterations; internal int cbSalt; } internal struct PBE_PARAMS { internal CRYPT_PKCS12_PBE_PARAMS Params; internal unsafe fixed byte rgbSalt[8]; } [Flags] internal enum SecretAgreementFlags { None = 0, UseSecretAsHmacKey = 1 } internal enum BufferType { KdfHashAlgorithm = 0, KdfSecretPrepend = 1, KdfSecretAppend = 2, KdfHmacKey = 3, KdfTlsLabel = 4, KdfTlsSeed = 5, PkcsAlgOid = 41, PkcsAlgParam = 42, PkcsSecret = 46 } internal struct NCryptBuffer { public int cbBuffer; public BufferType BufferType; public IntPtr pvBuffer; } internal struct NCryptBufferDesc { public int ulVersion; public int cBuffers; public IntPtr pBuffers; } internal struct NCRYPT_UI_POLICY { public int dwVersion; public CngUIProtectionLevels dwFlags; public IntPtr pszCreationTitle; public IntPtr pszFriendlyName; public IntPtr pszDescription; } internal unsafe static ErrorCode NCryptEncrypt(SafeNCryptKeyHandle hKey, ReadOnlySpan pbInput, int cbInput, void* pPaddingInfo, Span pbOutput, int cbOutput, out int pcbResult, AsymmetricPaddingMode dwFlags) { return NCryptEncrypt(hKey, ref MemoryMarshal.GetReference(pbInput), cbInput, pPaddingInfo, ref MemoryMarshal.GetReference(pbOutput), cbOutput, out pcbResult, dwFlags); } [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] private unsafe static extern ErrorCode NCryptEncrypt(SafeNCryptKeyHandle hKey, ref byte pbInput, int cbInput, void* pPaddingInfo, ref byte pbOutput, int cbOutput, out int pcbResult, AsymmetricPaddingMode dwFlags); internal unsafe static ErrorCode NCryptDecrypt(SafeNCryptKeyHandle hKey, ReadOnlySpan pbInput, int cbInput, void* pPaddingInfo, Span pbOutput, int cbOutput, out int pcbResult, AsymmetricPaddingMode dwFlags) { return NCryptDecrypt(hKey, ref MemoryMarshal.GetReference(pbInput), cbInput, pPaddingInfo, ref MemoryMarshal.GetReference(pbOutput), cbOutput, out pcbResult, dwFlags); } [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] private unsafe static extern ErrorCode NCryptDecrypt(SafeNCryptKeyHandle hKey, ref byte pbInput, int cbInput, void* pPaddingInfo, ref byte pbOutput, int cbOutput, out int pcbResult, AsymmetricPaddingMode dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern ErrorCode NCryptOpenKey(SafeNCryptProviderHandle hProvider, out SafeNCryptKeyHandle phKey, string pszKeyName, int dwLegacyKeySpec, CngKeyOpenOptions dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern ErrorCode NCryptImportKey(SafeNCryptProviderHandle hProvider, IntPtr hImportKey, string pszBlobType, IntPtr pParameterList, out SafeNCryptKeyHandle phKey, ref byte pbData, int cbData, int dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern ErrorCode NCryptImportKey(SafeNCryptProviderHandle hProvider, IntPtr hImportKey, string pszBlobType, ref NCryptBufferDesc pParameterList, out SafeNCryptKeyHandle phKey, ref byte pbData, int cbData, int dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern ErrorCode NCryptExportKey(SafeNCryptKeyHandle hKey, IntPtr hExportKey, string pszBlobType, IntPtr pParameterList, [Out] byte[] pbOutput, int cbOutput, out int pcbResult, int dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern ErrorCode NCryptExportKey(SafeNCryptKeyHandle hKey, IntPtr hExportKey, string pszBlobType, IntPtr pParameterList, ref byte pbOutput, int cbOutput, out int pcbResult, int dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern ErrorCode NCryptExportKey(SafeNCryptKeyHandle hKey, IntPtr hExportKey, string pszBlobType, ref NCryptBufferDesc pParameterList, ref byte pbOutput, int cbOutput, out int pcbResult, int dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern ErrorCode NCryptDeleteKey(SafeNCryptKeyHandle hKey, int dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern ErrorCode NCryptCreatePersistedKey(SafeNCryptProviderHandle hProvider, out SafeNCryptKeyHandle phKey, string pszAlgId, string pszKeyName, int dwLegacyKeySpec, CngKeyCreationOptions dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern ErrorCode NCryptFinalizeKey(SafeNCryptKeyHandle hKey, int dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern ErrorCode NCryptFreeObject(IntPtr hObject); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern ErrorCode NCryptOpenStorageProvider(out SafeNCryptProviderHandle phProvider, string pszProviderName, int dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] private static extern ErrorCode NCryptDeriveKey(SafeNCryptSecretHandle hSharedSecret, string pwszKDF, [In] ref NCryptBufferDesc pParameterList, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] pbDerivedKey, int cbDerivedKey, out int pcbResult, SecretAgreementFlags dwFlags); private unsafe static byte[] DeriveKeyMaterial(SafeNCryptSecretHandle secretAgreement, string kdf, string hashAlgorithm, byte[] hmacKey, byte[] secretPrepend, byte[] secretAppend, SecretAgreementFlags flags) { IntPtr intPtr = IntPtr.Zero; try { intPtr = Marshal.StringToCoTaskMemUni(hashAlgorithm); Span span = stackalloc NCryptBuffer[4]; int num = 0; NCryptBuffer nCryptBuffer = default(NCryptBuffer); nCryptBuffer.cbBuffer = (hashAlgorithm.Length + 1) * 2; nCryptBuffer.BufferType = BufferType.KdfHashAlgorithm; nCryptBuffer.pvBuffer = intPtr; span[num] = nCryptBuffer; num++; fixed (byte* ptr = hmacKey) { fixed (byte* ptr2 = secretPrepend) { fixed (byte* ptr3 = secretAppend) { if (ptr != null) { NCryptBuffer nCryptBuffer2 = default(NCryptBuffer); nCryptBuffer2.cbBuffer = hmacKey.Length; nCryptBuffer2.BufferType = BufferType.KdfHmacKey; nCryptBuffer2.pvBuffer = new IntPtr(ptr); span[num] = nCryptBuffer2; num++; } if (ptr2 != null) { NCryptBuffer nCryptBuffer3 = default(NCryptBuffer); nCryptBuffer3.cbBuffer = secretPrepend.Length; nCryptBuffer3.BufferType = BufferType.KdfSecretPrepend; nCryptBuffer3.pvBuffer = new IntPtr(ptr2); span[num] = nCryptBuffer3; num++; } if (ptr3 != null) { NCryptBuffer nCryptBuffer4 = default(NCryptBuffer); nCryptBuffer4.cbBuffer = secretAppend.Length; nCryptBuffer4.BufferType = BufferType.KdfSecretAppend; nCryptBuffer4.pvBuffer = new IntPtr(ptr3); span[num] = nCryptBuffer4; num++; } return DeriveKeyMaterial(secretAgreement, kdf, span.Slice(0, num), flags); } } } } finally { if (intPtr != IntPtr.Zero) { Marshal.FreeCoTaskMem(intPtr); } } } private unsafe static byte[] DeriveKeyMaterial(SafeNCryptSecretHandle secretAgreement, string kdf, ReadOnlySpan parameters, SecretAgreementFlags flags) { fixed (NCryptBuffer* value = &MemoryMarshal.GetReference(parameters)) { NCryptBufferDesc pParameterList = default(NCryptBufferDesc); pParameterList.ulVersion = 0; pParameterList.cBuffers = parameters.Length; pParameterList.pBuffers = new IntPtr(value); ErrorCode errorCode = NCryptDeriveKey(secretAgreement, kdf, ref pParameterList, null, 0, out var pcbResult, flags); if (errorCode != 0 && errorCode != ErrorCode.NTE_BUFFER_TOO_SMALL) { throw errorCode.ToCryptographicException(); } byte[] array = new byte[pcbResult]; errorCode = NCryptDeriveKey(secretAgreement, kdf, ref pParameterList, array, array.Length, out pcbResult, flags); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } Array.Resize(ref array, Math.Min(pcbResult, array.Length)); return array; } } internal static byte[] DeriveKeyMaterialHash(SafeNCryptSecretHandle secretAgreement, string hashAlgorithm, byte[] secretPrepend, byte[] secretAppend, SecretAgreementFlags flags) { return DeriveKeyMaterial(secretAgreement, "HASH", hashAlgorithm, null, secretPrepend, secretAppend, flags); } internal static byte[] DeriveKeyMaterialHmac(SafeNCryptSecretHandle secretAgreement, string hashAlgorithm, byte[] hmacKey, byte[] secretPrepend, byte[] secretAppend, SecretAgreementFlags flags) { return DeriveKeyMaterial(secretAgreement, "HMAC", hashAlgorithm, hmacKey, secretPrepend, secretAppend, flags); } internal unsafe static byte[] DeriveKeyMaterialTls(SafeNCryptSecretHandle secretAgreement, byte[] label, byte[] seed, SecretAgreementFlags flags) { Span span = stackalloc NCryptBuffer[2]; fixed (byte* value = label) { fixed (byte* value2 = seed) { NCryptBuffer nCryptBuffer = default(NCryptBuffer); nCryptBuffer.cbBuffer = label.Length; nCryptBuffer.BufferType = BufferType.KdfTlsLabel; nCryptBuffer.pvBuffer = new IntPtr(value); span[0] = nCryptBuffer; NCryptBuffer nCryptBuffer2 = default(NCryptBuffer); nCryptBuffer2.cbBuffer = seed.Length; nCryptBuffer2.BufferType = BufferType.KdfTlsSeed; nCryptBuffer2.pvBuffer = new IntPtr(value2); span[1] = nCryptBuffer2; return DeriveKeyMaterial(secretAgreement, "TLS_PRF", span, flags); } } } [DllImport("ncrypt.dll")] private static extern ErrorCode NCryptSecretAgreement(SafeNCryptKeyHandle hPrivKey, SafeNCryptKeyHandle hPubKey, out SafeNCryptSecretHandle phSecret, int dwFlags); internal static SafeNCryptSecretHandle DeriveSecretAgreement(SafeNCryptKeyHandle privateKey, SafeNCryptKeyHandle otherPartyPublicKey) { SafeNCryptSecretHandle phSecret; ErrorCode errorCode = NCryptSecretAgreement(privateKey, otherPartyPublicKey, out phSecret, 0); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } return phSecret; } [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal unsafe static extern ErrorCode NCryptGetProperty(SafeNCryptHandle hObject, string pszProperty, [Out] void* pbOutput, int cbOutput, out int pcbResult, CngPropertyOptions dwFlags); [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal unsafe static extern ErrorCode NCryptSetProperty(SafeNCryptHandle hObject, string pszProperty, [In] void* pbInput, int cbInput, CngPropertyOptions dwFlags); internal unsafe static ErrorCode NCryptGetIntProperty(SafeNCryptHandle hObject, string pszProperty, ref int result) { fixed (int* pbOutput = &result) { int pcbResult; return NCryptGetProperty(hObject, pszProperty, pbOutput, 4, out pcbResult, CngPropertyOptions.None); } } internal unsafe static ErrorCode NCryptSignHash(SafeNCryptKeyHandle hKey, void* pPaddingInfo, ReadOnlySpan pbHashValue, int cbHashValue, Span pbSignature, int cbSignature, out int pcbResult, AsymmetricPaddingMode dwFlags) { return NCryptSignHash(hKey, pPaddingInfo, ref MemoryMarshal.GetReference(pbHashValue), cbHashValue, ref MemoryMarshal.GetReference(pbSignature), cbSignature, out pcbResult, dwFlags); } [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] private unsafe static extern ErrorCode NCryptSignHash(SafeNCryptKeyHandle hKey, void* pPaddingInfo, ref byte pbHashValue, int cbHashValue, ref byte pbSignature, int cbSignature, out int pcbResult, AsymmetricPaddingMode dwFlags); internal unsafe static ErrorCode NCryptVerifySignature(SafeNCryptKeyHandle hKey, void* pPaddingInfo, ReadOnlySpan pbHashValue, int cbHashValue, ReadOnlySpan pbSignature, int cbSignature, AsymmetricPaddingMode dwFlags) { return NCryptVerifySignature(hKey, pPaddingInfo, ref MemoryMarshal.GetReference(pbHashValue), cbHashValue, ref MemoryMarshal.GetReference(pbSignature), cbSignature, dwFlags); } [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] private unsafe static extern ErrorCode NCryptVerifySignature(SafeNCryptKeyHandle hKey, void* pPaddingInfo, ref byte pbHashValue, int cbHashValue, ref byte pbSignature, int cbSignature, AsymmetricPaddingMode dwFlags); } internal static class Kernel32 { [DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Unicode, EntryPoint = "FormatMessageW", ExactSpelling = true, SetLastError = true)] private unsafe static extern int FormatMessage(int dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, void* lpBuffer, int nSize, IntPtr arguments); internal static string GetMessage(int errorCode) { return GetMessage(errorCode, IntPtr.Zero); } internal unsafe static string GetMessage(int errorCode, IntPtr moduleHandle) { int num = 12800; if (moduleHandle != IntPtr.Zero) { num |= 0x800; } Span span = stackalloc char[256]; fixed (char* lpBuffer = span) { int num2 = FormatMessage(num, moduleHandle, (uint)errorCode, 0, lpBuffer, span.Length, IntPtr.Zero); if (num2 > 0) { return GetAndTrimString(span.Slice(0, num2)); } } if (Marshal.GetLastWin32Error() == 122) { IntPtr intPtr = default(IntPtr); try { int num3 = FormatMessage(num | 0x100, moduleHandle, (uint)errorCode, 0, &intPtr, 0, IntPtr.Zero); if (num3 > 0) { return GetAndTrimString(new Span((void*)intPtr, num3)); } } finally { Marshal.FreeHGlobal(intPtr); } } return $"Unknown error (0x{errorCode:x})"; } private static string GetAndTrimString(Span buffer) { int num = buffer.Length; while (num > 0 && buffer[num - 1] <= ' ') { num--; } return buffer.Slice(0, num).ToString(); } } } namespace FxResources.System.Security.Cryptography.Cng { internal static class SR { } } namespace Internal.NativeCrypto { internal static class Cng { [Flags] public enum OpenAlgorithmProviderFlags { NONE = 0, BCRYPT_ALG_HANDLE_HMAC_FLAG = 8 } internal static class Interop { [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)] public static extern global::Interop.BCrypt.NTSTATUS BCryptOpenAlgorithmProvider(out SafeAlgorithmHandle phAlgorithm, string pszAlgId, string pszImplementation, int dwFlags); [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)] public static extern global::Interop.BCrypt.NTSTATUS BCryptSetProperty(SafeAlgorithmHandle hObject, string pszProperty, string pbInput, int cbInput, int dwFlags); [DllImport("BCrypt.dll", CharSet = CharSet.Unicode, EntryPoint = "BCryptSetProperty")] private static extern global::Interop.BCrypt.NTSTATUS BCryptSetIntPropertyPrivate(SafeBCryptHandle hObject, string pszProperty, ref int pdwInput, int cbInput, int dwFlags); public static global::Interop.BCrypt.NTSTATUS BCryptSetIntProperty(SafeBCryptHandle hObject, string pszProperty, ref int pdwInput, int dwFlags) { return BCryptSetIntPropertyPrivate(hObject, pszProperty, ref pdwInput, 4, dwFlags); } } public static SafeAlgorithmHandle BCryptOpenAlgorithmProvider(string pszAlgId, string pszImplementation, OpenAlgorithmProviderFlags dwFlags) { SafeAlgorithmHandle phAlgorithm; global::Interop.BCrypt.NTSTATUS nTSTATUS = Interop.BCryptOpenAlgorithmProvider(out phAlgorithm, pszAlgId, pszImplementation, (int)dwFlags); if (nTSTATUS != 0) { throw CreateCryptographicException(nTSTATUS); } return phAlgorithm; } public static void SetFeedbackSize(this SafeAlgorithmHandle hAlg, int dwFeedbackSize) { global::Interop.BCrypt.NTSTATUS nTSTATUS = Interop.BCryptSetIntProperty(hAlg, "MessageBlockLength", ref dwFeedbackSize, 0); if (nTSTATUS != 0) { throw CreateCryptographicException(nTSTATUS); } } public static void SetCipherMode(this SafeAlgorithmHandle hAlg, string cipherMode) { global::Interop.BCrypt.NTSTATUS nTSTATUS = Interop.BCryptSetProperty(hAlg, "ChainingMode", cipherMode, (cipherMode.Length + 1) * 2, 0); if (nTSTATUS != 0) { throw CreateCryptographicException(nTSTATUS); } } private static Exception CreateCryptographicException(global::Interop.BCrypt.NTSTATUS ntStatus) { int hr = (int)(ntStatus | (global::Interop.BCrypt.NTSTATUS)16777216u); return hr.ToCryptographicException(); } } internal sealed class SafeAlgorithmHandle : SafeBCryptHandle { protected sealed override bool ReleaseHandle() { uint num = BCryptCloseAlgorithmProvider(handle, 0); return num == 0; } [DllImport("BCrypt.dll")] private static extern uint BCryptCloseAlgorithmProvider(IntPtr hAlgorithm, int dwFlags); } internal sealed class SafeKeyHandle : SafeBCryptHandle { private SafeAlgorithmHandle _parentHandle; public void SetParentHandle(SafeAlgorithmHandle parentHandle) { bool success = false; parentHandle.DangerousAddRef(ref success); _parentHandle = parentHandle; } protected sealed override bool ReleaseHandle() { if (_parentHandle != null) { _parentHandle.DangerousRelease(); _parentHandle = null; } uint num = BCryptDestroyKey(handle); return num == 0; } [DllImport("BCrypt.dll")] private static extern uint BCryptDestroyKey(IntPtr hKey); } } namespace Internal.Cryptography { internal sealed class BasicSymmetricCipherNCrypt : Internal.Cryptography.BasicSymmetricCipher { private CngKey _cngKey; private readonly bool _encrypting; private static readonly CngProperty s_ECBMode = new CngProperty("Chaining Mode", Encoding.Unicode.GetBytes("ChainingModeECB\0"), CngPropertyOptions.None); private static readonly CngProperty s_CBCMode = new CngProperty("Chaining Mode", Encoding.Unicode.GetBytes("ChainingModeCBC\0"), CngPropertyOptions.None); private static readonly CngProperty s_CFBMode = new CngProperty("Chaining Mode", Encoding.Unicode.GetBytes("ChainingModeCFB\0"), CngPropertyOptions.None); public BasicSymmetricCipherNCrypt(Func cngKeyFactory, CipherMode cipherMode, int blockSizeInBytes, byte[] iv, bool encrypting, int paddingSize) : base(iv, blockSizeInBytes, paddingSize) { _encrypting = encrypting; _cngKey = cngKeyFactory(); CngProperty property = cipherMode switch { CipherMode.ECB => s_ECBMode, CipherMode.CBC => s_CBCMode, CipherMode.CFB => s_CFBMode, _ => throw new CryptographicException(System.SR.Cryptography_InvalidCipherMode), }; _cngKey.SetProperty(property); Reset(); } public unsafe sealed override int Transform(ReadOnlySpan input, Span output) { global::Interop.NCrypt.ErrorCode errorCode; int pcbResult; using (SafeNCryptKeyHandle hKey = _cngKey.Handle) { errorCode = (_encrypting ? global::Interop.NCrypt.NCryptEncrypt(hKey, input, input.Length, null, output, output.Length, out pcbResult, global::Interop.NCrypt.AsymmetricPaddingMode.None) : global::Interop.NCrypt.NCryptDecrypt(hKey, input, input.Length, null, output, output.Length, out pcbResult, global::Interop.NCrypt.AsymmetricPaddingMode.None)); } if (errorCode != 0) { throw errorCode.ToCryptographicException(); } if (pcbResult != input.Length) { throw new CryptographicException(System.SR.Cryptography_UnexpectedTransformTruncation); } return pcbResult; } public sealed override int TransformFinal(ReadOnlySpan input, Span output) { int result = 0; if (input.Length != 0) { result = Transform(input, output); } Reset(); return result; } protected sealed override void Dispose(bool disposing) { if (disposing && _cngKey != null) { _cngKey.Dispose(); _cngKey = null; } base.Dispose(disposing); } private void Reset() { if (base.IV != null) { CngProperty property = new CngProperty("IV", base.IV, CngPropertyOptions.None); _cngKey.SetProperty(property); } } } internal struct CngAlgorithmCore { private readonly string _disposedName; public CngAlgorithm DefaultKeyType; private CngKey _lazyKey; private bool _disposed; public CngAlgorithmCore(string disposedName) { this = default(CngAlgorithmCore); _disposedName = disposedName; } public static CngKey Duplicate(CngKey key) { using SafeNCryptKeyHandle keyHandle = key.Handle; return CngKey.Open(keyHandle, key.IsEphemeral ? CngKeyHandleOpenOptions.EphemeralKey : CngKeyHandleOpenOptions.None); } public bool IsKeyGeneratedNamedCurve() { ThrowIfDisposed(); if (_lazyKey != null) { return _lazyKey.IsECNamedCurve(); } return false; } public void DisposeKey() { if (_lazyKey != null) { _lazyKey.Dispose(); _lazyKey = null; } } public CngKey GetOrGenerateKey(int keySize, CngAlgorithm algorithm) { ThrowIfDisposed(); if (_lazyKey != null && _lazyKey.KeySize != keySize) { DisposeKey(); } if (_lazyKey == null) { CngKeyCreationParameters cngKeyCreationParameters = new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport }; CngProperty item = new CngProperty("Length", BitConverter.GetBytes(keySize), CngPropertyOptions.None); cngKeyCreationParameters.Parameters.Add(item); _lazyKey = CngKey.Create(algorithm, null, cngKeyCreationParameters); } return _lazyKey; } public CngKey GetOrGenerateKey(ECCurve? curve) { ThrowIfDisposed(); if (_lazyKey != null) { return _lazyKey; } CngKeyCreationParameters cngKeyCreationParameters = new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport }; if (curve.Value.IsNamed) { cngKeyCreationParameters.Parameters.Add(CngKey.GetPropertyFromNamedCurve(curve.Value)); } else { if (!curve.Value.IsPrime) { throw new PlatformNotSupportedException(System.SR.Format(System.SR.Cryptography_CurveNotSupported, curve.Value.CurveType.ToString())); } ECCurve curve2 = curve.Value; byte[] primeCurveParameterBlob = ECCng.GetPrimeCurveParameterBlob(ref curve2); CngProperty item = new CngProperty("ECCParameters", primeCurveParameterBlob, CngPropertyOptions.None); cngKeyCreationParameters.Parameters.Add(item); } try { _lazyKey = CngKey.Create(DefaultKeyType ?? CngAlgorithm.ECDsa, null, cngKeyCreationParameters); } catch (CryptographicException ex) { global::Interop.NCrypt.ErrorCode hResult = (global::Interop.NCrypt.ErrorCode)ex.HResult; if ((curve.Value.IsNamed && hResult == global::Interop.NCrypt.ErrorCode.NTE_INVALID_PARAMETER) || hResult == global::Interop.NCrypt.ErrorCode.NTE_NOT_SUPPORTED) { throw new PlatformNotSupportedException(System.SR.Format(System.SR.Cryptography_CurveNotSupported, curve.Value.Oid.FriendlyName), ex); } throw; } return _lazyKey; } public void SetKey(CngKey key) { ThrowIfDisposed(); DisposeKey(); _lazyKey = key; } public void Dispose() { DisposeKey(); _disposed = true; } internal void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(_disposedName); } } } internal static class Helpers { [UnsupportedOSPlatformGuard("android")] public static bool IsRC2Supported => !OperatingSystem.IsAndroid(); public static bool UsesIv(this CipherMode cipherMode) { return cipherMode != CipherMode.ECB; } public static byte[] GetCipherIv(this CipherMode cipherMode, byte[] iv) { if (cipherMode.UsesIv()) { if (iv == null) { throw new CryptographicException(System.SR.Cryptography_MissingIV); } return iv; } return null; } public static byte[] MapZeroLengthArrayToNonNullPointer(this byte[] src) { if (src != null && src.Length == 0) { return new byte[1]; } return src; } public static SafeNCryptProviderHandle OpenStorageProvider(this CngProvider provider) { string provider2 = provider.Provider; SafeNCryptProviderHandle phProvider; global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptOpenStorageProvider(out phProvider, provider2, 0); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } return phProvider; } public unsafe static byte[] GetProperty(this SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options) { global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptGetProperty(ncryptHandle, propertyName, null, 0, out var pcbResult, options); switch (errorCode) { case global::Interop.NCrypt.ErrorCode.NTE_NOT_FOUND: return null; default: throw errorCode.ToCryptographicException(); case global::Interop.NCrypt.ErrorCode.ERROR_SUCCESS: { byte[] array = new byte[pcbResult]; fixed (byte* pbOutput = array) { errorCode = global::Interop.NCrypt.NCryptGetProperty(ncryptHandle, propertyName, pbOutput, array.Length, out pcbResult, options); } switch (errorCode) { case global::Interop.NCrypt.ErrorCode.NTE_NOT_FOUND: return null; default: throw errorCode.ToCryptographicException(); case global::Interop.NCrypt.ErrorCode.ERROR_SUCCESS: Array.Resize(ref array, pcbResult); return array; } } } } public unsafe static string GetPropertyAsString(this SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options) { byte[] property = ncryptHandle.GetProperty(propertyName, options); if (property == null) { return null; } if (property.Length == 0) { return string.Empty; } fixed (byte* ptr = &property[0]) { return Marshal.PtrToStringUni((IntPtr)ptr); } } public static int GetPropertyAsDword(this SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options) { byte[] property = ncryptHandle.GetProperty(propertyName, options); if (property == null) { return 0; } return BitConverter.ToInt32(property, 0); } public unsafe static IntPtr GetPropertyAsIntPtr(this SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options) { Unsafe.SkipInit(out IntPtr intPtr); int pcbResult; global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptGetProperty(ncryptHandle, propertyName, &intPtr, IntPtr.Size, out pcbResult, options); return errorCode switch { global::Interop.NCrypt.ErrorCode.NTE_NOT_FOUND => IntPtr.Zero, global::Interop.NCrypt.ErrorCode.ERROR_SUCCESS => intPtr, _ => throw errorCode.ToCryptographicException(), }; } public unsafe static void SetExportPolicy(this SafeNCryptKeyHandle keyHandle, CngExportPolicies exportPolicy) { global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptSetProperty(keyHandle, "Export Policy", &exportPolicy, 4, CngPropertyOptions.Persist); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } } public static int BitSizeToByteSize(this int bits) { return (bits + 7) / 8; } public static byte[] GenerateRandom(int count) { byte[] array = new byte[count]; RandomNumberGenerator.Fill(array); return array; } [return: NotNullIfNotNull("src")] public static byte[] CloneByteArray(this byte[] src) { if (src == null) { return null; } return (byte[])src.Clone(); } public static int GetPaddingSize(this SymmetricAlgorithm algorithm, CipherMode mode, int feedbackSizeInBits) { return ((mode == CipherMode.CFB) ? feedbackSizeInBits : algorithm.BlockSize) / 8; } } internal interface ICngSymmetricAlgorithm { int BlockSize { get; } int FeedbackSize { get; } CipherMode Mode { get; } PaddingMode Padding { get; } byte[] IV { get; set; } KeySizes[] LegalKeySizes { get; } byte[] BaseKey { get; set; } int BaseKeySize { get; set; } bool IsWeakKey(byte[] key); SafeAlgorithmHandle GetEphemeralModeHandle(CipherMode mode, int feedbackSizeInBits); string GetNCryptAlgorithmIdentifier(); byte[] PreprocessKey(byte[] key); int GetPaddingSize(CipherMode mode, int feedbackSizeBits); bool IsValidEphemeralFeedbackSize(int feedbackSizeInBits); } internal static class SymmetricImportExportExtensions { private static readonly CngKeyBlobFormat s_cipherKeyBlobFormat = new CngKeyBlobFormat("CipherKeyBlob"); public static byte[] GetSymmetricKeyDataIfExportable(this CngKey cngKey, string algorithm) { byte[] buffer = cngKey.Export(s_cipherKeyBlobFormat); using MemoryStream input = new MemoryStream(buffer); using BinaryReader binaryReader = new BinaryReader(input, Encoding.Unicode); int num = binaryReader.ReadInt32(); if (num != 16) { throw new CryptographicException(System.SR.Cryptography_KeyBlobParsingError); } int num2 = binaryReader.ReadInt32(); if (num2 != 1380470851) { throw new CryptographicException(System.SR.Cryptography_KeyBlobParsingError); } int num3 = binaryReader.ReadInt32(); binaryReader.ReadInt32(); string text = new string(binaryReader.ReadChars(num3 / 2 - 1)); if (text != algorithm) { throw new CryptographicException(System.SR.Format(System.SR.Cryptography_CngKeyWrongAlgorithm, text, algorithm)); } if (binaryReader.ReadChar() != 0) { throw new CryptographicException(System.SR.Cryptography_KeyBlobParsingError); } int num4 = binaryReader.ReadInt32(); if (num4 != 1296188491) { throw new CryptographicException(System.SR.Cryptography_KeyBlobParsingError); } int num5 = binaryReader.ReadInt32(); if (num5 != 1) { throw new CryptographicException(System.SR.Cryptography_KeyBlobParsingError); } int count = binaryReader.ReadInt32(); return binaryReader.ReadBytes(count); } } internal struct CngSymmetricAlgorithmCore { private readonly ICngSymmetricAlgorithm _outer; private string _keyName; private readonly CngProvider _provider; private readonly CngKeyOpenOptions _optionOptions; private bool KeyInPlainText => _keyName == null; public CngSymmetricAlgorithmCore(ICngSymmetricAlgorithm outer) { _outer = outer; _keyName = null; _provider = null; _optionOptions = CngKeyOpenOptions.None; } public CngSymmetricAlgorithmCore(ICngSymmetricAlgorithm outer, string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { if (keyName == null) { throw new ArgumentNullException("keyName"); } if (provider == null) { throw new ArgumentNullException("provider"); } _outer = outer; _keyName = keyName; _provider = provider; _optionOptions = openOptions; using CngKey cngKey = ProduceCngKey(); CngAlgorithm algorithm = cngKey.Algorithm; string nCryptAlgorithmIdentifier = _outer.GetNCryptAlgorithmIdentifier(); if (nCryptAlgorithmIdentifier != algorithm.Algorithm) { throw new CryptographicException(System.SR.Format(System.SR.Cryptography_CngKeyWrongAlgorithm, algorithm.Algorithm, nCryptAlgorithmIdentifier)); } _outer.BaseKeySize = cngKey.KeySize; } public byte[] GetKeyIfExportable() { if (KeyInPlainText) { return _outer.BaseKey; } using CngKey cngKey = ProduceCngKey(); return cngKey.GetSymmetricKeyDataIfExportable(_outer.GetNCryptAlgorithmIdentifier()); } public void SetKey(byte[] key) { _outer.BaseKey = key; _keyName = null; } public void SetKeySize(int keySize, ICngSymmetricAlgorithm outer) { outer.BaseKeySize = keySize; _keyName = null; } public void GenerateKey() { byte[] key = Internal.Cryptography.Helpers.GenerateRandom(_outer.BaseKeySize.BitSizeToByteSize()); SetKey(key); } public void GenerateIV() { byte[] iV = Internal.Cryptography.Helpers.GenerateRandom(_outer.BlockSize.BitSizeToByteSize()); _outer.IV = iV; } public ICryptoTransform CreateEncryptor() { return CreateCryptoTransform(encrypting: true); } public ICryptoTransform CreateDecryptor() { return CreateCryptoTransform(encrypting: false); } public ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { return CreateCryptoTransform(rgbKey, rgbIV, encrypting: true, _outer.Padding, _outer.Mode, _outer.FeedbackSize); } public ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { return CreateCryptoTransform(rgbKey, rgbIV, encrypting: false, _outer.Padding, _outer.Mode, _outer.FeedbackSize); } private ICryptoTransform CreateCryptoTransform(bool encrypting) { if (KeyInPlainText) { return CreateCryptoTransform(_outer.BaseKey, _outer.IV, encrypting, _outer.Padding, _outer.Mode, _outer.FeedbackSize); } return CreatePersistedCryptoTransformCore(ProduceCngKey, _outer.IV, encrypting, _outer.Padding, _outer.Mode, _outer.FeedbackSize); } public Internal.Cryptography.UniversalCryptoTransform CreateCryptoTransform(byte[] iv, bool encrypting, PaddingMode padding, CipherMode mode, int feedbackSizeInBits) { if (KeyInPlainText) { return CreateCryptoTransform(_outer.BaseKey, iv, encrypting, padding, mode, feedbackSizeInBits); } return CreatePersistedCryptoTransformCore(ProduceCngKey, iv, encrypting, padding, mode, feedbackSizeInBits); } private Internal.Cryptography.UniversalCryptoTransform CreateCryptoTransform(byte[] rgbKey, byte[] rgbIV, bool encrypting, PaddingMode padding, CipherMode mode, int feedbackSizeInBits) { if (rgbKey == null) { throw new ArgumentNullException("rgbKey"); } ValidateFeedbackSize(mode, feedbackSizeInBits); byte[] array = rgbKey.CloneByteArray(); long num = (long)array.Length * 8L; if (num > int.MaxValue || !((int)num).IsLegalSize(_outer.LegalKeySizes)) { throw new ArgumentException(System.SR.Cryptography_InvalidKeySize, "rgbKey"); } if (_outer.IsWeakKey(array)) { throw new CryptographicException(System.SR.Cryptography_WeakKey); } if (rgbIV != null && rgbIV.Length != _outer.BlockSize.BitSizeToByteSize()) { throw new ArgumentException(System.SR.Cryptography_InvalidIVSize, "rgbIV"); } byte[] iv = mode.GetCipherIv(rgbIV).CloneByteArray(); array = _outer.PreprocessKey(array); return CreateEphemeralCryptoTransformCore(array, iv, encrypting, padding, mode, feedbackSizeInBits); } private Internal.Cryptography.UniversalCryptoTransform CreateEphemeralCryptoTransformCore(byte[] key, byte[] iv, bool encrypting, PaddingMode padding, CipherMode mode, int feedbackSizeInBits) { int blockSizeInBytes = _outer.BlockSize.BitSizeToByteSize(); SafeAlgorithmHandle ephemeralModeHandle = _outer.GetEphemeralModeHandle(mode, feedbackSizeInBits); Internal.Cryptography.BasicSymmetricCipher cipher = new BasicSymmetricCipherBCrypt(ephemeralModeHandle, mode, blockSizeInBytes, _outer.GetPaddingSize(mode, feedbackSizeInBits), key, ownsParentHandle: false, iv, encrypting); return Internal.Cryptography.UniversalCryptoTransform.Create(padding, cipher, encrypting); } private Internal.Cryptography.UniversalCryptoTransform CreatePersistedCryptoTransformCore(Func cngKeyFactory, byte[] iv, bool encrypting, PaddingMode padding, CipherMode mode, int feedbackSizeInBits) { ValidateFeedbackSize(mode, feedbackSizeInBits); int blockSizeInBytes = _outer.BlockSize.BitSizeToByteSize(); Internal.Cryptography.BasicSymmetricCipher cipher = new BasicSymmetricCipherNCrypt(cngKeyFactory, mode, blockSizeInBytes, iv, encrypting, _outer.GetPaddingSize(mode, feedbackSizeInBits)); return Internal.Cryptography.UniversalCryptoTransform.Create(padding, cipher, encrypting); } private CngKey ProduceCngKey() { return CngKey.Open(_keyName, _provider, _optionOptions); } private void ValidateFeedbackSize(CipherMode mode, int feedbackSizeInBits) { if (mode != CipherMode.CFB) { return; } if (KeyInPlainText) { if (!_outer.IsValidEphemeralFeedbackSize(feedbackSizeInBits)) { throw new CryptographicException(string.Format(System.SR.Cryptography_CipherModeFeedbackNotSupported, feedbackSizeInBits, CipherMode.CFB)); } } else if (feedbackSizeInBits != 8) { throw new CryptographicException(string.Format(System.SR.Cryptography_CipherModeFeedbackNotSupported, feedbackSizeInBits, CipherMode.CFB)); } } } internal static class AesBCryptModes { private static readonly Lazy s_hAlgCbc = OpenAesAlgorithm("ChainingModeCBC"); private static readonly Lazy s_hAlgEcb = OpenAesAlgorithm("ChainingModeECB"); private static readonly Lazy s_hAlgCfb128 = OpenAesAlgorithm("ChainingModeCFB", 16); private static readonly Lazy s_hAlgCfb8 = OpenAesAlgorithm("ChainingModeCFB", 1); internal static SafeAlgorithmHandle GetSharedHandle(CipherMode cipherMode, int feedback) { switch (cipherMode) { case CipherMode.CFB: switch (feedback) { case 16: return s_hAlgCfb128.Value; case 1: return s_hAlgCfb8.Value; } break; case CipherMode.CBC: return s_hAlgCbc.Value; case CipherMode.ECB: return s_hAlgEcb.Value; } throw new NotSupportedException(); } internal static Lazy OpenAesAlgorithm(string cipherMode, int feedback = 0) { return new Lazy(delegate { SafeAlgorithmHandle safeAlgorithmHandle = Cng.BCryptOpenAlgorithmProvider("AES", null, Cng.OpenAlgorithmProviderFlags.NONE); safeAlgorithmHandle.SetCipherMode(cipherMode); if (feedback > 0 && feedback != 1) { try { safeAlgorithmHandle.SetFeedbackSize(feedback); } catch (CryptographicException inner) { throw new CryptographicException(System.SR.Cryptography_FeedbackSizeNotSupported, inner); } } return safeAlgorithmHandle; }); } } internal static class TripleDesBCryptModes { private static readonly Lazy s_hAlgCbc = Open3DesAlgorithm("ChainingModeCBC"); private static readonly Lazy s_hAlgEcb = Open3DesAlgorithm("ChainingModeECB"); private static readonly Lazy s_hAlgCfb8 = Open3DesAlgorithm("ChainingModeCFB", 1); private static readonly Lazy s_hAlgCfb64 = Open3DesAlgorithm("ChainingModeCFB", 8); internal static SafeAlgorithmHandle GetSharedHandle(CipherMode cipherMode, int feedback) { switch (cipherMode) { case CipherMode.CFB: switch (feedback) { case 1: return s_hAlgCfb8.Value; case 8: return s_hAlgCfb64.Value; } break; case CipherMode.CBC: return s_hAlgCbc.Value; case CipherMode.ECB: return s_hAlgEcb.Value; } throw new NotSupportedException(); } private static Lazy Open3DesAlgorithm(string cipherMode, int feedback = 0) { return new Lazy(delegate { SafeAlgorithmHandle safeAlgorithmHandle = Cng.BCryptOpenAlgorithmProvider("3DES", null, Cng.OpenAlgorithmProviderFlags.NONE); safeAlgorithmHandle.SetCipherMode(cipherMode); if (feedback > 0 && feedback != 1) { try { safeAlgorithmHandle.SetFeedbackSize(feedback); } catch (CryptographicException inner) { throw new CryptographicException(System.SR.Cryptography_FeedbackSizeNotSupported, inner); } } return safeAlgorithmHandle; }); } } internal static class CryptoThrowHelper { private sealed class WindowsCryptographicException : CryptographicException { public WindowsCryptographicException(int hr, string message) : base(message) { base.HResult = hr; } } public static CryptographicException ToCryptographicException(this int hr) { string message = global::Interop.Kernel32.GetMessage(hr); if ((hr & 0x80000000u) != 2147483648u) { hr = (hr & 0xFFFF) | -2147024896; } return new WindowsCryptographicException(hr, message); } } internal static class ErrorCodeHelper { public static CryptographicException ToCryptographicException(this global::Interop.NCrypt.ErrorCode errorCode) { return ((int)errorCode).ToCryptographicException(); } } internal static class CngCommon { public static byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { using HashProviderCng hashProviderCng = new HashProviderCng(hashAlgorithm.Name, null); hashProviderCng.AppendHashData(data, offset, count); return hashProviderCng.FinalizeHashAndReset(); } public static bool TryHashData(ReadOnlySpan source, Span destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) { using HashProviderCng hashProviderCng = new HashProviderCng(hashAlgorithm.Name, null); if (destination.Length < hashProviderCng.HashSizeInBytes) { bytesWritten = 0; return false; } hashProviderCng.AppendHashData(source); return hashProviderCng.TryFinalizeHashAndReset(destination, out bytesWritten); } public static byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { using HashProviderCng hashProviderCng = new HashProviderCng(hashAlgorithm.Name, null); byte[] array = new byte[4096]; int count; while ((count = data.Read(array, 0, array.Length)) > 0) { hashProviderCng.AppendHashData(array, 0, count); } return hashProviderCng.FinalizeHashAndReset(); } public unsafe static byte[] SignHash(this SafeNCryptKeyHandle keyHandle, ReadOnlySpan hash, global::Interop.NCrypt.AsymmetricPaddingMode paddingMode, void* pPaddingInfo, int estimatedSize) { byte[] array = new byte[estimatedSize]; int pcbResult; global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptSignHash(keyHandle, pPaddingInfo, hash, hash.Length, array, array.Length, out pcbResult, paddingMode); if (errorCode == global::Interop.NCrypt.ErrorCode.STATUS_UNSUCCESSFUL) { errorCode = global::Interop.NCrypt.NCryptSignHash(keyHandle, pPaddingInfo, hash, hash.Length, array, array.Length, out pcbResult, paddingMode); } if (errorCode == global::Interop.NCrypt.ErrorCode.NTE_BUFFER_TOO_SMALL) { array = new byte[pcbResult]; errorCode = global::Interop.NCrypt.NCryptSignHash(keyHandle, pPaddingInfo, hash, hash.Length, array, array.Length, out pcbResult, paddingMode); } if (errorCode == global::Interop.NCrypt.ErrorCode.STATUS_UNSUCCESSFUL) { errorCode = global::Interop.NCrypt.NCryptSignHash(keyHandle, pPaddingInfo, hash, hash.Length, array, array.Length, out pcbResult, paddingMode); } if (errorCode != 0) { throw errorCode.ToCryptographicException(); } Array.Resize(ref array, pcbResult); return array; } public unsafe static bool TrySignHash(this SafeNCryptKeyHandle keyHandle, ReadOnlySpan hash, Span signature, global::Interop.NCrypt.AsymmetricPaddingMode paddingMode, void* pPaddingInfo, out int bytesWritten) { for (int i = 0; i <= 1; i++) { int pcbResult; global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptSignHash(keyHandle, pPaddingInfo, hash, hash.Length, signature, signature.Length, out pcbResult, paddingMode); switch (errorCode) { case global::Interop.NCrypt.ErrorCode.ERROR_SUCCESS: bytesWritten = pcbResult; return true; case global::Interop.NCrypt.ErrorCode.NTE_BUFFER_TOO_SMALL: bytesWritten = 0; return false; default: throw errorCode.ToCryptographicException(); case global::Interop.NCrypt.ErrorCode.STATUS_UNSUCCESSFUL: break; } } throw global::Interop.NCrypt.ErrorCode.STATUS_UNSUCCESSFUL.ToCryptographicException(); } public unsafe static bool VerifyHash(this SafeNCryptKeyHandle keyHandle, ReadOnlySpan hash, ReadOnlySpan signature, global::Interop.NCrypt.AsymmetricPaddingMode paddingMode, void* pPaddingInfo) { global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptVerifySignature(keyHandle, pPaddingInfo, hash, hash.Length, signature, signature.Length, paddingMode); if (errorCode == global::Interop.NCrypt.ErrorCode.STATUS_UNSUCCESSFUL) { errorCode = global::Interop.NCrypt.NCryptVerifySignature(keyHandle, pPaddingInfo, hash, hash.Length, signature, signature.Length, paddingMode); } return errorCode == global::Interop.NCrypt.ErrorCode.ERROR_SUCCESS; } } internal abstract class HashProvider : IDisposable { public abstract int HashSizeInBytes { get; } public void AppendHashData(byte[] data, int offset, int count) { if (data == null) { throw new ArgumentNullException("data", System.SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum); } if (data.Length - offset < count) { throw new ArgumentException(System.SR.Argument_InvalidOffLen); } AppendHashData(new ReadOnlySpan(data, offset, count)); } public abstract void AppendHashData(ReadOnlySpan data); public abstract int FinalizeHashAndReset(Span destination); public byte[] FinalizeHashAndReset() { byte[] array = new byte[HashSizeInBytes]; int num = FinalizeHashAndReset(array); return array; } public bool TryFinalizeHashAndReset(Span destination, out int bytesWritten) { if (destination.Length < HashSizeInBytes) { bytesWritten = 0; return false; } bytesWritten = FinalizeHashAndReset(destination); return true; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } public abstract void Dispose(bool disposing); public abstract void Reset(); } internal sealed class HashProviderCng : Internal.Cryptography.HashProvider { private readonly SafeBCryptAlgorithmHandle _hAlgorithm; private SafeBCryptHashHandle _hHash; private byte[] _key; private readonly bool _reusable; private readonly int _hashSize; private bool _running; public sealed override int HashSizeInBytes => _hashSize; public HashProviderCng(string hashAlgId, byte[] key) : this(hashAlgId, key, key != null) { } internal HashProviderCng(string hashAlgId, ReadOnlySpan key, bool isHmac) { global::Interop.BCrypt.BCryptOpenAlgorithmProviderFlags bCryptOpenAlgorithmProviderFlags = global::Interop.BCrypt.BCryptOpenAlgorithmProviderFlags.None; if (isHmac) { _key = key.ToArray(); bCryptOpenAlgorithmProviderFlags |= global::Interop.BCrypt.BCryptOpenAlgorithmProviderFlags.BCRYPT_ALG_HANDLE_HMAC_FLAG; } _hAlgorithm = global::Interop.BCrypt.BCryptAlgorithmCache.GetCachedBCryptAlgorithmHandle(hashAlgId, bCryptOpenAlgorithmProviderFlags, out _hashSize); SafeBCryptHashHandle phHash; global::Interop.BCrypt.NTSTATUS nTSTATUS = global::Interop.BCrypt.BCryptCreateHash(_hAlgorithm, out phHash, IntPtr.Zero, 0, key, (!(key == null)) ? key.Length : 0, global::Interop.BCrypt.BCryptCreateHashFlags.BCRYPT_HASH_REUSABLE_FLAG); switch (nTSTATUS) { case global::Interop.BCrypt.NTSTATUS.STATUS_INVALID_PARAMETER: phHash.Dispose(); Reset(); break; default: phHash.Dispose(); throw global::Interop.BCrypt.CreateCryptographicException(nTSTATUS); case global::Interop.BCrypt.NTSTATUS.STATUS_SUCCESS: _hHash = phHash; _reusable = true; break; } } public sealed override void AppendHashData(ReadOnlySpan source) { global::Interop.BCrypt.NTSTATUS nTSTATUS = global::Interop.BCrypt.BCryptHashData(_hHash, source, source.Length, 0); if (nTSTATUS != 0) { throw global::Interop.BCrypt.CreateCryptographicException(nTSTATUS); } _running = true; } public override int FinalizeHashAndReset(Span destination) { global::Interop.BCrypt.NTSTATUS nTSTATUS = global::Interop.BCrypt.BCryptFinishHash(_hHash, destination, _hashSize, 0); if (nTSTATUS != 0) { throw global::Interop.BCrypt.CreateCryptographicException(nTSTATUS); } _running = false; Reset(); return _hashSize; } public sealed override void Dispose(bool disposing) { if (disposing) { DestroyHash(); if (_key != null) { byte[] key = _key; _key = null; Array.Clear(key); } } } public override void Reset() { if (!_reusable || _running) { DestroyHash(); global::Interop.BCrypt.BCryptCreateHashFlags dwFlags = (_reusable ? global::Interop.BCrypt.BCryptCreateHashFlags.BCRYPT_HASH_REUSABLE_FLAG : global::Interop.BCrypt.BCryptCreateHashFlags.None); SafeBCryptHashHandle phHash; global::Interop.BCrypt.NTSTATUS nTSTATUS = global::Interop.BCrypt.BCryptCreateHash(_hAlgorithm, out phHash, IntPtr.Zero, 0, _key, (_key != null) ? _key.Length : 0, dwFlags); if (nTSTATUS != 0) { throw global::Interop.BCrypt.CreateCryptographicException(nTSTATUS); } _hHash = phHash; } } private void DestroyHash() { SafeBCryptHashHandle hHash = _hHash; _hHash = null; hHash?.Dispose(); } } internal abstract class BasicSymmetricCipher : IDisposable { public int BlockSizeInBytes { get; private set; } public int PaddingSizeInBytes { get; private set; } protected byte[] IV { get; private set; } protected BasicSymmetricCipher(byte[] iv, int blockSizeInBytes, int paddingSizeInBytes) { IV = iv; BlockSizeInBytes = blockSizeInBytes; PaddingSizeInBytes = ((paddingSizeInBytes > 0) ? paddingSizeInBytes : blockSizeInBytes); } public abstract int Transform(ReadOnlySpan input, Span output); public abstract int TransformFinal(ReadOnlySpan input, Span output); public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing && IV != null) { Array.Clear(IV); IV = null; } } } internal sealed class BasicSymmetricCipherBCrypt : Internal.Cryptography.BasicSymmetricCipher { private readonly bool _encrypting; private SafeKeyHandle _hKey; private byte[] _currentIv; public BasicSymmetricCipherBCrypt(SafeAlgorithmHandle algorithm, CipherMode cipherMode, int blockSizeInBytes, int paddingSizeInBytes, byte[] key, bool ownsParentHandle, byte[] iv, bool encrypting) : base(cipherMode.GetCipherIv(iv), blockSizeInBytes, paddingSizeInBytes) { _encrypting = encrypting; if (base.IV != null) { _currentIv = new byte[base.IV.Length]; } _hKey = global::Interop.BCrypt.BCryptImportKey(algorithm, key); if (ownsParentHandle) { _hKey.SetParentHandle(algorithm); } Reset(); } protected override void Dispose(bool disposing) { if (disposing) { SafeKeyHandle hKey = _hKey; _hKey = null; hKey?.Dispose(); byte[] currentIv = _currentIv; _currentIv = null; if (currentIv != null) { Array.Clear(currentIv); } } base.Dispose(disposing); } public override int Transform(ReadOnlySpan input, Span output) { int num = 0; if (input.Overlaps(output, out var elementOffset) && elementOffset != 0) { byte[] array = System.Security.Cryptography.CryptoPool.Rent(output.Length); try { num = BCryptTransform(input, array); array.AsSpan(0, num).CopyTo(output); } finally { System.Security.Cryptography.CryptoPool.Return(array, num); } } else { num = BCryptTransform(input, output); } if (num != input.Length) { throw new CryptographicException(System.SR.Cryptography_UnexpectedTransformTruncation); } return num; int BCryptTransform(ReadOnlySpan input, Span output) { if (!_encrypting) { return global::Interop.BCrypt.BCryptDecrypt(_hKey, input, _currentIv, output); } return global::Interop.BCrypt.BCryptEncrypt(_hKey, input, _currentIv, output); } } public override int TransformFinal(ReadOnlySpan input, Span output) { int result = 0; if (input.Length != 0) { result = Transform(input, output); } Reset(); return result; } private void Reset() { if (base.IV != null) { Buffer.BlockCopy(base.IV, 0, _currentIv, 0, base.IV.Length); } } } internal abstract class UniversalCryptoTransform : ICryptoTransform, IDisposable { public bool CanReuseTransform => true; public bool CanTransformMultipleBlocks => true; protected int PaddingSizeBytes => BasicSymmetricCipher.PaddingSizeInBytes; public int InputBlockSize => BasicSymmetricCipher.BlockSizeInBytes; public int OutputBlockSize => BasicSymmetricCipher.BlockSizeInBytes; protected PaddingMode PaddingMode { get; private set; } protected Internal.Cryptography.BasicSymmetricCipher BasicSymmetricCipher { get; private set; } public static Internal.Cryptography.UniversalCryptoTransform Create(PaddingMode paddingMode, Internal.Cryptography.BasicSymmetricCipher cipher, bool encrypting) { if (encrypting) { return new Internal.Cryptography.UniversalCryptoEncryptor(paddingMode, cipher); } return new Internal.Cryptography.UniversalCryptoDecryptor(paddingMode, cipher); } protected UniversalCryptoTransform(PaddingMode paddingMode, Internal.Cryptography.BasicSymmetricCipher basicSymmetricCipher) { PaddingMode = paddingMode; BasicSymmetricCipher = basicSymmetricCipher; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { if (inputBuffer == null) { throw new ArgumentNullException("inputBuffer"); } if (inputOffset < 0) { throw new ArgumentOutOfRangeException("inputOffset"); } if (inputOffset > inputBuffer.Length) { throw new ArgumentOutOfRangeException("inputOffset"); } if (inputCount <= 0) { throw new ArgumentOutOfRangeException("inputCount"); } if (inputCount % InputBlockSize != 0) { throw new ArgumentOutOfRangeException("inputCount", System.SR.Cryptography_MustTransformWholeBlock); } if (inputCount > inputBuffer.Length - inputOffset) { throw new ArgumentOutOfRangeException("inputCount", System.SR.Cryptography_TransformBeyondEndOfBuffer); } if (outputBuffer == null) { throw new ArgumentNullException("outputBuffer"); } if (outputOffset > outputBuffer.Length) { throw new ArgumentOutOfRangeException("outputOffset"); } if (inputCount > outputBuffer.Length - outputOffset) { throw new ArgumentOutOfRangeException("outputOffset", System.SR.Cryptography_TransformBeyondEndOfBuffer); } return UncheckedTransformBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); } public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { if (inputBuffer == null) { throw new ArgumentNullException("inputBuffer"); } if (inputOffset < 0) { throw new ArgumentOutOfRangeException("inputOffset"); } if (inputCount < 0) { throw new ArgumentOutOfRangeException("inputCount"); } if (inputOffset > inputBuffer.Length) { throw new ArgumentOutOfRangeException("inputOffset"); } if (inputCount > inputBuffer.Length - inputOffset) { throw new ArgumentOutOfRangeException("inputCount", System.SR.Cryptography_TransformBeyondEndOfBuffer); } return UncheckedTransformFinalBlock(inputBuffer, inputOffset, inputCount); } public abstract bool TransformOneShot(ReadOnlySpan input, Span output, out int bytesWritten); protected virtual void Dispose(bool disposing) { if (disposing) { BasicSymmetricCipher.Dispose(); } } protected int UncheckedTransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { return UncheckedTransformBlock(inputBuffer.AsSpan(inputOffset, inputCount), outputBuffer.AsSpan(outputOffset)); } protected abstract int UncheckedTransformBlock(ReadOnlySpan inputBuffer, Span outputBuffer); protected abstract byte[] UncheckedTransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount); protected abstract int UncheckedTransformFinalBlock(ReadOnlySpan inputBuffer, Span outputBuffer); } internal sealed class UniversalCryptoEncryptor : Internal.Cryptography.UniversalCryptoTransform { public UniversalCryptoEncryptor(PaddingMode paddingMode, Internal.Cryptography.BasicSymmetricCipher basicSymmetricCipher) : base(paddingMode, basicSymmetricCipher) { } protected override int UncheckedTransformBlock(ReadOnlySpan inputBuffer, Span outputBuffer) { return base.BasicSymmetricCipher.Transform(inputBuffer, outputBuffer); } protected override int UncheckedTransformFinalBlock(ReadOnlySpan inputBuffer, Span outputBuffer) { int length = PadBlock(inputBuffer, outputBuffer); return base.BasicSymmetricCipher.TransformFinal(outputBuffer.Slice(0, length), outputBuffer); } protected override byte[] UncheckedTransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { byte[] array = GC.AllocateUninitializedArray(GetCiphertextLength(inputCount)); int num = UncheckedTransformFinalBlock(inputBuffer.AsSpan(inputOffset, inputCount), array); return array; } public override bool TransformOneShot(ReadOnlySpan input, Span output, out int bytesWritten) { int ciphertextLength = GetCiphertextLength(input.Length); if (output.Length < ciphertextLength) { bytesWritten = 0; return false; } Span span = output[..PadBlock(input, output)]; bytesWritten = base.BasicSymmetricCipher.TransformFinal(span, span); return true; } private int GetCiphertextLength(int plaintextLength) { int result; int num = Math.DivRem(plaintextLength, base.PaddingSizeBytes, out result) * base.PaddingSizeBytes; switch (base.PaddingMode) { case PaddingMode.None: if (result != 0) { throw new CryptographicException(System.SR.Cryptography_PartialBlock); } goto IL_004c; case PaddingMode.Zeros: if (result == 0) { goto IL_004c; } goto case PaddingMode.PKCS7; case PaddingMode.PKCS7: case PaddingMode.ANSIX923: case PaddingMode.ISO10126: return checked(num + base.PaddingSizeBytes); default: { throw new CryptographicException(System.SR.Cryptography_UnknownPaddingMode); } IL_004c: return plaintextLength; } } private int PadBlock(ReadOnlySpan block, Span destination) { int length = block.Length; int num = length % base.PaddingSizeBytes; int num2 = base.PaddingSizeBytes - num; switch (base.PaddingMode) { case PaddingMode.None: if (num != 0) { throw new CryptographicException(System.SR.Cryptography_PartialBlock); } if (destination.Length < length) { throw new ArgumentException(System.SR.Argument_DestinationTooShort, "destination"); } block.CopyTo(destination); return length; case PaddingMode.ANSIX923: { int num4 = length + num2; if (destination.Length < num4) { throw new ArgumentException(System.SR.Argument_DestinationTooShort, "destination"); } block.CopyTo(destination); destination.Slice(length, num2 - 1).Clear(); destination[length + num2 - 1] = (byte)num2; return num4; } case PaddingMode.ISO10126: { int num6 = length + num2; if (destination.Length < num6) { throw new ArgumentException(System.SR.Argument_DestinationTooShort, "destination"); } block.CopyTo(destination); RandomNumberGenerator.Fill(destination.Slice(length, num2 - 1)); destination[length + num2 - 1] = (byte)num2; return num6; } case PaddingMode.PKCS7: { int num5 = length + num2; if (destination.Length < num5) { throw new ArgumentException(System.SR.Argument_DestinationTooShort, "destination"); } block.CopyTo(destination); destination.Slice(length, num2).Fill((byte)num2); return num5; } case PaddingMode.Zeros: { if (num2 == base.PaddingSizeBytes) { num2 = 0; } int num3 = length + num2; if (destination.Length < num3) { throw new ArgumentException(System.SR.Argument_DestinationTooShort, "destination"); } block.CopyTo(destination); destination.Slice(length, num2).Clear(); return num3; } default: throw new CryptographicException(System.SR.Cryptography_UnknownPaddingMode); } } } internal sealed class UniversalCryptoDecryptor : Internal.Cryptography.UniversalCryptoTransform { private byte[] _heldoverCipher; private bool DepaddingRequired { get { switch (base.PaddingMode) { case PaddingMode.PKCS7: case PaddingMode.ANSIX923: case PaddingMode.ISO10126: return true; case PaddingMode.None: case PaddingMode.Zeros: return false; default: throw new CryptographicException(System.SR.Cryptography_UnknownPaddingMode); } } } public UniversalCryptoDecryptor(PaddingMode paddingMode, Internal.Cryptography.BasicSymmetricCipher basicSymmetricCipher) : base(paddingMode, basicSymmetricCipher) { } protected override int UncheckedTransformBlock(ReadOnlySpan inputBuffer, Span outputBuffer) { int num = 0; if (DepaddingRequired) { if (_heldoverCipher != null) { int num2 = base.BasicSymmetricCipher.Transform(_heldoverCipher, outputBuffer); outputBuffer = outputBuffer.Slice(num2); num += num2; } else { _heldoverCipher = new byte[base.InputBlockSize]; } inputBuffer.Slice(inputBuffer.Length - _heldoverCipher.Length).CopyTo(_heldoverCipher); inputBuffer = inputBuffer.Slice(0, inputBuffer.Length - _heldoverCipher.Length); } if (inputBuffer.Length > 0) { num += base.BasicSymmetricCipher.Transform(inputBuffer, outputBuffer); } return num; } protected unsafe override int UncheckedTransformFinalBlock(ReadOnlySpan inputBuffer, Span outputBuffer) { if (inputBuffer.Length % base.PaddingSizeBytes != 0) { throw new CryptographicException(System.SR.Cryptography_PartialBlock); } byte[] array = null; int num = 0; try { Span span; ReadOnlySpan input; if (_heldoverCipher == null) { num = inputBuffer.Length; array = System.Security.Cryptography.CryptoPool.Rent(inputBuffer.Length); span = array.AsSpan(0, inputBuffer.Length); input = inputBuffer; } else { num = _heldoverCipher.Length + inputBuffer.Length; array = System.Security.Cryptography.CryptoPool.Rent(num); span = array.AsSpan(0, num); _heldoverCipher.AsSpan().CopyTo(span); inputBuffer.CopyTo(span.Slice(_heldoverCipher.Length)); input = span; } int num2 = 0; fixed (byte* ptr = span) { Span span2 = span[..base.BasicSymmetricCipher.TransformFinal(input, span)]; if (span2.Length > 0) { num2 = GetPaddingLength(span2); span2.Slice(0, num2).CopyTo(outputBuffer); } } Reset(); return num2; } finally { if (array != null) { System.Security.Cryptography.CryptoPool.Return(array, num); } } } protected unsafe override byte[] UncheckedTransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { if (DepaddingRequired) { byte[] array = System.Security.Cryptography.CryptoPool.Rent(inputCount + base.InputBlockSize); int num = 0; fixed (byte* ptr = array) { try { num = UncheckedTransformFinalBlock(inputBuffer.AsSpan(inputOffset, inputCount), array); return array.AsSpan(0, num).ToArray(); } finally { System.Security.Cryptography.CryptoPool.Return(array, num); } } } byte[] array2 = GC.AllocateUninitializedArray(inputCount); int num2 = UncheckedTransformFinalBlock(inputBuffer.AsSpan(inputOffset, inputCount), array2); return array2; } protected sealed override void Dispose(bool disposing) { if (disposing) { byte[] heldoverCipher = _heldoverCipher; _heldoverCipher = null; if (heldoverCipher != null) { Array.Clear(heldoverCipher); } } base.Dispose(disposing); } public unsafe override bool TransformOneShot(ReadOnlySpan input, Span output, out int bytesWritten) { if (input.Length % base.PaddingSizeBytes != 0) { throw new CryptographicException(System.SR.Cryptography_PartialBlock); } if (!DepaddingRequired) { if (output.Length >= input.Length) { bytesWritten = base.BasicSymmetricCipher.TransformFinal(input, output); return true; } bytesWritten = 0; return false; } byte[] array = System.Security.Cryptography.CryptoPool.Rent(input.Length); Span output2 = array.AsSpan(0, input.Length); Span span = default(Span); fixed (byte* ptr = output2) { try { span = output2[..base.BasicSymmetricCipher.TransformFinal(input, output2)]; int paddingLength = GetPaddingLength(span); if (paddingLength > output.Length) { bytesWritten = 0; return false; } span.Slice(0, paddingLength).CopyTo(output); bytesWritten = paddingLength; return true; } finally { CryptographicOperations.ZeroMemory(span); System.Security.Cryptography.CryptoPool.Return(array, 0); } } } private void Reset() { if (_heldoverCipher != null) { Array.Clear(_heldoverCipher); _heldoverCipher = null; } } private int GetPaddingLength(ReadOnlySpan block) { int num = 0; switch (base.PaddingMode) { case PaddingMode.ANSIX923: { num = block[^1]; if (num <= 0 || num > base.InputBlockSize) { throw new CryptographicException(System.SR.Cryptography_InvalidPadding); } for (int j = block.Length - num; j < block.Length - 1; j++) { if (block[j] != 0) { throw new CryptographicException(System.SR.Cryptography_InvalidPadding); } } break; } case PaddingMode.ISO10126: num = block[^1]; if (num <= 0 || num > base.InputBlockSize) { throw new CryptographicException(System.SR.Cryptography_InvalidPadding); } break; case PaddingMode.PKCS7: { num = block[^1]; if (num <= 0 || num > base.InputBlockSize) { throw new CryptographicException(System.SR.Cryptography_InvalidPadding); } for (int i = block.Length - num; i < block.Length - 1; i++) { if (block[i] != num) { throw new CryptographicException(System.SR.Cryptography_InvalidPadding); } } break; } case PaddingMode.None: case PaddingMode.Zeros: num = 0; break; default: throw new CryptographicException(System.SR.Cryptography_UnknownPaddingMode); } return block.Length - num; } } } namespace Microsoft.Win32.SafeHandles { public abstract class SafeNCryptHandle : SafeHandleZeroOrMinusOneIsInvalid { private enum OwnershipState { Owner, Duplicate, Holder } private OwnershipState _ownershipState; private SafeNCryptHandle _holder; private SafeHandle _parentHandle; private SafeNCryptHandle? Holder { get { return _holder; } [param: DisallowNull] set { _holder = value; _ownershipState = OwnershipState.Duplicate; } } protected SafeNCryptHandle() : base(ownsHandle: true) { } protected SafeNCryptHandle(IntPtr handle, SafeHandle parentHandle) : base(ownsHandle: true) { if (parentHandle == null) { throw new ArgumentNullException("parentHandle"); } if (parentHandle.IsClosed || parentHandle.IsInvalid) { throw new ArgumentException(System.SR.Argument_Invalid_SafeHandleInvalidOrClosed, "parentHandle"); } bool success = false; parentHandle.DangerousAddRef(ref success); _parentHandle = parentHandle; SetHandle(handle); if (IsInvalid) { _parentHandle.DangerousRelease(); _parentHandle = null; } } internal T Duplicate() where T : SafeNCryptHandle, new() { if (_ownershipState == OwnershipState.Owner) { return DuplicateOwnerHandle(); } return DuplicateDuplicatedHandle(); } private T DuplicateDuplicatedHandle() where T : SafeNCryptHandle, new() { bool success = false; T val = new T(); Holder.DangerousAddRef(ref success); val.SetHandle(Holder.DangerousGetHandle()); val.Holder = Holder; return val; } private T DuplicateOwnerHandle() where T : SafeNCryptHandle, new() { bool success = false; T val = new T(); T val2 = new T(); val._ownershipState = OwnershipState.Holder; val.SetHandle(DangerousGetHandle()); GC.SuppressFinalize(val); if (_parentHandle != null) { val._parentHandle = _parentHandle; _parentHandle = null; } Holder = val; val.DangerousAddRef(ref success); val2.SetHandle(val.DangerousGetHandle()); val2.Holder = val; return val2; } protected override bool ReleaseHandle() { if (_ownershipState == OwnershipState.Duplicate) { Holder.DangerousRelease(); return true; } if (_parentHandle != null) { _parentHandle.DangerousRelease(); return true; } return ReleaseNativeHandle(); } protected abstract bool ReleaseNativeHandle(); internal bool ReleaseNativeWithNCryptFreeObject() { global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptFreeObject(handle); return errorCode == global::Interop.NCrypt.ErrorCode.ERROR_SUCCESS; } } public sealed class SafeNCryptKeyHandle : SafeNCryptHandle { public SafeNCryptKeyHandle() { } public SafeNCryptKeyHandle(IntPtr handle, SafeHandle parentHandle) : base(handle, parentHandle) { } internal SafeNCryptKeyHandle Duplicate() { return Duplicate(); } protected override bool ReleaseNativeHandle() { return ReleaseNativeWithNCryptFreeObject(); } } public sealed class SafeNCryptProviderHandle : SafeNCryptHandle { internal SafeNCryptProviderHandle Duplicate() { return Duplicate(); } internal void SetHandleValue(IntPtr newHandleValue) { SetHandle(newHandleValue); } protected override bool ReleaseNativeHandle() { return ReleaseNativeWithNCryptFreeObject(); } } public sealed class SafeNCryptSecretHandle : SafeNCryptHandle { protected override bool ReleaseNativeHandle() { return ReleaseNativeWithNCryptFreeObject(); } } internal abstract class SafeBCryptHandle : SafeHandle, IDisposable { public sealed override bool IsInvalid => handle == IntPtr.Zero; protected SafeBCryptHandle() : base(IntPtr.Zero, ownsHandle: true) { } protected abstract override bool ReleaseHandle(); } internal sealed class SafeBCryptHashHandle : SafeBCryptHandle { protected sealed override bool ReleaseHandle() { global::Interop.BCrypt.NTSTATUS nTSTATUS = global::Interop.BCrypt.BCryptDestroyHash(handle); return nTSTATUS == global::Interop.BCrypt.NTSTATUS.STATUS_SUCCESS; } } internal sealed class SafeBCryptAlgorithmHandle : SafeBCryptHandle { protected sealed override bool ReleaseHandle() { global::Interop.BCrypt.NTSTATUS nTSTATUS = global::Interop.BCrypt.BCryptCloseAlgorithmProvider(handle, 0); return nTSTATUS == global::Interop.BCrypt.NTSTATUS.STATUS_SUCCESS; } } internal sealed class SafeUnicodeStringHandle : SafeHandle { public sealed override bool IsInvalid => handle == IntPtr.Zero; public SafeUnicodeStringHandle(string s) : base(IntPtr.Zero, ownsHandle: true) { handle = Marshal.StringToHGlobalUni(s); } public unsafe SafeUnicodeStringHandle(ReadOnlySpan s) : base(IntPtr.Zero, ownsHandle: true) { checked { if (s != default(ReadOnlySpan)) { int num = s.Length + 1; int cb = num * 2; handle = Marshal.AllocHGlobal(cb); Span destination = new Span(handle.ToPointer(), num); s.CopyTo(destination); destination[s.Length] = '\0'; } } } protected sealed override bool ReleaseHandle() { Marshal.FreeHGlobal(handle); return true; } } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled; private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); internal static string Argument_Invalid_SafeHandleInvalidOrClosed => GetResourceString("Argument_Invalid_SafeHandleInvalidOrClosed"); internal static string Argument_InvalidOffLen => GetResourceString("Argument_InvalidOffLen"); internal static string Argument_InvalidValue => GetResourceString("Argument_InvalidValue"); internal static string ArgumentNull_Buffer => GetResourceString("ArgumentNull_Buffer"); internal static string Cryptography_AlgorithmNotSupported => GetResourceString("Cryptography_AlgorithmNotSupported"); internal static string Cryptography_AlgKdfRequiresChars => GetResourceString("Cryptography_AlgKdfRequiresChars"); internal static string Cryptography_ArgECDHKeySizeMismatch => GetResourceString("Cryptography_ArgECDHKeySizeMismatch"); internal static string Cryptography_ArgECDHRequiresECDHKey => GetResourceString("Cryptography_ArgECDHRequiresECDHKey"); internal static string Cryptography_TlsRequiresLabelAndSeed => GetResourceString("Cryptography_TlsRequiresLabelAndSeed"); internal static string Cryptography_ArgDSARequiresDSAKey => GetResourceString("Cryptography_ArgDSARequiresDSAKey"); internal static string Cryptography_ArgECDsaRequiresECDsaKey => GetResourceString("Cryptography_ArgECDsaRequiresECDsaKey"); internal static string Cryptography_ArgRSARequiresRSAKey => GetResourceString("Cryptography_ArgRSARequiresRSAKey"); internal static string Cryptography_CipherModeFeedbackNotSupported => GetResourceString("Cryptography_CipherModeFeedbackNotSupported"); internal static string Cryptography_CngKeyWrongAlgorithm => GetResourceString("Cryptography_CngKeyWrongAlgorithm"); internal static string Cryptography_Der_Invalid_Encoding => GetResourceString("Cryptography_Der_Invalid_Encoding"); internal static string Cryptography_Encryption_MessageTooLong => GetResourceString("Cryptography_Encryption_MessageTooLong"); internal static string Cryptography_HashAlgorithmNameNullOrEmpty => GetResourceString("Cryptography_HashAlgorithmNameNullOrEmpty"); internal static string Cryptography_InvalidAlgorithmGroup => GetResourceString("Cryptography_InvalidAlgorithmGroup"); internal static string Cryptography_InvalidAlgorithmName => GetResourceString("Cryptography_InvalidAlgorithmName"); internal static string Cryptography_InvalidCipherMode => GetResourceString("Cryptography_InvalidCipherMode"); internal static string Cryptography_InvalidDsaParameters_MissingFields => GetResourceString("Cryptography_InvalidDsaParameters_MissingFields"); internal static string Cryptography_InvalidDsaParameters_MismatchedPGY => GetResourceString("Cryptography_InvalidDsaParameters_MismatchedPGY"); internal static string Cryptography_InvalidDsaParameters_MismatchedQX => GetResourceString("Cryptography_InvalidDsaParameters_MismatchedQX"); internal static string Cryptography_InvalidDsaParameters_MismatchedPJ => GetResourceString("Cryptography_InvalidDsaParameters_MismatchedPJ"); internal static string Cryptography_InvalidDsaParameters_SeedRestriction_ShortKey => GetResourceString("Cryptography_InvalidDsaParameters_SeedRestriction_ShortKey"); internal static string Cryptography_InvalidDsaParameters_QRestriction_ShortKey => GetResourceString("Cryptography_InvalidDsaParameters_QRestriction_ShortKey"); internal static string Cryptography_InvalidDsaParameters_QRestriction_LargeKey => GetResourceString("Cryptography_InvalidDsaParameters_QRestriction_LargeKey"); internal static string Cryptography_CurveNotSupported => GetResourceString("Cryptography_CurveNotSupported"); internal static string Cryptography_InvalidCurveOid => GetResourceString("Cryptography_InvalidCurveOid"); internal static string Cryptography_InvalidIVSize => GetResourceString("Cryptography_InvalidIVSize"); internal static string Cryptography_InvalidKeyBlobFormat => GetResourceString("Cryptography_InvalidKeyBlobFormat"); internal static string Cryptography_InvalidKeySize => GetResourceString("Cryptography_InvalidKeySize"); internal static string Cryptography_InvalidPadding => GetResourceString("Cryptography_InvalidPadding"); internal static string Cryptography_InvalidProviderName => GetResourceString("Cryptography_InvalidProviderName"); internal static string Cryptography_InvalidRsaParameters => GetResourceString("Cryptography_InvalidRsaParameters"); internal static string Cryptography_KeyBlobParsingError => GetResourceString("Cryptography_KeyBlobParsingError"); internal static string Cryptography_KeyTooSmall => GetResourceString("Cryptography_KeyTooSmall"); internal static string Cryptography_OpenEphemeralKeyHandleWithoutEphemeralFlag => GetResourceString("Cryptography_OpenEphemeralKeyHandleWithoutEphemeralFlag"); internal static string Cryptography_OpenInvalidHandle => GetResourceString("Cryptography_OpenInvalidHandle"); internal static string Cryptography_MissingIV => GetResourceString("Cryptography_MissingIV"); internal static string Cryptography_MustTransformWholeBlock => GetResourceString("Cryptography_MustTransformWholeBlock"); internal static string Cryptography_NotValidPrivateKey => GetResourceString("Cryptography_NotValidPrivateKey"); internal static string Cryptography_NotValidPublicOrPrivateKey => GetResourceString("Cryptography_NotValidPublicOrPrivateKey"); internal static string Cryptography_PartialBlock => GetResourceString("Cryptography_PartialBlock"); internal static string Cryptography_RSA_DecryptWrongSize => GetResourceString("Cryptography_RSA_DecryptWrongSize"); internal static string Cryptography_Pkcs8_EncryptedReadFailed => GetResourceString("Cryptography_Pkcs8_EncryptedReadFailed"); internal static string Cryptography_SignHash_WrongSize => GetResourceString("Cryptography_SignHash_WrongSize"); internal static string Cryptography_UnsupportedPaddingMode => GetResourceString("Cryptography_UnsupportedPaddingMode"); internal static string Cryptography_TransformBeyondEndOfBuffer => GetResourceString("Cryptography_TransformBeyondEndOfBuffer"); internal static string Cryptography_UnexpectedTransformTruncation => GetResourceString("Cryptography_UnexpectedTransformTruncation"); internal static string Cryptography_UnknownAlgorithmIdentifier => GetResourceString("Cryptography_UnknownAlgorithmIdentifier"); internal static string Cryptography_UnknownHashAlgorithm => GetResourceString("Cryptography_UnknownHashAlgorithm"); internal static string Cryptography_UnknownPaddingMode => GetResourceString("Cryptography_UnknownPaddingMode"); internal static string Cryptography_WeakKey => GetResourceString("Cryptography_WeakKey"); internal static string Cryptography_ECC_NamedCurvesOnly => GetResourceString("Cryptography_ECC_NamedCurvesOnly"); internal static string Cryptography_CSP_NoPrivateKey => GetResourceString("Cryptography_CSP_NoPrivateKey"); internal static string Cryptography_InvalidECCharacteristic2Curve => GetResourceString("Cryptography_InvalidECCharacteristic2Curve"); internal static string Argument_DestinationTooShort => GetResourceString("Argument_DestinationTooShort"); internal static string Cryptography_FeedbackSizeNotSupported => GetResourceString("Cryptography_FeedbackSizeNotSupported"); private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } 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); } } } namespace System.Buffers { internal class PointerMemoryManager : MemoryManager 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 GetSpan() { return new Span(_pointer, _length); } public override MemoryHandle Pin(int elementIndex = 0) { throw new NotSupportedException(); } public override void Unpin() { } } } namespace System.Security.Cryptography { public sealed class AesCng : Aes, ICngSymmetricAlgorithm { private CngSymmetricAlgorithmCore _core; public override byte[] Key { get { return _core.GetKeyIfExportable(); } set { _core.SetKey(value); } } public override int KeySize { get { return base.KeySize; } set { _core.SetKeySize(value, this); } } byte[] ICngSymmetricAlgorithm.BaseKey { get { return base.Key; } set { base.Key = value; } } int ICngSymmetricAlgorithm.BaseKeySize { get { return base.KeySize; } set { base.KeySize = value; } } public AesCng() { _core = new CngSymmetricAlgorithmCore(this); } public AesCng(string keyName) : this(keyName, CngProvider.MicrosoftSoftwareKeyStorageProvider) { } public AesCng(string keyName, CngProvider provider) : this(keyName, provider, CngKeyOpenOptions.None) { } public AesCng(string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { _core = new CngSymmetricAlgorithmCore(this, keyName, provider, openOptions); } public override ICryptoTransform CreateDecryptor() { return _core.CreateDecryptor(); } public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) { return _core.CreateDecryptor(rgbKey, rgbIV); } public override ICryptoTransform CreateEncryptor() { return _core.CreateEncryptor(); } public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) { return _core.CreateEncryptor(rgbKey, rgbIV); } public override void GenerateKey() { _core.GenerateKey(); } public override void GenerateIV() { _core.GenerateIV(); } protected override bool TryDecryptEcbCore(ReadOnlySpan ciphertext, Span destination, PaddingMode paddingMode, out int bytesWritten) { Internal.Cryptography.UniversalCryptoTransform universalCryptoTransform = _core.CreateCryptoTransform(null, encrypting: false, paddingMode, CipherMode.ECB, 0); using (universalCryptoTransform) { return universalCryptoTransform.TransformOneShot(ciphertext, destination, out bytesWritten); } } protected override bool TryEncryptEcbCore(ReadOnlySpan plaintext, Span destination, PaddingMode paddingMode, out int bytesWritten) { Internal.Cryptography.UniversalCryptoTransform universalCryptoTransform = _core.CreateCryptoTransform(null, encrypting: true, paddingMode, CipherMode.ECB, 0); using (universalCryptoTransform) { return universalCryptoTransform.TransformOneShot(plaintext, destination, out bytesWritten); } } protected override bool TryEncryptCbcCore(ReadOnlySpan plaintext, ReadOnlySpan iv, Span destination, PaddingMode paddingMode, out int bytesWritten) { Internal.Cryptography.UniversalCryptoTransform universalCryptoTransform = _core.CreateCryptoTransform(iv.ToArray(), encrypting: true, paddingMode, CipherMode.CBC, 0); using (universalCryptoTransform) { return universalCryptoTransform.TransformOneShot(plaintext, destination, out bytesWritten); } } protected override bool TryDecryptCbcCore(ReadOnlySpan ciphertext, ReadOnlySpan iv, Span destination, PaddingMode paddingMode, out int bytesWritten) { Internal.Cryptography.UniversalCryptoTransform universalCryptoTransform = _core.CreateCryptoTransform(iv.ToArray(), encrypting: false, paddingMode, CipherMode.CBC, 0); using (universalCryptoTransform) { return universalCryptoTransform.TransformOneShot(ciphertext, destination, out bytesWritten); } } protected override bool TryDecryptCfbCore(ReadOnlySpan ciphertext, ReadOnlySpan iv, Span destination, PaddingMode paddingMode, int feedbackSizeInBits, out int bytesWritten) { Internal.Cryptography.UniversalCryptoTransform universalCryptoTransform = _core.CreateCryptoTransform(iv.ToArray(), encrypting: false, paddingMode, CipherMode.CFB, feedbackSizeInBits); using (universalCryptoTransform) { return universalCryptoTransform.TransformOneShot(ciphertext, destination, out bytesWritten); } } protected override bool TryEncryptCfbCore(ReadOnlySpan plaintext, ReadOnlySpan iv, Span destination, PaddingMode paddingMode, int feedbackSizeInBits, out int bytesWritten) { Internal.Cryptography.UniversalCryptoTransform universalCryptoTransform = _core.CreateCryptoTransform(iv.ToArray(), encrypting: true, paddingMode, CipherMode.CFB, feedbackSizeInBits); using (universalCryptoTransform) { return universalCryptoTransform.TransformOneShot(plaintext, destination, out bytesWritten); } } protected override void Dispose(bool disposing) { base.Dispose(disposing); } bool ICngSymmetricAlgorithm.IsWeakKey(byte[] key) { return false; } int ICngSymmetricAlgorithm.GetPaddingSize(CipherMode mode, int feedbackSizeBits) { return this.GetPaddingSize(mode, feedbackSizeBits); } SafeAlgorithmHandle ICngSymmetricAlgorithm.GetEphemeralModeHandle(CipherMode mode, int feedbackSizeInBits) { try { return AesBCryptModes.GetSharedHandle(mode, feedbackSizeInBits / 8); } catch (NotSupportedException) { throw new CryptographicException(System.SR.Cryptography_InvalidCipherMode); } } string ICngSymmetricAlgorithm.GetNCryptAlgorithmIdentifier() { return "AES"; } byte[] ICngSymmetricAlgorithm.PreprocessKey(byte[] key) { return key; } bool ICngSymmetricAlgorithm.IsValidEphemeralFeedbackSize(int feedbackSizeInBits) { if (feedbackSizeInBits != 8) { return feedbackSizeInBits == 128; } return true; } } public sealed class CngAlgorithm : IEquatable { private static CngAlgorithm s_ecdh; private static CngAlgorithm s_ecdhp256; private static CngAlgorithm s_ecdhp384; private static CngAlgorithm s_ecdhp521; private static CngAlgorithm s_ecdsa; private static CngAlgorithm s_ecdsap256; private static CngAlgorithm s_ecdsap384; private static CngAlgorithm s_ecdsap521; private static CngAlgorithm s_md5; private static CngAlgorithm s_sha1; private static CngAlgorithm s_sha256; private static CngAlgorithm s_sha384; private static CngAlgorithm s_sha512; private static CngAlgorithm s_rsa; private readonly string _algorithm; public string Algorithm => _algorithm; public static CngAlgorithm Rsa => s_rsa ?? (s_rsa = new CngAlgorithm("RSA")); public static CngAlgorithm ECDiffieHellman => s_ecdh ?? (s_ecdh = new CngAlgorithm("ECDH")); public static CngAlgorithm ECDiffieHellmanP256 => s_ecdhp256 ?? (s_ecdhp256 = new CngAlgorithm("ECDH_P256")); public static CngAlgorithm ECDiffieHellmanP384 => s_ecdhp384 ?? (s_ecdhp384 = new CngAlgorithm("ECDH_P384")); public static CngAlgorithm ECDiffieHellmanP521 => s_ecdhp521 ?? (s_ecdhp521 = new CngAlgorithm("ECDH_P521")); public static CngAlgorithm ECDsa => s_ecdsa ?? (s_ecdsa = new CngAlgorithm("ECDSA")); public static CngAlgorithm ECDsaP256 => s_ecdsap256 ?? (s_ecdsap256 = new CngAlgorithm("ECDSA_P256")); public static CngAlgorithm ECDsaP384 => s_ecdsap384 ?? (s_ecdsap384 = new CngAlgorithm("ECDSA_P384")); public static CngAlgorithm ECDsaP521 => s_ecdsap521 ?? (s_ecdsap521 = new CngAlgorithm("ECDSA_P521")); public static CngAlgorithm MD5 => s_md5 ?? (s_md5 = new CngAlgorithm("MD5")); public static CngAlgorithm Sha1 => s_sha1 ?? (s_sha1 = new CngAlgorithm("SHA1")); public static CngAlgorithm Sha256 => s_sha256 ?? (s_sha256 = new CngAlgorithm("SHA256")); public static CngAlgorithm Sha384 => s_sha384 ?? (s_sha384 = new CngAlgorithm("SHA384")); public static CngAlgorithm Sha512 => s_sha512 ?? (s_sha512 = new CngAlgorithm("SHA512")); public CngAlgorithm(string algorithm) { if (algorithm == null) { throw new ArgumentNullException("algorithm"); } if (algorithm.Length == 0) { throw new ArgumentException(System.SR.Format(System.SR.Cryptography_InvalidAlgorithmName, algorithm), "algorithm"); } _algorithm = algorithm; } public static bool operator ==(CngAlgorithm? left, CngAlgorithm? right) { return left?.Equals(right) ?? ((object)right == null); } public static bool operator !=(CngAlgorithm? left, CngAlgorithm? right) { if ((object)left == null) { return (object)right != null; } return !left.Equals(right); } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj as CngAlgorithm); } public bool Equals([NotNullWhen(true)] CngAlgorithm? other) { if ((object)other == null) { return false; } return _algorithm.Equals(other.Algorithm); } public override int GetHashCode() { return _algorithm.GetHashCode(); } public override string ToString() { return _algorithm; } } public sealed class CngAlgorithmGroup : IEquatable { private static CngAlgorithmGroup s_dh; private static CngAlgorithmGroup s_dsa; private static CngAlgorithmGroup s_ecdh; private static CngAlgorithmGroup s_ecdsa; private static CngAlgorithmGroup s_rsa; private readonly string _algorithmGroup; public string AlgorithmGroup => _algorithmGroup; public static CngAlgorithmGroup DiffieHellman => s_dh ?? (s_dh = new CngAlgorithmGroup("DH")); public static CngAlgorithmGroup Dsa => s_dsa ?? (s_dsa = new CngAlgorithmGroup("DSA")); public static CngAlgorithmGroup ECDiffieHellman => s_ecdh ?? (s_ecdh = new CngAlgorithmGroup("ECDH")); public static CngAlgorithmGroup ECDsa => s_ecdsa ?? (s_ecdsa = new CngAlgorithmGroup("ECDSA")); public static CngAlgorithmGroup Rsa => s_rsa ?? (s_rsa = new CngAlgorithmGroup("RSA")); public CngAlgorithmGroup(string algorithmGroup) { if (algorithmGroup == null) { throw new ArgumentNullException("algorithmGroup"); } if (algorithmGroup.Length == 0) { throw new ArgumentException(System.SR.Format(System.SR.Cryptography_InvalidAlgorithmGroup, algorithmGroup), "algorithmGroup"); } _algorithmGroup = algorithmGroup; } public static bool operator ==(CngAlgorithmGroup? left, CngAlgorithmGroup? right) { return left?.Equals(right) ?? ((object)right == null); } public static bool operator !=(CngAlgorithmGroup? left, CngAlgorithmGroup? right) { if ((object)left == null) { return (object)right != null; } return !left.Equals(right); } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj as CngAlgorithmGroup); } public bool Equals([NotNullWhen(true)] CngAlgorithmGroup? other) { if ((object)other == null) { return false; } return _algorithmGroup.Equals(other.AlgorithmGroup); } public override int GetHashCode() { return _algorithmGroup.GetHashCode(); } public override string ToString() { return _algorithmGroup; } } [Flags] public enum CngExportPolicies { None = 0, AllowExport = 1, AllowPlaintextExport = 2, AllowArchiving = 4, AllowPlaintextArchiving = 8 } public sealed class CngKey : IDisposable { private readonly SafeNCryptKeyHandle _keyHandle; private readonly SafeNCryptProviderHandle _providerHandle; private static readonly byte[] s_pkcs12TripleDesOidBytes = Encoding.ASCII.GetBytes("1.2.840.113549.1.12.1.3\0"); public CngAlgorithm Algorithm { get { string propertyAsString = _keyHandle.GetPropertyAsString("Algorithm Name", CngPropertyOptions.None); return new CngAlgorithm(propertyAsString); } } public CngAlgorithmGroup? AlgorithmGroup { get { string propertyAsString = _keyHandle.GetPropertyAsString("Algorithm Group", CngPropertyOptions.None); if (propertyAsString == null) { return null; } return new CngAlgorithmGroup(propertyAsString); } } public CngExportPolicies ExportPolicy { get { return (CngExportPolicies)_keyHandle.GetPropertyAsDword("Export Policy", CngPropertyOptions.None); } internal set { _keyHandle.SetExportPolicy(value); } } public SafeNCryptKeyHandle Handle => _keyHandle.Duplicate(); public unsafe bool IsEphemeral { get { Unsafe.SkipInit(out byte b); if (global::Interop.NCrypt.NCryptGetProperty(_keyHandle, "CLR IsEphemeral", &b, 1, out var pcbResult, CngPropertyOptions.CustomProperty) != 0) { return false; } if (pcbResult != 1) { return false; } if (b != 1) { return false; } return true; } private set { byte b = (byte)(value ? 1 : 0); global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptSetProperty(_keyHandle, "CLR IsEphemeral", &b, 1, CngPropertyOptions.CustomProperty); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } } } public bool IsMachineKey { get { CngKeyOpenOptions propertyAsDword = (CngKeyOpenOptions)_keyHandle.GetPropertyAsDword("Key Type", CngPropertyOptions.None); return (propertyAsDword & CngKeyOpenOptions.MachineKey) == CngKeyOpenOptions.MachineKey; } } public string? KeyName { get { if (IsEphemeral) { return null; } return _keyHandle.GetPropertyAsString("Name", CngPropertyOptions.None); } } public int KeySize { get { int result = 0; global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptGetIntProperty(_keyHandle, "PublicKeyLength", ref result); if (errorCode != 0) { errorCode = global::Interop.NCrypt.NCryptGetIntProperty(_keyHandle, "Length", ref result); } if (errorCode != 0) { throw errorCode.ToCryptographicException(); } return result; } } public CngKeyUsages KeyUsage => (CngKeyUsages)_keyHandle.GetPropertyAsDword("Key Usage", CngPropertyOptions.None); public unsafe IntPtr ParentWindowHandle { get { return _keyHandle.GetPropertyAsIntPtr("HWND Handle", CngPropertyOptions.None); } set { global::Interop.NCrypt.NCryptSetProperty(_keyHandle, "HWND Handle", &value, IntPtr.Size, CngPropertyOptions.None); } } public CngProvider? Provider { get { string propertyAsString = _providerHandle.GetPropertyAsString("Name", CngPropertyOptions.None); if (propertyAsString == null) { return null; } return new CngProvider(propertyAsString); } } public SafeNCryptProviderHandle ProviderHandle => _providerHandle.Duplicate(); public unsafe CngUIPolicy UIPolicy { get { global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptGetProperty(_keyHandle, "UI Policy", null, 0, out var pcbResult, CngPropertyOptions.None); if (errorCode != 0 && errorCode != global::Interop.NCrypt.ErrorCode.NTE_NOT_FOUND) { throw errorCode.ToCryptographicException(); } CngUIProtectionLevels protectionLevel; string friendlyName; string description; string creationTitle; if (errorCode != 0 || pcbResult == 0) { protectionLevel = CngUIProtectionLevels.None; friendlyName = null; description = null; creationTitle = null; } else { if (pcbResult < sizeof(global::Interop.NCrypt.NCRYPT_UI_POLICY)) { throw global::Interop.NCrypt.ErrorCode.E_FAIL.ToCryptographicException(); } byte[] array = new byte[pcbResult]; fixed (byte* ptr = &array[0]) { errorCode = global::Interop.NCrypt.NCryptGetProperty(_keyHandle, "UI Policy", ptr, array.Length, out pcbResult, CngPropertyOptions.None); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } global::Interop.NCrypt.NCRYPT_UI_POLICY* ptr2 = (global::Interop.NCrypt.NCRYPT_UI_POLICY*)ptr; protectionLevel = ptr2->dwFlags; friendlyName = Marshal.PtrToStringUni(ptr2->pszFriendlyName); description = Marshal.PtrToStringUni(ptr2->pszDescription); creationTitle = Marshal.PtrToStringUni(ptr2->pszCreationTitle); } } string propertyAsString = _keyHandle.GetPropertyAsString("Use Context", CngPropertyOptions.None); return new CngUIPolicy(protectionLevel, friendlyName, description, propertyAsString, creationTitle); } } public string? UniqueName { get { if (IsEphemeral) { return null; } return _keyHandle.GetPropertyAsString("Unique Name", CngPropertyOptions.None); } } private CngKey(SafeNCryptProviderHandle providerHandle, SafeNCryptKeyHandle keyHandle) { _providerHandle = providerHandle; _keyHandle = keyHandle; } public void Dispose() { if (_providerHandle != null) { _providerHandle.Dispose(); } if (_keyHandle != null) { _keyHandle.Dispose(); } } public CngProperty GetProperty(string name, CngPropertyOptions options) { if (name == null) { throw new ArgumentNullException("name"); } byte[] array = _keyHandle.GetProperty(name, options); if (array == null) { throw global::Interop.NCrypt.ErrorCode.NTE_NOT_FOUND.ToCryptographicException(); } if (array.Length == 0) { array = null; } return new CngProperty(name, array, options); } public unsafe bool HasProperty(string name, CngPropertyOptions options) { if (name == null) { throw new ArgumentNullException("name"); } int pcbResult; global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptGetProperty(_keyHandle, name, null, 0, out pcbResult, options); return errorCode switch { global::Interop.NCrypt.ErrorCode.NTE_NOT_FOUND => false, global::Interop.NCrypt.ErrorCode.ERROR_SUCCESS => true, _ => throw errorCode.ToCryptographicException(), }; } public unsafe void SetProperty(CngProperty property) { byte[] valueWithoutCopying = property.GetValueWithoutCopying(); if (valueWithoutCopying == null) { throw global::Interop.NCrypt.ErrorCode.NTE_INVALID_PARAMETER.ToCryptographicException(); } fixed (byte* pbInput = valueWithoutCopying.MapZeroLengthArrayToNonNullPointer()) { global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptSetProperty(_keyHandle, property.Name, pbInput, valueWithoutCopying.Length, property.Options); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } } } public static CngKey Create(CngAlgorithm algorithm) { return Create(algorithm, null); } public static CngKey Create(CngAlgorithm algorithm, string? keyName) { return Create(algorithm, keyName, null); } public static CngKey Create(CngAlgorithm algorithm, string? keyName, CngKeyCreationParameters? creationParameters) { if (algorithm == null) { throw new ArgumentNullException("algorithm"); } if (creationParameters == null) { creationParameters = new CngKeyCreationParameters(); } SafeNCryptProviderHandle safeNCryptProviderHandle = creationParameters.Provider.OpenStorageProvider(); global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptCreatePersistedKey(safeNCryptProviderHandle, out var phKey, algorithm.Algorithm, keyName, 0, creationParameters.KeyCreationOptions); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } InitializeKeyProperties(phKey, creationParameters); errorCode = global::Interop.NCrypt.NCryptFinalizeKey(phKey, 0); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } CngKey cngKey = new CngKey(safeNCryptProviderHandle, phKey); if (keyName == null) { cngKey.IsEphemeral = true; } return cngKey; } private unsafe static void InitializeKeyProperties(SafeNCryptKeyHandle keyHandle, CngKeyCreationParameters creationParameters) { if (creationParameters.ExportPolicy.HasValue) { CngExportPolicies value = creationParameters.ExportPolicy.Value; keyHandle.SetExportPolicy(value); } if (creationParameters.KeyUsage.HasValue) { CngKeyUsages value2 = creationParameters.KeyUsage.Value; global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptSetProperty(keyHandle, "Key Usage", &value2, 4, CngPropertyOptions.Persist); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } } if (creationParameters.ParentWindowHandle != IntPtr.Zero) { IntPtr parentWindowHandle = creationParameters.ParentWindowHandle; global::Interop.NCrypt.ErrorCode errorCode2 = global::Interop.NCrypt.NCryptSetProperty(keyHandle, "HWND Handle", &parentWindowHandle, sizeof(IntPtr), CngPropertyOptions.None); if (errorCode2 != 0) { throw errorCode2.ToCryptographicException(); } } CngUIPolicy uIPolicy = creationParameters.UIPolicy; if (uIPolicy != null) { InitializeKeyUiPolicyProperties(keyHandle, uIPolicy); } foreach (CngProperty parameter in creationParameters.Parameters) { byte[] valueWithoutCopying = parameter.GetValueWithoutCopying(); int cbInput = ((valueWithoutCopying != null) ? valueWithoutCopying.Length : 0); fixed (byte* pbInput = valueWithoutCopying.MapZeroLengthArrayToNonNullPointer()) { global::Interop.NCrypt.ErrorCode errorCode3 = global::Interop.NCrypt.NCryptSetProperty(keyHandle, parameter.Name, pbInput, cbInput, parameter.Options); if (errorCode3 != 0) { throw errorCode3.ToCryptographicException(); } } } } private unsafe static void InitializeKeyUiPolicyProperties(SafeNCryptKeyHandle keyHandle, CngUIPolicy uiPolicy) { //The blocks IL_0031, IL_0039, IL_004a, IL_00b2 are reachable both inside and outside the pinned region starting at IL_002c. ILSpy has duplicated these blocks in order to place them both within and outside the `fixed` statement. fixed (char* value3 = uiPolicy.CreationTitle) { string? friendlyName = uiPolicy.FriendlyName; char* intPtr; string? description; global::Interop.NCrypt.NCRYPT_UI_POLICY nCRYPT_UI_POLICY2; if (friendlyName == null) { char* value; intPtr = (value = null); description = uiPolicy.Description; fixed (char* ptr = description) { char* value2 = ptr; global::Interop.NCrypt.NCRYPT_UI_POLICY nCRYPT_UI_POLICY = default(global::Interop.NCrypt.NCRYPT_UI_POLICY); nCRYPT_UI_POLICY.dwVersion = 1; nCRYPT_UI_POLICY.dwFlags = uiPolicy.ProtectionLevel; nCRYPT_UI_POLICY.pszCreationTitle = new IntPtr(value3); nCRYPT_UI_POLICY.pszFriendlyName = new IntPtr(value); nCRYPT_UI_POLICY.pszDescription = new IntPtr(value2); nCRYPT_UI_POLICY2 = nCRYPT_UI_POLICY; global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptSetProperty(keyHandle, "UI Policy", &nCRYPT_UI_POLICY2, sizeof(global::Interop.NCrypt.NCRYPT_UI_POLICY), CngPropertyOptions.Persist); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } } } else { fixed (char* ptr2 = &friendlyName.GetPinnableReference()) { char* value; intPtr = (value = ptr2); description = uiPolicy.Description; fixed (char* ptr = description) { char* value2 = ptr; global::Interop.NCrypt.NCRYPT_UI_POLICY nCRYPT_UI_POLICY = default(global::Interop.NCrypt.NCRYPT_UI_POLICY); nCRYPT_UI_POLICY.dwVersion = 1; nCRYPT_UI_POLICY.dwFlags = uiPolicy.ProtectionLevel; nCRYPT_UI_POLICY.pszCreationTitle = new IntPtr(value3); nCRYPT_UI_POLICY.pszFriendlyName = new IntPtr(value); nCRYPT_UI_POLICY.pszDescription = new IntPtr(value2); nCRYPT_UI_POLICY2 = nCRYPT_UI_POLICY; global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptSetProperty(keyHandle, "UI Policy", &nCRYPT_UI_POLICY2, sizeof(global::Interop.NCrypt.NCRYPT_UI_POLICY), CngPropertyOptions.Persist); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } } } } } string useContext = uiPolicy.UseContext; if (useContext == null) { return; } int cbInput = checked((useContext.Length + 1) * 2); fixed (char* pbInput = useContext) { global::Interop.NCrypt.ErrorCode errorCode2 = global::Interop.NCrypt.NCryptSetProperty(keyHandle, "Use Context", pbInput, cbInput, CngPropertyOptions.Persist); if (errorCode2 != 0) { throw errorCode2.ToCryptographicException(); } } } internal bool IsECNamedCurve() { return IsECNamedCurve(Algorithm.Algorithm); } internal static bool IsECNamedCurve(string algorithm) { if (!(algorithm == CngAlgorithm.ECDiffieHellman.Algorithm)) { return algorithm == CngAlgorithm.ECDsa.Algorithm; } return true; } internal string GetCurveName(out string oidValue) { if (IsECNamedCurve()) { oidValue = null; return _keyHandle.GetPropertyAsString("ECCCurveName", CngPropertyOptions.None); } return GetECSpecificCurveName(out oidValue); } private string GetECSpecificCurveName(out string oidValue) { string algorithm = Algorithm.Algorithm; if (algorithm == CngAlgorithm.ECDiffieHellmanP256.Algorithm || algorithm == CngAlgorithm.ECDsaP256.Algorithm) { oidValue = "1.2.840.10045.3.1.7"; return "nistP256"; } if (algorithm == CngAlgorithm.ECDiffieHellmanP384.Algorithm || algorithm == CngAlgorithm.ECDsaP384.Algorithm) { oidValue = "1.3.132.0.34"; return "nistP384"; } if (algorithm == CngAlgorithm.ECDiffieHellmanP521.Algorithm || algorithm == CngAlgorithm.ECDsaP521.Algorithm) { oidValue = "1.3.132.0.35"; return "nistP521"; } throw new PlatformNotSupportedException(System.SR.Format(System.SR.Cryptography_CurveNotSupported, algorithm)); } internal static CngProperty GetPropertyFromNamedCurve(ECCurve curve) { string friendlyName = curve.Oid.FriendlyName; byte[] array = new byte[(friendlyName.Length + 1) * 2]; Encoding.Unicode.GetBytes(friendlyName, 0, friendlyName.Length, array, 0); return new CngProperty("ECCCurveName", array, CngPropertyOptions.None); } internal static CngAlgorithm EcdsaCurveNameToAlgorithm(string name) { switch (name) { case "nistP256": case "ECDSA_P256": return CngAlgorithm.ECDsaP256; case "nistP384": case "ECDSA_P384": return CngAlgorithm.ECDsaP384; case "nistP521": case "ECDSA_P521": return CngAlgorithm.ECDsaP521; default: return CngAlgorithm.ECDsa; } } internal static CngAlgorithm EcdhCurveNameToAlgorithm(string name) { switch (name) { case "nistP256": case "ECDH_P256": return CngAlgorithm.ECDiffieHellmanP256; case "nistP384": case "ECDH_P384": return CngAlgorithm.ECDiffieHellmanP384; case "nistP521": case "ECDH_P521": return CngAlgorithm.ECDiffieHellmanP521; default: return CngAlgorithm.ECDiffieHellman; } } internal static CngKey Import(ReadOnlySpan keyBlob, CngKeyBlobFormat format) { return Import(keyBlob, null, format, CngProvider.MicrosoftSoftwareKeyStorageProvider); } public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format) { return Import(keyBlob, format, CngProvider.MicrosoftSoftwareKeyStorageProvider); } internal static CngKey Import(byte[] keyBlob, string curveName, CngKeyBlobFormat format) { return Import(keyBlob, curveName, format, CngProvider.MicrosoftSoftwareKeyStorageProvider); } public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format, CngProvider provider) { return Import(keyBlob, null, format, provider); } internal static CngKey ImportEncryptedPkcs8(ReadOnlySpan keyBlob, ReadOnlySpan password) { return ImportEncryptedPkcs8(keyBlob, password, CngProvider.MicrosoftSoftwareKeyStorageProvider); } internal unsafe static CngKey ImportEncryptedPkcs8(ReadOnlySpan keyBlob, ReadOnlySpan password, CngProvider provider) { SafeNCryptProviderHandle safeNCryptProviderHandle = provider.OpenStorageProvider(); SafeNCryptKeyHandle phKey; using (SafeUnicodeStringHandle safeUnicodeStringHandle = new SafeUnicodeStringHandle(password)) { global::Interop.NCrypt.NCryptBuffer* ptr = stackalloc global::Interop.NCrypt.NCryptBuffer[1]; *ptr = new global::Interop.NCrypt.NCryptBuffer { BufferType = global::Interop.NCrypt.BufferType.PkcsSecret, cbBuffer = checked(2 * (password.Length + 1)), pvBuffer = safeUnicodeStringHandle.DangerousGetHandle() }; if (ptr->pvBuffer == IntPtr.Zero) { ptr->cbBuffer = 0; } global::Interop.NCrypt.NCryptBufferDesc nCryptBufferDesc = default(global::Interop.NCrypt.NCryptBufferDesc); nCryptBufferDesc.cBuffers = 1; nCryptBufferDesc.pBuffers = (IntPtr)ptr; nCryptBufferDesc.ulVersion = 0; global::Interop.NCrypt.NCryptBufferDesc pParameterList = nCryptBufferDesc; global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptImportKey(safeNCryptProviderHandle, IntPtr.Zero, "PKCS8_PRIVATEKEY", ref pParameterList, out phKey, ref MemoryMarshal.GetReference(keyBlob), keyBlob.Length, 0); if (errorCode != 0) { phKey.Dispose(); throw errorCode.ToCryptographicException(); } } CngKey cngKey = new CngKey(safeNCryptProviderHandle, phKey); cngKey.IsEphemeral = true; return cngKey; } internal static CngKey Import(byte[] keyBlob, string curveName, CngKeyBlobFormat format, CngProvider provider) { if (keyBlob == null) { throw new ArgumentNullException("keyBlob"); } return Import(new ReadOnlySpan(keyBlob), curveName, format, provider); } internal static CngKey Import(ReadOnlySpan keyBlob, string curveName, CngKeyBlobFormat format, CngProvider provider) { if (format == null) { throw new ArgumentNullException("format"); } if (provider == null) { throw new ArgumentNullException("provider"); } SafeNCryptProviderHandle safeNCryptProviderHandle = provider.OpenStorageProvider(); SafeNCryptKeyHandle phKey = null; if (curveName == null) { global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptImportKey(safeNCryptProviderHandle, IntPtr.Zero, format.Format, IntPtr.Zero, out phKey, ref MemoryMarshal.GetReference(keyBlob), keyBlob.Length, 0); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } } else { phKey = ECCng.ImportKeyBlob(format.Format, keyBlob, curveName, safeNCryptProviderHandle); } CngKey cngKey = new CngKey(safeNCryptProviderHandle, phKey); cngKey.IsEphemeral = format != CngKeyBlobFormat.OpaqueTransportBlob; return cngKey; } public byte[] Export(CngKeyBlobFormat format) { if (format == null) { throw new ArgumentNullException("format"); } global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptExportKey(_keyHandle, IntPtr.Zero, format.Format, IntPtr.Zero, null, 0, out var pcbResult, 0); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } byte[] array = new byte[pcbResult]; errorCode = global::Interop.NCrypt.NCryptExportKey(_keyHandle, IntPtr.Zero, format.Format, IntPtr.Zero, array, array.Length, out pcbResult, 0); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } Array.Resize(ref array, pcbResult); return array; } internal bool TryExportKeyBlob(string blobType, Span destination, out int bytesWritten) { Span span = default(Span); global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptExportKey(_keyHandle, IntPtr.Zero, blobType, IntPtr.Zero, ref MemoryMarshal.GetReference(span), span.Length, out var pcbResult, 0); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } if (pcbResult > destination.Length) { bytesWritten = 0; return false; } errorCode = global::Interop.NCrypt.NCryptExportKey(_keyHandle, IntPtr.Zero, blobType, IntPtr.Zero, ref MemoryMarshal.GetReference(destination), destination.Length, out pcbResult, 0); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } bytesWritten = pcbResult; return true; } internal byte[] ExportPkcs8KeyBlob(ReadOnlySpan password, int kdfCount) { int bytesWritten; byte[] allocated; bool flag = ExportPkcs8KeyBlob(allocate: true, _keyHandle, password, kdfCount, Span.Empty, out bytesWritten, out allocated); return allocated; } internal bool TryExportPkcs8KeyBlob(ReadOnlySpan password, int kdfCount, Span destination, out int bytesWritten) { byte[] allocated; return ExportPkcs8KeyBlob(allocate: false, _keyHandle, password, kdfCount, destination, out bytesWritten, out allocated); } internal unsafe static bool ExportPkcs8KeyBlob(bool allocate, SafeNCryptKeyHandle keyHandle, ReadOnlySpan password, int kdfCount, Span destination, out int bytesWritten, out byte[] allocated) { using SafeUnicodeStringHandle safeUnicodeStringHandle = new SafeUnicodeStringHandle(password); fixed (byte* ptr2 = s_pkcs12TripleDesOidBytes) { global::Interop.NCrypt.NCryptBuffer* ptr = stackalloc global::Interop.NCrypt.NCryptBuffer[3]; global::Interop.NCrypt.PBE_PARAMS pBE_PARAMS = default(global::Interop.NCrypt.PBE_PARAMS); Span data = new Span(pBE_PARAMS.rgbSalt, 8); RandomNumberGenerator.Fill(data); pBE_PARAMS.Params.cbSalt = data.Length; pBE_PARAMS.Params.iIterations = kdfCount; *ptr = new global::Interop.NCrypt.NCryptBuffer { BufferType = global::Interop.NCrypt.BufferType.PkcsSecret, cbBuffer = checked(2 * (password.Length + 1)), pvBuffer = safeUnicodeStringHandle.DangerousGetHandle() }; if (ptr->pvBuffer == IntPtr.Zero) { ptr->cbBuffer = 0; } ptr[1] = new global::Interop.NCrypt.NCryptBuffer { BufferType = global::Interop.NCrypt.BufferType.PkcsAlgOid, cbBuffer = s_pkcs12TripleDesOidBytes.Length, pvBuffer = (IntPtr)ptr2 }; ptr[2] = new global::Interop.NCrypt.NCryptBuffer { BufferType = global::Interop.NCrypt.BufferType.PkcsAlgParam, cbBuffer = sizeof(global::Interop.NCrypt.PBE_PARAMS), pvBuffer = (IntPtr)(&pBE_PARAMS) }; global::Interop.NCrypt.NCryptBufferDesc nCryptBufferDesc = default(global::Interop.NCrypt.NCryptBufferDesc); nCryptBufferDesc.cBuffers = 3; nCryptBufferDesc.pBuffers = (IntPtr)ptr; nCryptBufferDesc.ulVersion = 0; global::Interop.NCrypt.NCryptBufferDesc pParameterList = nCryptBufferDesc; global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptExportKey(keyHandle, IntPtr.Zero, "PKCS8_PRIVATEKEY", ref pParameterList, ref MemoryMarshal.GetReference(default(Span)), 0, out var pcbResult, 0); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } allocated = null; if (allocate) { allocated = new byte[pcbResult]; destination = allocated; } else if (pcbResult > destination.Length) { bytesWritten = 0; return false; } errorCode = global::Interop.NCrypt.NCryptExportKey(keyHandle, IntPtr.Zero, "PKCS8_PRIVATEKEY", ref pParameterList, ref MemoryMarshal.GetReference(destination), destination.Length, out pcbResult, 0); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } if (allocate && pcbResult != destination.Length) { byte[] array = new byte[pcbResult]; destination.Slice(0, pcbResult).CopyTo(array); Array.Clear(allocated, 0, pcbResult); allocated = array; } bytesWritten = pcbResult; return true; } } public void Delete() { global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptDeleteKey(_keyHandle, 0); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } _keyHandle.SetHandleAsInvalid(); Dispose(); } public static bool Exists(string keyName) { return Exists(keyName, CngProvider.MicrosoftSoftwareKeyStorageProvider); } public static bool Exists(string keyName, CngProvider provider) { return Exists(keyName, provider, CngKeyOpenOptions.None); } public static bool Exists(string keyName, CngProvider provider, CngKeyOpenOptions options) { if (keyName == null) { throw new ArgumentNullException("keyName"); } if (provider == null) { throw new ArgumentNullException("provider"); } using SafeNCryptProviderHandle hProvider = provider.OpenStorageProvider(); SafeNCryptKeyHandle phKey = null; try { global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptOpenKey(hProvider, out phKey, keyName, 0, options); return errorCode switch { global::Interop.NCrypt.ErrorCode.NTE_BAD_KEYSET => false, global::Interop.NCrypt.ErrorCode.ERROR_SUCCESS => true, _ => throw errorCode.ToCryptographicException(), }; } finally { phKey?.Dispose(); } } public static CngKey Open(string keyName) { return Open(keyName, CngProvider.MicrosoftSoftwareKeyStorageProvider); } public static CngKey Open(string keyName, CngProvider provider) { return Open(keyName, provider, CngKeyOpenOptions.None); } public static CngKey Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { if (keyName == null) { throw new ArgumentNullException("keyName"); } if (provider == null) { throw new ArgumentNullException("provider"); } SafeNCryptProviderHandle safeNCryptProviderHandle = provider.OpenStorageProvider(); SafeNCryptKeyHandle phKey; global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.NCryptOpenKey(safeNCryptProviderHandle, out phKey, keyName, 0, openOptions); if (errorCode != 0) { throw errorCode.ToCryptographicException(); } return new CngKey(safeNCryptProviderHandle, phKey); } public static CngKey Open(SafeNCryptKeyHandle keyHandle, CngKeyHandleOpenOptions keyHandleOpenOptions) { if (keyHandle == null) { throw new ArgumentNullException("keyHandle"); } if (keyHandle.IsClosed || keyHandle.IsInvalid) { throw new ArgumentException(System.SR.Cryptography_OpenInvalidHandle, "keyHandle"); } SafeNCryptKeyHandle keyHandle2 = keyHandle.Duplicate(); SafeNCryptProviderHandle safeNCryptProviderHandle = new SafeNCryptProviderHandle(); IntPtr propertyAsIntPtr = keyHandle.GetPropertyAsIntPtr("Provider Handle", CngPropertyOptions.None); safeNCryptProviderHandle.SetHandleValue(propertyAsIntPtr); CngKey cngKey = null; try { cngKey = new CngKey(safeNCryptProviderHandle, keyHandle2); bool flag = (keyHandleOpenOptions & CngKeyHandleOpenOptions.EphemeralKey) == CngKeyHandleOpenOptions.EphemeralKey; if (!cngKey.IsEphemeral && flag) { cngKey.IsEphemeral = true; } else if (cngKey.IsEphemeral && !flag) { throw new ArgumentException(System.SR.Cryptography_OpenEphemeralKeyHandleWithoutEphemeralFlag, "keyHandleOpenOptions"); } } catch { cngKey?.Dispose(); throw; } return cngKey; } } public sealed class CngKeyBlobFormat : IEquatable { private static CngKeyBlobFormat s_eccPrivate; private static CngKeyBlobFormat s_eccPublic; private static CngKeyBlobFormat s_eccFullPrivate; private static CngKeyBlobFormat s_eccFullPublic; private static CngKeyBlobFormat s_genericPrivate; private static CngKeyBlobFormat s_genericPublic; private static CngKeyBlobFormat s_opaqueTransport; private static CngKeyBlobFormat s_pkcs8Private; private readonly string _format; public string Format => _format; public static CngKeyBlobFormat EccPrivateBlob => s_eccPrivate ?? (s_eccPrivate = new CngKeyBlobFormat("ECCPRIVATEBLOB")); public static CngKeyBlobFormat EccPublicBlob => s_eccPublic ?? (s_eccPublic = new CngKeyBlobFormat("ECCPUBLICBLOB")); public static CngKeyBlobFormat EccFullPrivateBlob => s_eccFullPrivate ?? (s_eccFullPrivate = new CngKeyBlobFormat("ECCFULLPRIVATEBLOB")); public static CngKeyBlobFormat EccFullPublicBlob => s_eccFullPublic ?? (s_eccFullPublic = new CngKeyBlobFormat("ECCFULLPUBLICBLOB")); public static CngKeyBlobFormat GenericPrivateBlob => s_genericPrivate ?? (s_genericPrivate = new CngKeyBlobFormat("PRIVATEBLOB")); public static CngKeyBlobFormat GenericPublicBlob => s_genericPublic ?? (s_genericPublic = new CngKeyBlobFormat("PUBLICBLOB")); public static CngKeyBlobFormat OpaqueTransportBlob => s_opaqueTransport ?? (s_opaqueTransport = new CngKeyBlobFormat("OpaqueTransport")); public static CngKeyBlobFormat Pkcs8PrivateBlob => s_pkcs8Private ?? (s_pkcs8Private = new CngKeyBlobFormat("PKCS8_PRIVATEKEY")); public CngKeyBlobFormat(string format) { if (format == null) { throw new ArgumentNullException("format"); } if (format.Length == 0) { throw new ArgumentException(System.SR.Format(System.SR.Cryptography_InvalidKeyBlobFormat, format), "format"); } _format = format; } public static bool operator ==(CngKeyBlobFormat? left, CngKeyBlobFormat? right) { return left?.Equals(right) ?? ((object)right == null); } public static bool operator !=(CngKeyBlobFormat? left, CngKeyBlobFormat? right) { if ((object)left == null) { return (object)right != null; } return !left.Equals(right); } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj as CngKeyBlobFormat); } public bool Equals([NotNullWhen(true)] CngKeyBlobFormat? other) { if ((object)other == null) { return false; } return _format.Equals(other.Format); } public override int GetHashCode() { return _format.GetHashCode(); } public override string ToString() { return _format; } } [Flags] public enum CngKeyCreationOptions { None = 0, MachineKey = 0x20, OverwriteExistingKey = 0x80 } public sealed class CngKeyCreationParameters { private CngProvider _provider; public CngExportPolicies? ExportPolicy { get; set; } public CngKeyCreationOptions KeyCreationOptions { get; set; } public CngKeyUsages? KeyUsage { get; set; } public CngPropertyCollection Parameters { get; private set; } public IntPtr ParentWindowHandle { get; set; } public CngProvider Provider { get { return _provider; } set { if (value == null) { throw new ArgumentNullException("value"); } _provider = value; } } public CngUIPolicy? UIPolicy { get; set; } public CngKeyCreationParameters() { Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider; Parameters = new CngPropertyCollection(); } } [Flags] public enum CngKeyHandleOpenOptions { None = 0, EphemeralKey = 1 } [Flags] public enum CngKeyOpenOptions { None = 0, UserKey = 0, MachineKey = 0x20, Silent = 0x40 } [Flags] public enum CngKeyUsages { None = 0, Decryption = 1, Signing = 2, KeyAgreement = 4, AllUsages = 0xFFFFFF } internal static class CngPkcs8 { internal struct Pkcs8Response { internal CngKey Key; internal string GetAlgorithmGroup() { return Key.AlgorithmGroup.AlgorithmGroup; } internal void FreeKey() { Key.Dispose(); } } private static readonly PbeParameters s_platformParameters = new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 1); private static Pkcs8Response ImportPkcs8(ReadOnlySpan keyBlob) { CngKey cngKey = CngKey.Import(keyBlob, CngKeyBlobFormat.Pkcs8PrivateBlob); cngKey.ExportPolicy = CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport; Pkcs8Response result = default(Pkcs8Response); result.Key = cngKey; return result; } private static Pkcs8Response ImportPkcs8(ReadOnlySpan keyBlob, ReadOnlySpan password) { CngKey cngKey = CngKey.ImportEncryptedPkcs8(keyBlob, password); cngKey.ExportPolicy = CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport; Pkcs8Response result = default(Pkcs8Response); result.Key = cngKey; return result; } internal static bool IsPlatformScheme(PbeParameters pbeParameters) { if (pbeParameters.EncryptionAlgorithm == s_platformParameters.EncryptionAlgorithm) { return pbeParameters.HashAlgorithm == s_platformParameters.HashAlgorithm; } return false; } internal static byte[] ExportEncryptedPkcs8PrivateKey(AsymmetricAlgorithm key, ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } System.Security.Cryptography.PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, ReadOnlySpan.Empty, passwordBytes); if (passwordBytes.Length == 0) { return key.ExportEncryptedPkcs8PrivateKey(ReadOnlySpan.Empty, pbeParameters); } AsnWriter asnWriter = RewriteEncryptedPkcs8PrivateKey(key, passwordBytes, pbeParameters); return asnWriter.Encode(); } internal static bool TryExportEncryptedPkcs8PrivateKey(AsymmetricAlgorithm key, ReadOnlySpan passwordBytes, PbeParameters pbeParameters, Span destination, out int bytesWritten) { if (passwordBytes.Length == 0) { return key.TryExportEncryptedPkcs8PrivateKey(ReadOnlySpan.Empty, pbeParameters, destination, out bytesWritten); } AsnWriter asnWriter = RewriteEncryptedPkcs8PrivateKey(key, passwordBytes, pbeParameters); return asnWriter.TryEncode(destination, out bytesWritten); } internal static byte[] ExportEncryptedPkcs8PrivateKey(AsymmetricAlgorithm key, ReadOnlySpan password, PbeParameters pbeParameters) { AsnWriter asnWriter = RewriteEncryptedPkcs8PrivateKey(key, password, pbeParameters); return asnWriter.Encode(); } internal static bool TryExportEncryptedPkcs8PrivateKey(AsymmetricAlgorithm key, ReadOnlySpan password, PbeParameters pbeParameters, Span destination, out int bytesWritten) { AsnWriter asnWriter = RewriteEncryptedPkcs8PrivateKey(key, password, pbeParameters); return asnWriter.TryEncode(destination, out bytesWritten); } internal static Pkcs8Response ImportPkcs8PrivateKey(ReadOnlySpan source, out int bytesRead) { int bytesConsumed; try { AsnDecoder.ReadEncodedValue(source, AsnEncodingRules.BER, out var _, out var _, out bytesConsumed); } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } bytesRead = bytesConsumed; ReadOnlySpan readOnlySpan = source.Slice(0, bytesConsumed); try { return ImportPkcs8(readOnlySpan); } catch (CryptographicException) { AsnWriter asnWriter = RewritePkcs8ECPrivateKeyWithZeroPublicKey(readOnlySpan); if (asnWriter == null) { throw; } return ImportPkcs8(asnWriter); } catch (AsnContentException inner2) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner2); } } private static Pkcs8Response ImportPkcs8(AsnWriter pkcs8Writer) { byte[] array = System.Security.Cryptography.CryptoPool.Rent(pkcs8Writer.GetEncodedLength()); if (!pkcs8Writer.TryEncode(array, out var bytesWritten)) { throw new CryptographicException(); } Pkcs8Response result = ImportPkcs8(array.AsSpan(0, bytesWritten)); System.Security.Cryptography.CryptoPool.Return(array, bytesWritten); return result; } internal unsafe static Pkcs8Response ImportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, ReadOnlySpan source, out int bytesRead) { fixed (byte* pointer = &MemoryMarshal.GetReference(source)) { using MemoryManager memoryManager = new System.Buffers.PointerMemoryManager(pointer, source.Length); try { ArraySegment arraySegment = System.Security.Cryptography.KeyFormatHelper.DecryptPkcs8(passwordBytes, memoryManager.Memory, out bytesRead); Span span = arraySegment; try { return ImportPkcs8(span); } catch (CryptographicException inner) { AsnWriter asnWriter = RewritePkcs8ECPrivateKeyWithZeroPublicKey(span); if (asnWriter == null) { throw new CryptographicException(System.SR.Cryptography_Pkcs8_EncryptedReadFailed, inner); } try { return ImportPkcs8(asnWriter); } catch (CryptographicException) { throw new CryptographicException(System.SR.Cryptography_Pkcs8_EncryptedReadFailed, inner); } } finally { System.Security.Cryptography.CryptoPool.Return(arraySegment); } } catch (AsnContentException inner2) { throw new CryptographicException(System.SR.Cryptography_Pkcs8_EncryptedReadFailed, inner2); } } } internal unsafe static Pkcs8Response ImportEncryptedPkcs8PrivateKey(ReadOnlySpan password, ReadOnlySpan source, out int bytesRead) { try { AsnDecoder.ReadEncodedValue(source, AsnEncodingRules.BER, out var _, out var _, out var bytesConsumed); source = source.Slice(0, bytesConsumed); fixed (byte* pointer = &MemoryMarshal.GetReference(source)) { using MemoryManager memoryManager = new System.Buffers.PointerMemoryManager(pointer, source.Length); try { bytesRead = bytesConsumed; return ImportPkcs8(source, password); } catch (CryptographicException) { } int bytesRead2; ArraySegment arraySegment = System.Security.Cryptography.KeyFormatHelper.DecryptPkcs8(password, memoryManager.Memory.Slice(0, bytesConsumed), out bytesRead2); Span span = arraySegment; try { if (bytesRead2 != bytesConsumed) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } bytesRead = bytesConsumed; return ImportPkcs8(span); } catch (CryptographicException inner) { AsnWriter asnWriter = RewritePkcs8ECPrivateKeyWithZeroPublicKey(span); if (asnWriter == null) { throw new CryptographicException(System.SR.Cryptography_Pkcs8_EncryptedReadFailed, inner); } try { bytesRead = bytesConsumed; return ImportPkcs8(asnWriter); } catch (CryptographicException) { throw new CryptographicException(System.SR.Cryptography_Pkcs8_EncryptedReadFailed, inner); } } finally { System.Security.Cryptography.CryptoPool.Return(arraySegment); } } } catch (AsnContentException inner2) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner2); } } private static AsnWriter RewriteEncryptedPkcs8PrivateKey(AsymmetricAlgorithm key, ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { byte[] array = System.Security.Cryptography.CryptoPool.Rent(key.KeySize); int bytesWritten = 0; Span span = stackalloc char[22]; try { FillRandomAsciiString(span); while (!key.TryExportEncryptedPkcs8PrivateKey(span, s_platformParameters, array, out bytesWritten)) { int num = array.Length; byte[] array2 = array; array = System.Security.Cryptography.CryptoPool.Rent(checked(num * 2)); System.Security.Cryptography.CryptoPool.Return(array2, bytesWritten); } return System.Security.Cryptography.KeyFormatHelper.ReencryptPkcs8(span, array.AsMemory(0, bytesWritten), passwordBytes, pbeParameters); } finally { span.Clear(); System.Security.Cryptography.CryptoPool.Return(array, bytesWritten); } } private static AsnWriter RewriteEncryptedPkcs8PrivateKey(AsymmetricAlgorithm key, ReadOnlySpan password, PbeParameters pbeParameters) { byte[] array = System.Security.Cryptography.CryptoPool.Rent(key.KeySize); int bytesWritten = 0; try { while (!key.TryExportEncryptedPkcs8PrivateKey(password, s_platformParameters, array, out bytesWritten)) { int num = array.Length; byte[] array2 = array; array = System.Security.Cryptography.CryptoPool.Rent(checked(num * 2)); System.Security.Cryptography.CryptoPool.Return(array2, bytesWritten); } return System.Security.Cryptography.KeyFormatHelper.ReencryptPkcs8(password, array.AsMemory(0, bytesWritten), password, pbeParameters); } finally { System.Security.Cryptography.CryptoPool.Return(array, bytesWritten); } } private unsafe static AsnWriter RewritePkcs8ECPrivateKeyWithZeroPublicKey(ReadOnlySpan source) { fixed (byte* pointer = &MemoryMarshal.GetReference(source)) { using MemoryManager memoryManager = new System.Buffers.PointerMemoryManager(pointer, source.Length); System.Security.Cryptography.Asn1.PrivateKeyInfoAsn privateKeyInfoAsn = System.Security.Cryptography.Asn1.PrivateKeyInfoAsn.Decode(memoryManager.Memory, AsnEncodingRules.BER); System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn algId = privateKeyInfoAsn.PrivateKeyAlgorithm; if (algId.Algorithm != "1.2.840.10045.2.1") { return null; } System.Security.Cryptography.Asn1.ECPrivateKey key = System.Security.Cryptography.Asn1.ECPrivateKey.Decode(privateKeyInfoAsn.PrivateKey, AsnEncodingRules.BER); System.Security.Cryptography.EccKeyFormatHelper.FromECPrivateKey(key, in algId, out var ret); fixed (byte* ptr = ret.D) { try { if (!ret.Curve.IsExplicit || ret.Q.X != null || ret.Q.Y != null) { return null; } byte[] array = new byte[ret.D.Length]; ret.Q.Y = array; ret.Q.X = array; return System.Security.Cryptography.EccKeyFormatHelper.WritePkcs8PrivateKey(ret, privateKeyInfoAsn.Attributes); } finally { Array.Clear(ret.D); } } } } private static void FillRandomAsciiString(Span destination) { Span data = stackalloc byte[destination.Length]; RandomNumberGenerator.Fill(data); for (int i = 0; i < data.Length; i++) { destination[i] = (char)(33 + (data[i] & 0x3F)); } } } public struct CngProperty : IEquatable { private readonly byte[] _value; private int? _lazyHashCode; public string Name { get; private set; } public CngPropertyOptions Options { get; private set; } public CngProperty(string name, byte[]? value, CngPropertyOptions options) { this = default(CngProperty); if (name == null) { throw new ArgumentNullException("name"); } Name = name; Options = options; _lazyHashCode = null; _value = value?.CloneByteArray(); } public byte[]? GetValue() { if (_value != null) { return _value.CloneByteArray(); } return null; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is CngProperty) { return Equals((CngProperty)obj); } return false; } public bool Equals(CngProperty other) { if (!string.Equals(Name, other.Name, StringComparison.Ordinal)) { return false; } if (Options != other.Options) { return false; } if (_value == null) { return other._value == null; } if (other._value == null) { return false; } if (_value.Length != other._value.Length) { return false; } for (int i = 0; i < _value.Length; i++) { if (_value[i] != other._value[i]) { return false; } } return true; } public override int GetHashCode() { if (!_lazyHashCode.HasValue) { int num = Name.GetHashCode() ^ Options.GetHashCode(); if (_value != null) { for (int i = 0; i < _value.Length; i++) { int num2 = _value[i] << i % 4 * 8; num ^= num2; } } _lazyHashCode = num; } return _lazyHashCode.Value; } public static bool operator ==(CngProperty left, CngProperty right) { return left.Equals(right); } public static bool operator !=(CngProperty left, CngProperty right) { return !left.Equals(right); } internal byte[] GetValueWithoutCopying() { return _value; } } public sealed class CngPropertyCollection : Collection { } [Flags] public enum CngPropertyOptions { None = 0, CustomProperty = 0x40000000, Persist = int.MinValue } public sealed class CngProvider : IEquatable { private static CngProvider s_msPlatformKsp; private static CngProvider s_msSmartCardKsp; private static CngProvider s_msSoftwareKsp; private readonly string _provider; public string Provider => _provider; public static CngProvider MicrosoftPlatformCryptoProvider => s_msPlatformKsp ?? (s_msPlatformKsp = new CngProvider("Microsoft Platform Crypto Provider")); public static CngProvider MicrosoftSmartCardKeyStorageProvider => s_msSmartCardKsp ?? (s_msSmartCardKsp = new CngProvider("Microsoft Smart Card Key Storage Provider")); public static CngProvider MicrosoftSoftwareKeyStorageProvider => s_msSoftwareKsp ?? (s_msSoftwareKsp = new CngProvider("Microsoft Software Key Storage Provider")); public CngProvider(string provider) { if (provider == null) { throw new ArgumentNullException("provider"); } if (provider.Length == 0) { throw new ArgumentException(System.SR.Format(System.SR.Cryptography_InvalidProviderName, provider), "provider"); } _provider = provider; } public static bool operator ==(CngProvider? left, CngProvider? right) { return left?.Equals(right) ?? ((object)right == null); } public static bool operator !=(CngProvider? left, CngProvider? right) { if ((object)left == null) { return (object)right != null; } return !left.Equals(right); } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj as CngProvider); } public bool Equals([NotNullWhen(true)] CngProvider? other) { if ((object)other == null) { return false; } return _provider.Equals(other.Provider); } public override int GetHashCode() { return _provider.GetHashCode(); } public override string ToString() { return _provider.ToString(); } } public sealed class CngUIPolicy { public CngUIProtectionLevels ProtectionLevel { get; private set; } public string? FriendlyName { get; private set; } public string? Description { get; private set; } public string? UseContext { get; private set; } public string? CreationTitle { get; private set; } public CngUIPolicy(CngUIProtectionLevels protectionLevel) : this(protectionLevel, null) { } public CngUIPolicy(CngUIProtectionLevels protectionLevel, string? friendlyName) : this(protectionLevel, friendlyName, null) { } public CngUIPolicy(CngUIProtectionLevels protectionLevel, string? friendlyName, string? description) : this(protectionLevel, friendlyName, description, null) { } public CngUIPolicy(CngUIProtectionLevels protectionLevel, string? friendlyName, string? description, string? useContext) : this(protectionLevel, friendlyName, description, useContext, null) { } public CngUIPolicy(CngUIProtectionLevels protectionLevel, string? friendlyName, string? description, string? useContext, string? creationTitle) { ProtectionLevel = protectionLevel; FriendlyName = friendlyName; Description = description; UseContext = useContext; CreationTitle = creationTitle; } } [Flags] public enum CngUIProtectionLevels { None = 0, ProtectKey = 1, ForceHighProtection = 2 } public sealed class DSACng : DSA { private CngAlgorithmCore _core = new CngAlgorithmCore("DSACng"); private readonly CngAlgorithm _dsnCng = new CngAlgorithm("DSA"); private static readonly KeySizes[] s_legalKeySizes = new KeySizes[1] { new KeySizes(512, 3072, 64) }; private static readonly int s_defaultKeySize = (Supports2048KeySize() ? 2048 : 1024); public CngKey Key { get { return _core.GetOrGenerateKey(KeySize, _dsnCng); } private set { if (value.AlgorithmGroup != CngAlgorithmGroup.Dsa) { throw new ArgumentException(System.SR.Cryptography_ArgDSARequiresDSAKey, "value"); } _core.SetKey(value); ForceSetKeySize(value.KeySize); } } public override KeySizes[] LegalKeySizes => base.LegalKeySizes; public override string SignatureAlgorithm => "DSA"; public override string? KeyExchangeAlgorithm => null; public DSACng(CngKey key) { if (key == null) { throw new ArgumentNullException("key"); } if (key.AlgorithmGroup != CngAlgorithmGroup.Dsa) { throw new ArgumentException(System.SR.Cryptography_ArgDSARequiresDSAKey, "key"); } Key = CngAlgorithmCore.Duplicate(key); } protected override void Dispose(bool disposing) { _core.Dispose(); } private void ThrowIfDisposed() { _core.ThrowIfDisposed(); } private byte[] ExportKeyBlob(bool includePrivateParameters) { CngKeyBlobFormat format = (includePrivateParameters ? CngKeyBlobFormat.GenericPrivateBlob : CngKeyBlobFormat.GenericPublicBlob); return Key.Export(format); } private void ImportKeyBlob(byte[] dsaBlob, bool includePrivate) { CngKeyBlobFormat format = (includePrivate ? CngKeyBlobFormat.GenericPrivateBlob : CngKeyBlobFormat.GenericPublicBlob); CngKey cngKey = CngKey.Import(dsaBlob, format); cngKey.ExportPolicy |= CngExportPolicies.AllowPlaintextExport; Key = cngKey; } public override bool TryExportPkcs8PrivateKey(Span destination, out int bytesWritten) { return Key.TryExportKeyBlob("PKCS8_PRIVATEKEY", destination, out bytesWritten); } private byte[] ExportEncryptedPkcs8(ReadOnlySpan pkcs8Password, int kdfCount) { return Key.ExportPkcs8KeyBlob(pkcs8Password, kdfCount); } private bool TryExportEncryptedPkcs8(ReadOnlySpan pkcs8Password, int kdfCount, Span destination, out int bytesWritten) { return Key.TryExportPkcs8KeyBlob(pkcs8Password, kdfCount, destination, out bytesWritten); } private SafeNCryptKeyHandle GetDuplicatedKeyHandle() { return Key.Handle; } public DSACng() : this(s_defaultKeySize) { } public DSACng(int keySize) { LegalKeySizesValue = s_legalKeySizes; KeySize = keySize; } protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { return CngCommon.HashData(data, offset, count, hashAlgorithm); } protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { return CngCommon.HashData(data, hashAlgorithm); } protected override bool TryHashData(ReadOnlySpan source, Span destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) { return CngCommon.TryHashData(source, destination, hashAlgorithm, out bytesWritten); } private void ForceSetKeySize(int newKeySize) { KeySizeValue = newKeySize; } private static bool Supports2048KeySize() { Version version = Environment.OSVersion.Version; return version.Major > 6 || (version.Major == 6 && version.Minor >= 2); } public override void ImportParameters(DSAParameters parameters) { if (parameters.P == null || parameters.Q == null || parameters.G == null || parameters.Y == null) { throw new ArgumentException(System.SR.Cryptography_InvalidDsaParameters_MissingFields); } if (parameters.J != null && parameters.J.Length >= parameters.P.Length) { throw new ArgumentException(System.SR.Cryptography_InvalidDsaParameters_MismatchedPJ); } bool flag = parameters.X != null; int num = parameters.P.Length; int num2 = num * 8; if (parameters.G.Length != num || parameters.Y.Length != num) { throw new ArgumentException(System.SR.Cryptography_InvalidDsaParameters_MismatchedPGY); } if (flag && parameters.X.Length != parameters.Q.Length) { throw new ArgumentException(System.SR.Cryptography_InvalidDsaParameters_MismatchedQX); } byte[] blob; if (num2 <= 1024) { GenerateV1DsaBlob(out blob, parameters, num, flag); } else { GenerateV2DsaBlob(out blob, parameters, num, flag); } ImportKeyBlob(blob, flag); } public override void ImportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, ReadOnlySpan source, out int bytesRead) { ThrowIfDisposed(); base.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead); } public override void ImportEncryptedPkcs8PrivateKey(ReadOnlySpan password, ReadOnlySpan source, out int bytesRead) { ThrowIfDisposed(); base.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead); } public override byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } return CngPkcs8.ExportEncryptedPkcs8PrivateKey(this, passwordBytes, pbeParameters); } public override byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan password, PbeParameters pbeParameters) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } System.Security.Cryptography.PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, password, ReadOnlySpan.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return ExportEncryptedPkcs8(password, pbeParameters.IterationCount); } return CngPkcs8.ExportEncryptedPkcs8PrivateKey(this, password, pbeParameters); } public override bool TryExportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, PbeParameters pbeParameters, Span destination, out int bytesWritten) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } System.Security.Cryptography.PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, ReadOnlySpan.Empty, passwordBytes); return CngPkcs8.TryExportEncryptedPkcs8PrivateKey(this, passwordBytes, pbeParameters, destination, out bytesWritten); } public override bool TryExportEncryptedPkcs8PrivateKey(ReadOnlySpan password, PbeParameters pbeParameters, Span destination, out int bytesWritten) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } System.Security.Cryptography.PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, password, ReadOnlySpan.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return TryExportEncryptedPkcs8(password, pbeParameters.IterationCount, destination, out bytesWritten); } return CngPkcs8.TryExportEncryptedPkcs8PrivateKey(this, password, pbeParameters, destination, out bytesWritten); } private unsafe static void GenerateV1DsaBlob(out byte[] blob, DSAParameters parameters, int cbKey, bool includePrivate) { int num = sizeof(global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB) + cbKey + cbKey + cbKey; if (includePrivate) { num += 20; } blob = new byte[num]; fixed (byte* ptr = &blob[0]) { global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB* ptr2 = (global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB*)ptr; ptr2->Magic = (includePrivate ? global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC : global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC); ptr2->cbKey = cbKey; int offset = 8; if (parameters.Seed != null) { if (parameters.Seed.Length != 20) { throw new ArgumentException(System.SR.Cryptography_InvalidDsaParameters_SeedRestriction_ShortKey); } global::Interop.BCrypt.EmitBigEndian(blob, ref offset, parameters.Counter); global::Interop.BCrypt.Emit(blob, ref offset, parameters.Seed); } else { global::Interop.BCrypt.EmitByte(blob, ref offset, byte.MaxValue, 24); } if (parameters.Q.Length != 20) { throw new ArgumentException(System.SR.Cryptography_InvalidDsaParameters_QRestriction_ShortKey); } global::Interop.BCrypt.Emit(blob, ref offset, parameters.Q); global::Interop.BCrypt.Emit(blob, ref offset, parameters.P); global::Interop.BCrypt.Emit(blob, ref offset, parameters.G); global::Interop.BCrypt.Emit(blob, ref offset, parameters.Y); if (includePrivate) { global::Interop.BCrypt.Emit(blob, ref offset, parameters.X); } } } private unsafe static void GenerateV2DsaBlob(out byte[] blob, DSAParameters parameters, int cbKey, bool includePrivateParameters) { int num = sizeof(global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB_V2) + ((parameters.Seed == null) ? parameters.Q.Length : parameters.Seed.Length) + parameters.Q.Length + parameters.P.Length + parameters.G.Length + parameters.Y.Length + (includePrivateParameters ? parameters.X.Length : 0); blob = new byte[num]; fixed (byte* ptr = &blob[0]) { global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB_V2* ptr2 = (global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB_V2*)ptr; ptr2->Magic = (includePrivateParameters ? global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC_V2 : global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC_V2); ptr2->cbKey = cbKey; ptr2->hashAlgorithm = parameters.Q.Length switch { 20 => global::Interop.BCrypt.HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA1, 32 => global::Interop.BCrypt.HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA256, 64 => global::Interop.BCrypt.HASHALGORITHM_ENUM.DSA_HASH_ALGORITHM_SHA512, _ => throw new PlatformNotSupportedException(System.SR.Cryptography_InvalidDsaParameters_QRestriction_LargeKey), }; ptr2->standardVersion = global::Interop.BCrypt.DSAFIPSVERSION_ENUM.DSA_FIPS186_3; int offset = sizeof(global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB_V2) - 4; if (parameters.Seed != null) { global::Interop.BCrypt.EmitBigEndian(blob, ref offset, parameters.Counter); ptr2->cbSeedLength = parameters.Seed.Length; ptr2->cbGroupSize = parameters.Q.Length; global::Interop.BCrypt.Emit(blob, ref offset, parameters.Seed); } else { global::Interop.BCrypt.EmitByte(blob, ref offset, byte.MaxValue, 4); int count = (ptr2->cbSeedLength = parameters.Q.Length); ptr2->cbGroupSize = parameters.Q.Length; global::Interop.BCrypt.EmitByte(blob, ref offset, byte.MaxValue, count); } global::Interop.BCrypt.Emit(blob, ref offset, parameters.Q); global::Interop.BCrypt.Emit(blob, ref offset, parameters.P); global::Interop.BCrypt.Emit(blob, ref offset, parameters.G); global::Interop.BCrypt.Emit(blob, ref offset, parameters.Y); if (includePrivateParameters) { global::Interop.BCrypt.Emit(blob, ref offset, parameters.X); } } } public unsafe override DSAParameters ExportParameters(bool includePrivateParameters) { byte[] array = ExportKeyBlob(includePrivateParameters); global::Interop.BCrypt.KeyBlobMagicNumber keyBlobMagicNumber = (global::Interop.BCrypt.KeyBlobMagicNumber)BitConverter.ToInt32(array, 0); CheckMagicValueOfKey(keyBlobMagicNumber, includePrivateParameters); DSAParameters result = default(DSAParameters); fixed (byte* ptr = array) { if (keyBlobMagicNumber == global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC || keyBlobMagicNumber == global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC) { if (array.Length < sizeof(global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB)) { throw global::Interop.NCrypt.ErrorCode.E_FAIL.ToCryptographicException(); } global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB* ptr2 = (global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB*)ptr; int offset = 8; result.Counter = BinaryPrimitives.ReadInt32BigEndian(global::Interop.BCrypt.Consume(array, ref offset, 4)); result.Seed = global::Interop.BCrypt.Consume(array, ref offset, 20); result.Q = global::Interop.BCrypt.Consume(array, ref offset, 20); result.P = global::Interop.BCrypt.Consume(array, ref offset, ptr2->cbKey); result.G = global::Interop.BCrypt.Consume(array, ref offset, ptr2->cbKey); result.Y = global::Interop.BCrypt.Consume(array, ref offset, ptr2->cbKey); if (includePrivateParameters) { result.X = global::Interop.BCrypt.Consume(array, ref offset, 20); } } else { if (array.Length < sizeof(global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB_V2)) { throw global::Interop.NCrypt.ErrorCode.E_FAIL.ToCryptographicException(); } global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB_V2* ptr3 = (global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB_V2*)ptr; int offset = sizeof(global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB_V2) - 4; result.Counter = BinaryPrimitives.ReadInt32BigEndian(global::Interop.BCrypt.Consume(array, ref offset, 4)); result.Seed = global::Interop.BCrypt.Consume(array, ref offset, ptr3->cbSeedLength); result.Q = global::Interop.BCrypt.Consume(array, ref offset, ptr3->cbGroupSize); result.P = global::Interop.BCrypt.Consume(array, ref offset, ptr3->cbKey); result.G = global::Interop.BCrypt.Consume(array, ref offset, ptr3->cbKey); result.Y = global::Interop.BCrypt.Consume(array, ref offset, ptr3->cbKey); if (includePrivateParameters) { result.X = global::Interop.BCrypt.Consume(array, ref offset, ptr3->cbGroupSize); } } if (result.Counter == -1) { result.Counter = 0; result.Seed = null; } return result; } } private static void CheckMagicValueOfKey(global::Interop.BCrypt.KeyBlobMagicNumber magic, bool includePrivateParameters) { if (includePrivateParameters) { if (magic != global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC && magic != global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC_V2) { throw new CryptographicException(System.SR.Cryptography_NotValidPrivateKey); } } else if (magic != global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC && magic != global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC_V2) { throw new CryptographicException(System.SR.Cryptography_NotValidPublicOrPrivateKey); } } public unsafe override byte[] CreateSignature(byte[] rgbHash) { if (rgbHash == null) { throw new ArgumentNullException("rgbHash"); } Span stackBuf = stackalloc byte[32]; ReadOnlySpan hash = AdjustHashSizeIfNecessary(rgbHash, stackBuf); using SafeNCryptKeyHandle keyHandle = GetDuplicatedKeyHandle(); return keyHandle.SignHash(hash, global::Interop.NCrypt.AsymmetricPaddingMode.None, null, hash.Length * 2); } public unsafe override bool TryCreateSignature(ReadOnlySpan hash, Span destination, out int bytesWritten) { Span stackBuf = stackalloc byte[32]; ReadOnlySpan hash2 = AdjustHashSizeIfNecessary(hash, stackBuf); using (SafeNCryptKeyHandle keyHandle = GetDuplicatedKeyHandle()) { if (!keyHandle.TrySignHash(hash2, destination, global::Interop.NCrypt.AsymmetricPaddingMode.None, null, out bytesWritten)) { bytesWritten = 0; return false; } } return true; } public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { if (rgbHash == null) { throw new ArgumentNullException("rgbHash"); } if (rgbSignature == null) { throw new ArgumentNullException("rgbSignature"); } return VerifySignature((ReadOnlySpan)rgbHash, (ReadOnlySpan)rgbSignature); } public unsafe override bool VerifySignature(ReadOnlySpan hash, ReadOnlySpan signature) { Span stackBuf = stackalloc byte[32]; ReadOnlySpan hash2 = AdjustHashSizeIfNecessary(hash, stackBuf); using SafeNCryptKeyHandle keyHandle = GetDuplicatedKeyHandle(); return keyHandle.VerifyHash(hash2, signature, global::Interop.NCrypt.AsymmetricPaddingMode.None, null); } private ReadOnlySpan AdjustHashSizeIfNecessary(ReadOnlySpan hash, Span stackBuf) { int num = ComputeQLength(); if (num == hash.Length) { return hash; } if (num < hash.Length) { return hash.Slice(0, num); } int num2 = num - hash.Length; stackBuf.Slice(0, num2).Clear(); hash.CopyTo(stackBuf.Slice(num2)); return stackBuf.Slice(0, num); } private unsafe int ComputeQLength() { byte[] array; using (GetDuplicatedKeyHandle()) { array = ExportKeyBlob(includePrivateParameters: false); } if (array.Length < sizeof(global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB_V2)) { return 20; } fixed (byte* ptr = array) { global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB_V2* ptr2 = (global::Interop.BCrypt.BCRYPT_DSA_KEY_BLOB_V2*)ptr; if (ptr2->Magic != global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_DSA_PUBLIC_MAGIC_V2 && ptr2->Magic != global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_DSA_PRIVATE_MAGIC_V2) { return 20; } return ptr2->cbGroupSize; } } } internal static class ECCng { internal static CngKey ImportKeyBlob(byte[] ecBlob, string curveName, bool includePrivateParameters) { CngKeyBlobFormat format = (includePrivateParameters ? CngKeyBlobFormat.EccPrivateBlob : CngKeyBlobFormat.EccPublicBlob); CngKey cngKey = CngKey.Import(ecBlob, curveName, format); cngKey.ExportPolicy |= CngExportPolicies.AllowPlaintextExport; return cngKey; } internal static CngKey ImportFullKeyBlob(byte[] ecBlob, bool includePrivateParameters) { CngKeyBlobFormat format = (includePrivateParameters ? CngKeyBlobFormat.EccFullPrivateBlob : CngKeyBlobFormat.EccFullPublicBlob); CngKey cngKey = CngKey.Import(ecBlob, format); cngKey.ExportPolicy |= CngExportPolicies.AllowPlaintextExport; return cngKey; } internal static byte[] ExportKeyBlob(CngKey key, bool includePrivateParameters) { CngKeyBlobFormat format = (includePrivateParameters ? CngKeyBlobFormat.EccPrivateBlob : CngKeyBlobFormat.EccPublicBlob); return key.Export(format); } internal static byte[] ExportFullKeyBlob(CngKey key, bool includePrivateParameters) { CngKeyBlobFormat format = (includePrivateParameters ? CngKeyBlobFormat.EccFullPrivateBlob : CngKeyBlobFormat.EccFullPublicBlob); return key.Export(format); } internal static byte[] ExportKeyBlob(CngKey key, bool includePrivateParameters, out CngKeyBlobFormat format, out string curveName) { curveName = key.GetCurveName(out var _); bool flag = false; if (string.IsNullOrEmpty(curveName)) { curveName = null; flag = true; format = (includePrivateParameters ? CngKeyBlobFormat.EccFullPrivateBlob : CngKeyBlobFormat.EccFullPublicBlob); } else { format = (includePrivateParameters ? CngKeyBlobFormat.EccPrivateBlob : CngKeyBlobFormat.EccPublicBlob); } byte[] array = key.Export(format); if (flag) { FixupGenericBlob(array); } return array; } private unsafe static void FixupGenericBlob(byte[] blob) { if (blob.Length <= sizeof(global::Interop.BCrypt.BCRYPT_ECCKEY_BLOB)) { return; } fixed (byte* ptr = blob) { global::Interop.BCrypt.BCRYPT_ECCKEY_BLOB* ptr2 = (global::Interop.BCrypt.BCRYPT_ECCKEY_BLOB*)ptr; switch (ptr2->Magic) { case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PUBLIC_P256_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PUBLIC_P384_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PUBLIC_P521_MAGIC: ptr2->Magic = global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PUBLIC_GENERIC_MAGIC; break; case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PRIVATE_P256_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PRIVATE_P384_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PRIVATE_P521_MAGIC: ptr2->Magic = global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PRIVATE_GENERIC_MAGIC; break; case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P256_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P384_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P521_MAGIC: ptr2->Magic = global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_GENERIC_MAGIC; break; case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P256_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P384_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P521_MAGIC: ptr2->Magic = global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_GENERIC_MAGIC; break; } } } internal unsafe static byte[] GetNamedCurveBlob(ref ECParameters parameters, bool ecdh) { bool flag = parameters.D != null; int num = sizeof(global::Interop.BCrypt.BCRYPT_ECCKEY_BLOB) + parameters.Q.X.Length + parameters.Q.Y.Length; if (flag) { num += parameters.D.Length; } byte[] array = new byte[num]; fixed (byte* ptr = &array[0]) { global::Interop.BCrypt.BCRYPT_ECCKEY_BLOB* ptr2 = (global::Interop.BCrypt.BCRYPT_ECCKEY_BLOB*)ptr; ptr2->Magic = (ecdh ? EcdhCurveNameToMagicNumber(parameters.Curve.Oid.FriendlyName, flag) : EcdsaCurveNameToMagicNumber(parameters.Curve.Oid.FriendlyName, flag)); ptr2->cbKey = parameters.Q.X.Length; int offset = sizeof(global::Interop.BCrypt.BCRYPT_ECCKEY_BLOB); global::Interop.BCrypt.Emit(array, ref offset, parameters.Q.X); global::Interop.BCrypt.Emit(array, ref offset, parameters.Q.Y); if (flag) { global::Interop.BCrypt.Emit(array, ref offset, parameters.D); } } return array; } internal unsafe static byte[] GetPrimeCurveBlob(ref ECParameters parameters, bool ecdh) { bool flag = parameters.D != null; ECCurve curve = parameters.Curve; int num = sizeof(global::Interop.BCrypt.BCRYPT_ECCFULLKEY_BLOB) + curve.Prime.Length + curve.A.Length + curve.B.Length + curve.G.X.Length + curve.G.Y.Length + curve.Order.Length + curve.Cofactor.Length + ((curve.Seed != null) ? curve.Seed.Length : 0) + parameters.Q.X.Length + parameters.Q.Y.Length; if (flag) { num += parameters.D.Length; } byte[] array = new byte[num]; fixed (byte* ptr = &array[0]) { global::Interop.BCrypt.BCRYPT_ECCFULLKEY_BLOB* ptr2 = (global::Interop.BCrypt.BCRYPT_ECCFULLKEY_BLOB*)ptr; ptr2->Version = 1; ptr2->Magic = ((!flag) ? (ecdh ? global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PUBLIC_GENERIC_MAGIC : global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_GENERIC_MAGIC) : (ecdh ? global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PRIVATE_GENERIC_MAGIC : global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_GENERIC_MAGIC)); ptr2->cbCofactor = curve.Cofactor.Length; ptr2->cbFieldLength = parameters.Q.X.Length; ptr2->cbSeed = ((curve.Seed != null) ? curve.Seed.Length : 0); ptr2->cbSubgroupOrder = curve.Order.Length; ptr2->CurveGenerationAlgId = GetHashAlgorithmId(curve.Hash); ptr2->CurveType = ConvertToCurveTypeEnum(curve.CurveType); int offset = sizeof(global::Interop.BCrypt.BCRYPT_ECCFULLKEY_BLOB); global::Interop.BCrypt.Emit(array, ref offset, curve.Prime); global::Interop.BCrypt.Emit(array, ref offset, curve.A); global::Interop.BCrypt.Emit(array, ref offset, curve.B); global::Interop.BCrypt.Emit(array, ref offset, curve.G.X); global::Interop.BCrypt.Emit(array, ref offset, curve.G.Y); global::Interop.BCrypt.Emit(array, ref offset, curve.Order); global::Interop.BCrypt.Emit(array, ref offset, curve.Cofactor); if (curve.Seed != null) { global::Interop.BCrypt.Emit(array, ref offset, curve.Seed); } global::Interop.BCrypt.Emit(array, ref offset, parameters.Q.X); global::Interop.BCrypt.Emit(array, ref offset, parameters.Q.Y); if (flag) { global::Interop.BCrypt.Emit(array, ref offset, parameters.D); } } return array; } internal unsafe static void ExportNamedCurveParameters(ref ECParameters ecParams, byte[] ecBlob, bool includePrivateParameters) { global::Interop.BCrypt.KeyBlobMagicNumber magic = (global::Interop.BCrypt.KeyBlobMagicNumber)BitConverter.ToInt32(ecBlob, 0); CheckMagicValueOfKey(magic, includePrivateParameters); if (ecBlob.Length < sizeof(global::Interop.BCrypt.BCRYPT_ECCKEY_BLOB)) { throw global::Interop.NCrypt.ErrorCode.E_FAIL.ToCryptographicException(); } fixed (byte* ptr = &ecBlob[0]) { global::Interop.BCrypt.BCRYPT_ECCKEY_BLOB* ptr2 = (global::Interop.BCrypt.BCRYPT_ECCKEY_BLOB*)ptr; int offset = sizeof(global::Interop.BCrypt.BCRYPT_ECCKEY_BLOB); ecParams.Q = new ECPoint { X = global::Interop.BCrypt.Consume(ecBlob, ref offset, ptr2->cbKey), Y = global::Interop.BCrypt.Consume(ecBlob, ref offset, ptr2->cbKey) }; if (includePrivateParameters) { ecParams.D = global::Interop.BCrypt.Consume(ecBlob, ref offset, ptr2->cbKey); } } } internal unsafe static void ExportPrimeCurveParameters(ref ECParameters ecParams, byte[] ecBlob, bool includePrivateParameters) { global::Interop.BCrypt.KeyBlobMagicNumber magic = (global::Interop.BCrypt.KeyBlobMagicNumber)BitConverter.ToInt32(ecBlob, 0); CheckMagicValueOfKey(magic, includePrivateParameters); if (ecBlob.Length < sizeof(global::Interop.BCrypt.BCRYPT_ECCFULLKEY_BLOB)) { throw global::Interop.NCrypt.ErrorCode.E_FAIL.ToCryptographicException(); } fixed (byte* ptr = &ecBlob[0]) { global::Interop.BCrypt.BCRYPT_ECCFULLKEY_BLOB* ptr2 = (global::Interop.BCrypt.BCRYPT_ECCFULLKEY_BLOB*)ptr; ECCurve curve = default(ECCurve); curve.CurveType = ConvertToCurveTypeEnum(ptr2->CurveType); curve.Hash = GetHashAlgorithmName(ptr2->CurveGenerationAlgId); int offset = sizeof(global::Interop.BCrypt.BCRYPT_ECCFULLKEY_BLOB); curve.Prime = global::Interop.BCrypt.Consume(ecBlob, ref offset, ptr2->cbFieldLength); curve.A = global::Interop.BCrypt.Consume(ecBlob, ref offset, ptr2->cbFieldLength); curve.B = global::Interop.BCrypt.Consume(ecBlob, ref offset, ptr2->cbFieldLength); curve.G = new ECPoint { X = global::Interop.BCrypt.Consume(ecBlob, ref offset, ptr2->cbFieldLength), Y = global::Interop.BCrypt.Consume(ecBlob, ref offset, ptr2->cbFieldLength) }; curve.Order = global::Interop.BCrypt.Consume(ecBlob, ref offset, ptr2->cbSubgroupOrder); curve.Cofactor = global::Interop.BCrypt.Consume(ecBlob, ref offset, ptr2->cbCofactor); curve.Seed = ((ptr2->cbSeed == 0) ? null : global::Interop.BCrypt.Consume(ecBlob, ref offset, ptr2->cbSeed)); ecParams.Q = new ECPoint { X = global::Interop.BCrypt.Consume(ecBlob, ref offset, ptr2->cbFieldLength), Y = global::Interop.BCrypt.Consume(ecBlob, ref offset, ptr2->cbFieldLength) }; if (includePrivateParameters) { ecParams.D = global::Interop.BCrypt.Consume(ecBlob, ref offset, ptr2->cbSubgroupOrder); } ecParams.Curve = curve; } } internal unsafe static byte[] GetPrimeCurveParameterBlob(ref ECCurve curve) { int num = sizeof(global::Interop.BCrypt.BCRYPT_ECC_PARAMETER_HEADER) + curve.Prime.Length + curve.A.Length + curve.B.Length + curve.G.X.Length + curve.G.Y.Length + curve.Order.Length + curve.Cofactor.Length + ((curve.Seed != null) ? curve.Seed.Length : 0); byte[] array = new byte[num]; fixed (byte* ptr = &array[0]) { global::Interop.BCrypt.BCRYPT_ECC_PARAMETER_HEADER* ptr2 = (global::Interop.BCrypt.BCRYPT_ECC_PARAMETER_HEADER*)ptr; ptr2->Version = 1; ptr2->cbCofactor = curve.Cofactor.Length; ptr2->cbFieldLength = curve.A.Length; ptr2->cbSeed = ((curve.Seed != null) ? curve.Seed.Length : 0); ptr2->cbSubgroupOrder = curve.Order.Length; ptr2->CurveGenerationAlgId = GetHashAlgorithmId(curve.Hash); ptr2->CurveType = ConvertToCurveTypeEnum(curve.CurveType); int offset = sizeof(global::Interop.BCrypt.BCRYPT_ECC_PARAMETER_HEADER); global::Interop.BCrypt.Emit(array, ref offset, curve.Prime); global::Interop.BCrypt.Emit(array, ref offset, curve.A); global::Interop.BCrypt.Emit(array, ref offset, curve.B); global::Interop.BCrypt.Emit(array, ref offset, curve.G.X); global::Interop.BCrypt.Emit(array, ref offset, curve.G.Y); global::Interop.BCrypt.Emit(array, ref offset, curve.Order); global::Interop.BCrypt.Emit(array, ref offset, curve.Cofactor); if (curve.Seed != null) { global::Interop.BCrypt.Emit(array, ref offset, curve.Seed); } } return array; } private static void CheckMagicValueOfKey(global::Interop.BCrypt.KeyBlobMagicNumber magic, bool includePrivateParameters) { if (includePrivateParameters) { if (!IsMagicValueOfKeyPrivate(magic)) { throw new CryptographicException(System.SR.Cryptography_NotValidPrivateKey); } } else if (!IsMagicValueOfKeyPublic(magic)) { throw new CryptographicException(System.SR.Cryptography_NotValidPublicOrPrivateKey); } } private static bool IsMagicValueOfKeyPrivate(global::Interop.BCrypt.KeyBlobMagicNumber magic) { switch (magic) { case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PRIVATE_P256_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P256_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PRIVATE_P384_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P384_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PRIVATE_P521_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P521_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_GENERIC_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PRIVATE_GENERIC_MAGIC: return true; default: return false; } } private static bool IsMagicValueOfKeyPublic(global::Interop.BCrypt.KeyBlobMagicNumber magic) { switch (magic) { case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PUBLIC_P256_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P256_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PUBLIC_P384_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P384_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PUBLIC_P521_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P521_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_GENERIC_MAGIC: case global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PUBLIC_GENERIC_MAGIC: return true; default: return IsMagicValueOfKeyPrivate(magic); } } private static global::Interop.BCrypt.KeyBlobMagicNumber EcdsaCurveNameToMagicNumber(string name, bool includePrivateParameters) { return EcdsaCurveNameToAlgorithm(name) switch { "ECDSA_P256" => includePrivateParameters ? global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P256_MAGIC : global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P256_MAGIC, "ECDSA_P384" => includePrivateParameters ? global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P384_MAGIC : global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P384_MAGIC, "ECDSA_P521" => includePrivateParameters ? global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P521_MAGIC : global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P521_MAGIC, _ => includePrivateParameters ? global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_GENERIC_MAGIC : global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_GENERIC_MAGIC, }; } private static global::Interop.BCrypt.KeyBlobMagicNumber EcdhCurveNameToMagicNumber(string name, bool includePrivateParameters) { return EcdhCurveNameToAlgorithm(name) switch { "ECDH_P256" => includePrivateParameters ? global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PRIVATE_P256_MAGIC : global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PUBLIC_P256_MAGIC, "ECDH_P384" => includePrivateParameters ? global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PRIVATE_P384_MAGIC : global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PUBLIC_P384_MAGIC, "ECDH_P521" => includePrivateParameters ? global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PRIVATE_P521_MAGIC : global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PUBLIC_P521_MAGIC, _ => includePrivateParameters ? global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PRIVATE_GENERIC_MAGIC : global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_ECDH_PUBLIC_GENERIC_MAGIC, }; } private static global::Interop.BCrypt.ECC_CURVE_TYPE_ENUM ConvertToCurveTypeEnum(ECCurve.ECCurveType value) { return (global::Interop.BCrypt.ECC_CURVE_TYPE_ENUM)value; } private static ECCurve.ECCurveType ConvertToCurveTypeEnum(global::Interop.BCrypt.ECC_CURVE_TYPE_ENUM value) { return (ECCurve.ECCurveType)value; } internal static SafeNCryptKeyHandle ImportKeyBlob(string blobType, ReadOnlySpan keyBlob, string curveName, SafeNCryptProviderHandle provider) { global::Interop.NCrypt.ErrorCode errorCode; SafeNCryptKeyHandle phKey; using (SafeUnicodeStringHandle safeUnicodeStringHandle = new SafeUnicodeStringHandle(curveName)) { global::Interop.BCrypt.BCryptBufferDesc structure = default(global::Interop.BCrypt.BCryptBufferDesc); global::Interop.BCrypt.BCryptBuffer structure2 = default(global::Interop.BCrypt.BCryptBuffer); IntPtr intPtr = IntPtr.Zero; IntPtr intPtr2 = IntPtr.Zero; try { intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(structure)); intPtr2 = Marshal.AllocHGlobal(Marshal.SizeOf(structure2)); structure2.cbBuffer = (curveName.Length + 1) * 2; structure2.BufferType = global::Interop.BCrypt.CngBufferDescriptors.NCRYPTBUFFER_ECC_CURVE_NAME; structure2.pvBuffer = safeUnicodeStringHandle.DangerousGetHandle(); Marshal.StructureToPtr(structure2, intPtr2, fDeleteOld: false); structure.cBuffers = 1; structure.pBuffers = intPtr2; structure.ulVersion = 0; Marshal.StructureToPtr(structure, intPtr, fDeleteOld: false); errorCode = global::Interop.NCrypt.NCryptImportKey(provider, IntPtr.Zero, blobType, intPtr, out phKey, ref MemoryMarshal.GetReference(keyBlob), keyBlob.Length, 0); } finally { Marshal.FreeHGlobal(intPtr); Marshal.FreeHGlobal(intPtr2); } } if (errorCode != 0) { Exception ex = errorCode.ToCryptographicException(); if (errorCode == global::Interop.NCrypt.ErrorCode.NTE_INVALID_PARAMETER) { throw new PlatformNotSupportedException(System.SR.Format(System.SR.Cryptography_CurveNotSupported, curveName), ex); } throw ex; } return phKey; } internal static string EcdsaCurveNameToAlgorithm(string algorithm) { switch (algorithm) { case "nistP256": case "ECDSA_P256": return "ECDSA_P256"; case "nistP384": case "ECDSA_P384": return "ECDSA_P384"; case "nistP521": case "ECDSA_P521": return "ECDSA_P521"; default: return "ECDSA"; } } internal static string EcdhCurveNameToAlgorithm(string algorithm) { switch (algorithm) { case "nistP256": case "ECDH_P256": case "ECDSA_P256": return "ECDH_P256"; case "nistP384": case "ECDH_P384": case "ECDSA_P384": return "ECDH_P384"; case "nistP521": case "ECDH_P521": case "ECDSA_P521": return "ECDH_P521"; default: return "ECDH"; } } internal static global::Interop.BCrypt.ECC_CURVE_ALG_ID_ENUM GetHashAlgorithmId(HashAlgorithmName? name) { if (!name.HasValue || string.IsNullOrEmpty(name.Value.Name)) { return global::Interop.BCrypt.ECC_CURVE_ALG_ID_ENUM.BCRYPT_NO_CURVE_GENERATION_ALG_ID; } global::Interop.Crypt32.CRYPT_OID_INFO cRYPT_OID_INFO = global::Interop.Crypt32.FindOidInfo(global::Interop.Crypt32.CryptOidInfoKeyType.CRYPT_OID_INFO_NAME_KEY, name.Value.Name, OidGroup.HashAlgorithm, fallBackToAllGroups: false); if (cRYPT_OID_INFO.AlgId == -1) { throw new CryptographicException(System.SR.Cryptography_UnknownHashAlgorithm, name.Value.Name); } return (global::Interop.BCrypt.ECC_CURVE_ALG_ID_ENUM)cRYPT_OID_INFO.AlgId; } internal static HashAlgorithmName? GetHashAlgorithmName(global::Interop.BCrypt.ECC_CURVE_ALG_ID_ENUM hashId) { global::Interop.Crypt32.CRYPT_OID_INFO cRYPT_OID_INFO = global::Interop.Crypt32.FindAlgIdOidInfo(hashId); if (cRYPT_OID_INFO.AlgId == -1) { return null; } return new HashAlgorithmName(cRYPT_OID_INFO.Name); } } public enum ECDiffieHellmanKeyDerivationFunction { Hash, Hmac, Tls } public sealed class ECDiffieHellmanCng : ECDiffieHellman { private CngAlgorithmCore _core = new CngAlgorithmCore("ECDiffieHellmanCng") { DefaultKeyType = CngAlgorithm.ECDiffieHellman }; private CngAlgorithm _hashAlgorithm = CngAlgorithm.Sha256; private ECDiffieHellmanKeyDerivationFunction _kdf; private byte[] _hmacKey; private byte[] _label; private byte[] _secretAppend; private byte[] _secretPrepend; private byte[] _seed; public CngAlgorithm HashAlgorithm { get { return _hashAlgorithm; } set { if (_hashAlgorithm == null) { throw new ArgumentNullException("value"); } _hashAlgorithm = value; } } public ECDiffieHellmanKeyDerivationFunction KeyDerivationFunction { get { return _kdf; } set { if (value < ECDiffieHellmanKeyDerivationFunction.Hash || value > ECDiffieHellmanKeyDerivationFunction.Tls) { throw new ArgumentOutOfRangeException("value"); } _kdf = value; } } public byte[]? HmacKey { get { return _hmacKey; } set { _hmacKey = value; } } public byte[]? Label { get { return _label; } set { _label = value; } } public byte[]? SecretAppend { get { return _secretAppend; } set { _secretAppend = value; } } public byte[]? SecretPrepend { get { return _secretPrepend; } set { _secretPrepend = value; } } public byte[]? Seed { get { return _seed; } set { _seed = value; } } public bool UseSecretAgreementAsHmacKey => HmacKey == null; public override ECDiffieHellmanPublicKey PublicKey => ECDiffieHellmanCngPublicKey.FromKey(Key); public CngKey Key { get { return GetKey(); } private set { if (value == null) { throw new ArgumentNullException("value"); } if (value.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) { throw new ArgumentException(System.SR.Cryptography_ArgECDHRequiresECDHKey, "value"); } _core.SetKey(value); ForceSetKeySize(value.KeySize); } } public override int KeySize { get { return base.KeySize; } set { if (KeySize != value) { base.KeySize = value; DisposeKey(); } } } public override KeySizes[] LegalKeySizes => new KeySizes[2] { new KeySizes(256, 384, 128), new KeySizes(521, 521, 0) }; public ECDiffieHellmanCng(CngKey key) { if (key == null) { throw new ArgumentNullException("key"); } if (key.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) { throw new ArgumentException(System.SR.Cryptography_ArgECDHRequiresECDHKey, "key"); } Key = CngAlgorithmCore.Duplicate(key); } protected override void Dispose(bool disposing) { _core.Dispose(); } private void ThrowIfDisposed() { _core.ThrowIfDisposed(); } private void DisposeKey() { _core.DisposeKey(); } internal string GetCurveName(out string oidValue) { return Key.GetCurveName(out oidValue); } private void ImportFullKeyBlob(byte[] ecfullKeyBlob, bool includePrivateParameters) { Key = ECCng.ImportFullKeyBlob(ecfullKeyBlob, includePrivateParameters); } private void ImportKeyBlob(byte[] ecfullKeyBlob, string curveName, bool includePrivateParameters) { Key = ECCng.ImportKeyBlob(ecfullKeyBlob, curveName, includePrivateParameters); } private byte[] ExportKeyBlob(bool includePrivateParameters) { return ECCng.ExportKeyBlob(Key, includePrivateParameters); } private byte[] ExportFullKeyBlob(bool includePrivateParameters) { return ECCng.ExportFullKeyBlob(Key, includePrivateParameters); } private void AcceptImport(CngPkcs8.Pkcs8Response response) { Key = response.Key; } public override bool TryExportPkcs8PrivateKey(Span destination, out int bytesWritten) { return Key.TryExportKeyBlob("PKCS8_PRIVATEKEY", destination, out bytesWritten); } private byte[] ExportEncryptedPkcs8(ReadOnlySpan pkcs8Password, int kdfCount) { return Key.ExportPkcs8KeyBlob(pkcs8Password, kdfCount); } private bool TryExportEncryptedPkcs8(ReadOnlySpan pkcs8Password, int kdfCount, Span destination, out int bytesWritten) { return Key.TryExportPkcs8KeyBlob(pkcs8Password, kdfCount, destination, out bytesWritten); } public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPublicKey) { if (otherPartyPublicKey == null) { throw new ArgumentNullException("otherPartyPublicKey"); } if (otherPartyPublicKey is ECDiffieHellmanCngPublicKey eCDiffieHellmanCngPublicKey) { using CngKey otherPartyPublicKey2 = eCDiffieHellmanCngPublicKey.Import(); return DeriveKeyMaterial(otherPartyPublicKey2); } ECParameters parameters = otherPartyPublicKey.ExportParameters(); using ECDiffieHellmanCng eCDiffieHellmanCng = new ECDiffieHellmanCng(); eCDiffieHellmanCng.ImportParameters(parameters); ECDiffieHellmanCngPublicKey eCDiffieHellmanCngPublicKey2; using (eCDiffieHellmanCngPublicKey2 = (ECDiffieHellmanCngPublicKey)eCDiffieHellmanCng.PublicKey) { using CngKey otherPartyPublicKey3 = eCDiffieHellmanCngPublicKey2.Import(); return DeriveKeyMaterial(otherPartyPublicKey3); } } public byte[] DeriveKeyMaterial(CngKey otherPartyPublicKey) { if (otherPartyPublicKey == null) { throw new ArgumentNullException("otherPartyPublicKey"); } if (otherPartyPublicKey.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) { throw new ArgumentException(System.SR.Cryptography_ArgECDHRequiresECDHKey, "otherPartyPublicKey"); } if (otherPartyPublicKey.KeySize != KeySize) { throw new ArgumentException(System.SR.Cryptography_ArgECDHKeySizeMismatch, "otherPartyPublicKey"); } global::Interop.NCrypt.SecretAgreementFlags flags = (UseSecretAgreementAsHmacKey ? global::Interop.NCrypt.SecretAgreementFlags.UseSecretAsHmacKey : global::Interop.NCrypt.SecretAgreementFlags.None); using SafeNCryptSecretHandle secretAgreement = DeriveSecretAgreementHandle(otherPartyPublicKey); switch (KeyDerivationFunction) { case ECDiffieHellmanKeyDerivationFunction.Hash: return global::Interop.NCrypt.DeriveKeyMaterialHash(secretAgreement, HashAlgorithm.Algorithm, _secretPrepend, _secretAppend, flags); case ECDiffieHellmanKeyDerivationFunction.Hmac: return global::Interop.NCrypt.DeriveKeyMaterialHmac(secretAgreement, HashAlgorithm.Algorithm, _hmacKey, _secretPrepend, _secretAppend, flags); default: if (_label == null || _seed == null) { throw new InvalidOperationException(System.SR.Cryptography_TlsRequiresLabelAndSeed); } return global::Interop.NCrypt.DeriveKeyMaterialTls(secretAgreement, _label, _seed, flags); } } public SafeNCryptSecretHandle DeriveSecretAgreementHandle(ECDiffieHellmanPublicKey otherPartyPublicKey) { if (otherPartyPublicKey == null) { throw new ArgumentNullException("otherPartyPublicKey"); } if (otherPartyPublicKey is ECDiffieHellmanCngPublicKey eCDiffieHellmanCngPublicKey) { using CngKey otherPartyPublicKey2 = eCDiffieHellmanCngPublicKey.Import(); return DeriveSecretAgreementHandle(otherPartyPublicKey2); } ECParameters parameters = otherPartyPublicKey.ExportParameters(); using ECDiffieHellmanCng eCDiffieHellmanCng = new ECDiffieHellmanCng(); eCDiffieHellmanCng.ImportParameters(parameters); ECDiffieHellmanCngPublicKey eCDiffieHellmanCngPublicKey2; using (eCDiffieHellmanCngPublicKey2 = (ECDiffieHellmanCngPublicKey)eCDiffieHellmanCng.PublicKey) { using CngKey otherPartyPublicKey3 = eCDiffieHellmanCngPublicKey2.Import(); return DeriveSecretAgreementHandle(otherPartyPublicKey3); } } public SafeNCryptSecretHandle DeriveSecretAgreementHandle(CngKey otherPartyPublicKey) { if (otherPartyPublicKey == null) { throw new ArgumentNullException("otherPartyPublicKey"); } if (otherPartyPublicKey.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) { throw new ArgumentException(System.SR.Cryptography_ArgECDHRequiresECDHKey, "otherPartyPublicKey"); } if (otherPartyPublicKey.KeySize != KeySize) { throw new ArgumentException(System.SR.Cryptography_ArgECDHKeySizeMismatch, "otherPartyPublicKey"); } using SafeNCryptKeyHandle privateKey = Key.Handle; using SafeNCryptKeyHandle otherPartyPublicKey2 = otherPartyPublicKey.Handle; return global::Interop.NCrypt.DeriveSecretAgreement(privateKey, otherPartyPublicKey2); } public override void GenerateKey(ECCurve curve) { curve.Validate(); _core.DisposeKey(); if (curve.IsNamed) { if (string.IsNullOrEmpty(curve.Oid.FriendlyName)) { throw new PlatformNotSupportedException(System.SR.Format(System.SR.Cryptography_InvalidCurveOid, curve.Oid.Value)); } CngAlgorithm cngAlgorithm = CngKey.EcdhCurveNameToAlgorithm(curve.Oid.FriendlyName); if (CngKey.IsECNamedCurve(cngAlgorithm.Algorithm)) { CngKey orGenerateKey = _core.GetOrGenerateKey(curve); ForceSetKeySize(orGenerateKey.KeySize); return; } int num = 0; if (cngAlgorithm == CngAlgorithm.ECDiffieHellmanP256) { num = 256; } else if (cngAlgorithm == CngAlgorithm.ECDiffieHellmanP384) { num = 384; } else { if (!(cngAlgorithm == CngAlgorithm.ECDiffieHellmanP521)) { throw new ArgumentException(System.SR.Cryptography_InvalidKeySize); } num = 521; } _core.GetOrGenerateKey(num, cngAlgorithm); ForceSetKeySize(num); } else { if (!curve.IsExplicit) { throw new PlatformNotSupportedException(System.SR.Format(System.SR.Cryptography_CurveNotSupported, curve.CurveType.ToString())); } CngKey orGenerateKey2 = _core.GetOrGenerateKey(curve); ForceSetKeySize(orGenerateKey2.KeySize); } } private CngKey GetKey() { if (_core.IsKeyGeneratedNamedCurve()) { return _core.GetOrGenerateKey(null); } int num = 0; num = KeySize; CngAlgorithm algorithm = num switch { 256 => CngAlgorithm.ECDiffieHellmanP256, 384 => CngAlgorithm.ECDiffieHellmanP384, 521 => CngAlgorithm.ECDiffieHellmanP521, _ => throw new ArgumentException(System.SR.Cryptography_InvalidKeySize), }; return _core.GetOrGenerateKey(num, algorithm); } public void FromXmlString(string xml, ECKeyXmlFormat format) { throw new PlatformNotSupportedException(); } public string ToXmlString(ECKeyXmlFormat format) { throw new PlatformNotSupportedException(); } public ECDiffieHellmanCng() : this(521) { } public ECDiffieHellmanCng(int keySize) { KeySize = keySize; } public ECDiffieHellmanCng(ECCurve curve) { GenerateKey(curve); } private void ForceSetKeySize(int newKeySize) { KeySizeValue = newKeySize; } public override byte[] DeriveKeyFromHash(ECDiffieHellmanPublicKey otherPartyPublicKey, HashAlgorithmName hashAlgorithm, byte[]? secretPrepend, byte[]? secretAppend) { if (otherPartyPublicKey == null) { throw new ArgumentNullException("otherPartyPublicKey"); } if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw new ArgumentException(System.SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); } using SafeNCryptSecretHandle secretAgreement = DeriveSecretAgreementHandle(otherPartyPublicKey); return global::Interop.NCrypt.DeriveKeyMaterialHash(secretAgreement, hashAlgorithm.Name, secretPrepend, secretAppend, global::Interop.NCrypt.SecretAgreementFlags.None); } public override byte[] DeriveKeyFromHmac(ECDiffieHellmanPublicKey otherPartyPublicKey, HashAlgorithmName hashAlgorithm, byte[]? hmacKey, byte[]? secretPrepend, byte[]? secretAppend) { if (otherPartyPublicKey == null) { throw new ArgumentNullException("otherPartyPublicKey"); } if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw new ArgumentException(System.SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); } using SafeNCryptSecretHandle secretAgreement = DeriveSecretAgreementHandle(otherPartyPublicKey); global::Interop.NCrypt.SecretAgreementFlags flags = ((hmacKey == null) ? global::Interop.NCrypt.SecretAgreementFlags.UseSecretAsHmacKey : global::Interop.NCrypt.SecretAgreementFlags.None); return global::Interop.NCrypt.DeriveKeyMaterialHmac(secretAgreement, hashAlgorithm.Name, hmacKey, secretPrepend, secretAppend, flags); } public override byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed) { if (otherPartyPublicKey == null) { throw new ArgumentNullException("otherPartyPublicKey"); } if (prfLabel == null) { throw new ArgumentNullException("prfLabel"); } if (prfSeed == null) { throw new ArgumentNullException("prfSeed"); } using SafeNCryptSecretHandle secretAgreement = DeriveSecretAgreementHandle(otherPartyPublicKey); return global::Interop.NCrypt.DeriveKeyMaterialTls(secretAgreement, prfLabel, prfSeed, global::Interop.NCrypt.SecretAgreementFlags.None); } public override void ImportParameters(ECParameters parameters) { parameters.Validate(); ThrowIfDisposed(); ECCurve curve = parameters.Curve; bool flag = parameters.D != null; bool flag2 = parameters.Q.X != null && parameters.Q.Y != null; if (curve.IsPrime) { if (!flag2 && flag) { byte[] array = new byte[parameters.D.Length]; ECParameters parameters2 = parameters; parameters2.Q.X = array; parameters2.Q.Y = array; byte[] primeCurveBlob = ECCng.GetPrimeCurveBlob(ref parameters2, ecdh: true); ImportFullKeyBlob(primeCurveBlob, includePrivateParameters: true); } else { byte[] primeCurveBlob2 = ECCng.GetPrimeCurveBlob(ref parameters, ecdh: true); ImportFullKeyBlob(primeCurveBlob2, flag); } return; } if (curve.IsNamed) { if (string.IsNullOrEmpty(curve.Oid.FriendlyName)) { throw new PlatformNotSupportedException(System.SR.Format(System.SR.Cryptography_InvalidCurveOid, curve.Oid.Value)); } if (!flag2 && flag) { byte[] array2 = new byte[parameters.D.Length]; ECParameters parameters3 = parameters; parameters3.Q.X = array2; parameters3.Q.Y = array2; byte[] namedCurveBlob = ECCng.GetNamedCurveBlob(ref parameters3, ecdh: true); ImportKeyBlob(namedCurveBlob, curve.Oid.FriendlyName, includePrivateParameters: true); } else { byte[] namedCurveBlob2 = ECCng.GetNamedCurveBlob(ref parameters, ecdh: true); ImportKeyBlob(namedCurveBlob2, curve.Oid.FriendlyName, flag); } return; } throw new PlatformNotSupportedException(System.SR.Format(System.SR.Cryptography_CurveNotSupported, curve.CurveType.ToString())); } public override ECParameters ExportExplicitParameters(bool includePrivateParameters) { byte[] array = ExportFullKeyBlob(includePrivateParameters); try { ECParameters ecParams = default(ECParameters); ECCng.ExportPrimeCurveParameters(ref ecParams, array, includePrivateParameters); return ecParams; } finally { Array.Clear(array); } } public override ECParameters ExportParameters(bool includePrivateParameters) { ECParameters ecParams = default(ECParameters); string oidValue; string curveName = GetCurveName(out oidValue); byte[] array = null; try { if (string.IsNullOrEmpty(curveName)) { array = ExportFullKeyBlob(includePrivateParameters); ECCng.ExportPrimeCurveParameters(ref ecParams, array, includePrivateParameters); } else { array = ExportKeyBlob(includePrivateParameters); ECCng.ExportNamedCurveParameters(ref ecParams, array, includePrivateParameters); ecParams.Curve = ECCurve.CreateFromOid(new Oid(oidValue, curveName)); } return ecParams; } finally { if (array != null) { Array.Clear(array); } } } public override void ImportPkcs8PrivateKey(ReadOnlySpan source, out int bytesRead) { ThrowIfDisposed(); int bytesRead2; CngPkcs8.Pkcs8Response response = CngPkcs8.ImportPkcs8PrivateKey(source, out bytesRead2); ProcessPkcs8Response(response); bytesRead = bytesRead2; } public override void ImportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, ReadOnlySpan source, out int bytesRead) { ThrowIfDisposed(); int bytesRead2; CngPkcs8.Pkcs8Response response = CngPkcs8.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead2); ProcessPkcs8Response(response); bytesRead = bytesRead2; } public override void ImportEncryptedPkcs8PrivateKey(ReadOnlySpan password, ReadOnlySpan source, out int bytesRead) { ThrowIfDisposed(); int bytesRead2; CngPkcs8.Pkcs8Response response = CngPkcs8.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead2); ProcessPkcs8Response(response); bytesRead = bytesRead2; } private void ProcessPkcs8Response(CngPkcs8.Pkcs8Response response) { if (response.GetAlgorithmGroup() != "ECDH") { response.FreeKey(); throw new CryptographicException(System.SR.Cryptography_NotValidPublicOrPrivateKey); } AcceptImport(response); } public override byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } return CngPkcs8.ExportEncryptedPkcs8PrivateKey(this, passwordBytes, pbeParameters); } public override byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan password, PbeParameters pbeParameters) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } System.Security.Cryptography.PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, password, ReadOnlySpan.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return ExportEncryptedPkcs8(password, pbeParameters.IterationCount); } return CngPkcs8.ExportEncryptedPkcs8PrivateKey(this, password, pbeParameters); } public override bool TryExportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, PbeParameters pbeParameters, Span destination, out int bytesWritten) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } System.Security.Cryptography.PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, ReadOnlySpan.Empty, passwordBytes); return CngPkcs8.TryExportEncryptedPkcs8PrivateKey(this, passwordBytes, pbeParameters, destination, out bytesWritten); } public override bool TryExportEncryptedPkcs8PrivateKey(ReadOnlySpan password, PbeParameters pbeParameters, Span destination, out int bytesWritten) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } System.Security.Cryptography.PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, password, ReadOnlySpan.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return TryExportEncryptedPkcs8(password, pbeParameters.IterationCount, destination, out bytesWritten); } return CngPkcs8.TryExportEncryptedPkcs8PrivateKey(this, password, pbeParameters, destination, out bytesWritten); } } public sealed class ECDiffieHellmanCngPublicKey : ECDiffieHellmanPublicKey { private readonly CngKeyBlobFormat _format; private readonly string _curveName; private bool _disposed; public CngKeyBlobFormat BlobFormat => _format; internal ECDiffieHellmanCngPublicKey(byte[] keyBlob, string curveName, CngKeyBlobFormat format) : base(keyBlob) { _format = format; _curveName = curveName; } protected override void Dispose(bool disposing) { if (disposing) { _disposed = true; } base.Dispose(disposing); } public override string ToXmlString() { throw new PlatformNotSupportedException(); } public static ECDiffieHellmanCngPublicKey FromXmlString(string xml) { throw new PlatformNotSupportedException(); } public static ECDiffieHellmanPublicKey FromByteArray(byte[] publicKeyBlob, CngKeyBlobFormat format) { if (publicKeyBlob == null) { throw new ArgumentNullException("publicKeyBlob"); } if (format == null) { throw new ArgumentNullException("format"); } using CngKey cngKey = CngKey.Import(publicKeyBlob, format); if (cngKey.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) { throw new ArgumentException(System.SR.Cryptography_ArgECDHRequiresECDHKey); } return new ECDiffieHellmanCngPublicKey(publicKeyBlob, null, format); } internal static ECDiffieHellmanCngPublicKey FromKey(CngKey key) { CngKeyBlobFormat format; string curveName; byte[] keyBlob = ECCng.ExportKeyBlob(key, includePrivateParameters: false, out format, out curveName); return new ECDiffieHellmanCngPublicKey(keyBlob, curveName, format); } public CngKey Import() { if (_disposed) { throw new ObjectDisposedException("ECDiffieHellmanCngPublicKey"); } return CngKey.Import(ToByteArray(), _curveName, BlobFormat); } public override ECParameters ExportExplicitParameters() { using CngKey key = Import(); ECParameters ecParams = default(ECParameters); byte[] ecBlob = ECCng.ExportFullKeyBlob(key, includePrivateParameters: false); ECCng.ExportPrimeCurveParameters(ref ecParams, ecBlob, includePrivateParameters: false); return ecParams; } public override ECParameters ExportParameters() { using CngKey cngKey = Import(); ECParameters ecParams = default(ECParameters); string oidValue; string curveName = cngKey.GetCurveName(out oidValue); if (string.IsNullOrEmpty(curveName)) { byte[] ecBlob = ECCng.ExportFullKeyBlob(cngKey, includePrivateParameters: false); ECCng.ExportPrimeCurveParameters(ref ecParams, ecBlob, includePrivateParameters: false); } else { byte[] ecBlob2 = ECCng.ExportKeyBlob(cngKey, includePrivateParameters: false); ECCng.ExportNamedCurveParameters(ref ecParams, ecBlob2, includePrivateParameters: false); ecParams.Curve = ECCurve.CreateFromFriendlyName(curveName); } return ecParams; } } public sealed class ECDsaCng : ECDsa { private CngAlgorithmCore _core = new CngAlgorithmCore("ECDsaCng"); private CngAlgorithm _hashAlgorithm = CngAlgorithm.Sha256; public CngAlgorithm HashAlgorithm { get { return _hashAlgorithm; } set { _hashAlgorithm = value ?? throw new ArgumentNullException("value"); } } public CngKey Key { get { return GetKey(); } private set { if (value == null) { throw new ArgumentNullException("value"); } if (!IsEccAlgorithmGroup(value.AlgorithmGroup)) { throw new ArgumentException(System.SR.Cryptography_ArgECDsaRequiresECDsaKey, "value"); } _core.SetKey(value); ForceSetKeySize(value.KeySize); } } public override int KeySize { get { return base.KeySize; } set { if (KeySize != value) { base.KeySize = value; DisposeKey(); } } } public override KeySizes[] LegalKeySizes => new KeySizes[2] { new KeySizes(256, 384, 128), new KeySizes(521, 521, 0) }; public ECDsaCng(CngKey key) { if (key == null) { throw new ArgumentNullException("key"); } if (!IsEccAlgorithmGroup(key.AlgorithmGroup)) { throw new ArgumentException(System.SR.Cryptography_ArgECDsaRequiresECDsaKey, "key"); } Key = CngAlgorithmCore.Duplicate(key); } protected override void Dispose(bool disposing) { _core.Dispose(); } private void ThrowIfDisposed() { _core.ThrowIfDisposed(); } private void DisposeKey() { _core.DisposeKey(); } private static bool IsEccAlgorithmGroup(CngAlgorithmGroup algorithmGroup) { if (!(algorithmGroup == CngAlgorithmGroup.ECDsa)) { return algorithmGroup == CngAlgorithmGroup.ECDiffieHellman; } return true; } internal string GetCurveName(out string oidValue) { return Key.GetCurveName(out oidValue); } private void ImportFullKeyBlob(byte[] ecfullKeyBlob, bool includePrivateParameters) { Key = ECCng.ImportFullKeyBlob(ecfullKeyBlob, includePrivateParameters); } private void ImportKeyBlob(byte[] ecfullKeyBlob, string curveName, bool includePrivateParameters) { Key = ECCng.ImportKeyBlob(ecfullKeyBlob, curveName, includePrivateParameters); } private byte[] ExportKeyBlob(bool includePrivateParameters) { return ECCng.ExportKeyBlob(Key, includePrivateParameters); } private byte[] ExportFullKeyBlob(bool includePrivateParameters) { return ECCng.ExportFullKeyBlob(Key, includePrivateParameters); } private void AcceptImport(CngPkcs8.Pkcs8Response response) { Key = response.Key; } public override bool TryExportPkcs8PrivateKey(Span destination, out int bytesWritten) { return Key.TryExportKeyBlob("PKCS8_PRIVATEKEY", destination, out bytesWritten); } private byte[] ExportEncryptedPkcs8(ReadOnlySpan pkcs8Password, int kdfCount) { return Key.ExportPkcs8KeyBlob(pkcs8Password, kdfCount); } private bool TryExportEncryptedPkcs8(ReadOnlySpan pkcs8Password, int kdfCount, Span destination, out int bytesWritten) { return Key.TryExportPkcs8KeyBlob(pkcs8Password, kdfCount, destination, out bytesWritten); } public void FromXmlString(string xml, ECKeyXmlFormat format) { throw new PlatformNotSupportedException(); } public byte[] SignData(byte[] data) { return SignData(data, new HashAlgorithmName(HashAlgorithm.Algorithm)); } public byte[] SignData(byte[] data, int offset, int count) { return SignData(data, offset, count, new HashAlgorithmName(HashAlgorithm.Algorithm)); } public byte[] SignData(Stream data) { return SignData(data, new HashAlgorithmName(HashAlgorithm.Algorithm)); } public string ToXmlString(ECKeyXmlFormat format) { throw new PlatformNotSupportedException(); } public bool VerifyData(byte[] data, byte[] signature) { return VerifyData(data, signature, new HashAlgorithmName(HashAlgorithm.Algorithm)); } public bool VerifyData(byte[] data, int offset, int count, byte[] signature) { return VerifyData(data, offset, count, signature, new HashAlgorithmName(HashAlgorithm.Algorithm)); } public bool VerifyData(Stream data, byte[] signature) { return VerifyData(data, signature, new HashAlgorithmName(HashAlgorithm.Algorithm)); } public override void GenerateKey(ECCurve curve) { curve.Validate(); _core.DisposeKey(); if (curve.IsNamed) { if (string.IsNullOrEmpty(curve.Oid.FriendlyName)) { throw new PlatformNotSupportedException(System.SR.Format(System.SR.Cryptography_InvalidCurveOid, curve.Oid.Value)); } CngAlgorithm cngAlgorithm = CngKey.EcdsaCurveNameToAlgorithm(curve.Oid.FriendlyName); if (CngKey.IsECNamedCurve(cngAlgorithm.Algorithm)) { CngKey orGenerateKey = _core.GetOrGenerateKey(curve); ForceSetKeySize(orGenerateKey.KeySize); return; } int num = 0; if (cngAlgorithm == CngAlgorithm.ECDsaP256) { num = 256; } else if (cngAlgorithm == CngAlgorithm.ECDsaP384) { num = 384; } else { if (!(cngAlgorithm == CngAlgorithm.ECDsaP521)) { throw new ArgumentException(System.SR.Cryptography_InvalidKeySize); } num = 521; } _core.GetOrGenerateKey(num, cngAlgorithm); ForceSetKeySize(num); } else { if (!curve.IsExplicit) { throw new PlatformNotSupportedException(System.SR.Format(System.SR.Cryptography_CurveNotSupported, curve.CurveType.ToString())); } CngKey orGenerateKey2 = _core.GetOrGenerateKey(curve); ForceSetKeySize(orGenerateKey2.KeySize); } } private CngKey GetKey() { CngKey cngKey = null; if (_core.IsKeyGeneratedNamedCurve()) { return _core.GetOrGenerateKey(null); } CngAlgorithm cngAlgorithm = null; int num = 0; num = KeySize; cngAlgorithm = num switch { 256 => CngAlgorithm.ECDsaP256, 384 => CngAlgorithm.ECDsaP384, 521 => CngAlgorithm.ECDsaP521, _ => throw new ArgumentException(System.SR.Cryptography_InvalidKeySize), }; return _core.GetOrGenerateKey(num, cngAlgorithm); } private SafeNCryptKeyHandle GetDuplicatedKeyHandle() { return Key.Handle; } public override void ImportParameters(ECParameters parameters) { parameters.Validate(); ThrowIfDisposed(); ECCurve curve = parameters.Curve; bool flag = parameters.D != null; bool flag2 = parameters.Q.X != null && parameters.Q.Y != null; if (curve.IsPrime) { if (!flag2 && flag) { byte[] array = new byte[parameters.D.Length]; ECParameters parameters2 = parameters; parameters2.Q.X = array; parameters2.Q.Y = array; byte[] primeCurveBlob = ECCng.GetPrimeCurveBlob(ref parameters2, ecdh: false); ImportFullKeyBlob(primeCurveBlob, includePrivateParameters: true); } else { byte[] primeCurveBlob2 = ECCng.GetPrimeCurveBlob(ref parameters, ecdh: false); ImportFullKeyBlob(primeCurveBlob2, flag); } return; } if (curve.IsNamed) { if (string.IsNullOrEmpty(curve.Oid.FriendlyName)) { throw new PlatformNotSupportedException(System.SR.Format(System.SR.Cryptography_InvalidCurveOid, curve.Oid.Value.ToString())); } if (!flag2 && flag) { byte[] array2 = new byte[parameters.D.Length]; ECParameters parameters3 = parameters; parameters3.Q.X = array2; parameters3.Q.Y = array2; byte[] namedCurveBlob = ECCng.GetNamedCurveBlob(ref parameters3, ecdh: false); ImportKeyBlob(namedCurveBlob, curve.Oid.FriendlyName, includePrivateParameters: true); } else { byte[] namedCurveBlob2 = ECCng.GetNamedCurveBlob(ref parameters, ecdh: false); ImportKeyBlob(namedCurveBlob2, curve.Oid.FriendlyName, flag); } return; } throw new PlatformNotSupportedException(System.SR.Format(System.SR.Cryptography_CurveNotSupported, curve.CurveType.ToString())); } public override ECParameters ExportExplicitParameters(bool includePrivateParameters) { byte[] ecBlob = ExportFullKeyBlob(includePrivateParameters); ECParameters ecParams = default(ECParameters); ECCng.ExportPrimeCurveParameters(ref ecParams, ecBlob, includePrivateParameters); return ecParams; } public override ECParameters ExportParameters(bool includePrivateParameters) { ECParameters ecParams = default(ECParameters); string oidValue; string curveName = GetCurveName(out oidValue); if (string.IsNullOrEmpty(curveName)) { byte[] ecBlob = ExportFullKeyBlob(includePrivateParameters); ECCng.ExportPrimeCurveParameters(ref ecParams, ecBlob, includePrivateParameters); } else { byte[] ecBlob2 = ExportKeyBlob(includePrivateParameters); ECCng.ExportNamedCurveParameters(ref ecParams, ecBlob2, includePrivateParameters); ecParams.Curve = ECCurve.CreateFromOid(new Oid(oidValue, curveName)); } return ecParams; } public override void ImportPkcs8PrivateKey(ReadOnlySpan source, out int bytesRead) { ThrowIfDisposed(); int bytesRead2; CngPkcs8.Pkcs8Response response = CngPkcs8.ImportPkcs8PrivateKey(source, out bytesRead2); ProcessPkcs8Response(response); bytesRead = bytesRead2; } public override void ImportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, ReadOnlySpan source, out int bytesRead) { ThrowIfDisposed(); int bytesRead2; CngPkcs8.Pkcs8Response response = CngPkcs8.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead2); ProcessPkcs8Response(response); bytesRead = bytesRead2; } public override void ImportEncryptedPkcs8PrivateKey(ReadOnlySpan password, ReadOnlySpan source, out int bytesRead) { ThrowIfDisposed(); int bytesRead2; CngPkcs8.Pkcs8Response response = CngPkcs8.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead2); ProcessPkcs8Response(response); bytesRead = bytesRead2; } private void ProcessPkcs8Response(CngPkcs8.Pkcs8Response response) { string algorithmGroup = response.GetAlgorithmGroup(); if (algorithmGroup == "ECDSA" || algorithmGroup == "ECDH") { AcceptImport(response); return; } response.FreeKey(); throw new CryptographicException(System.SR.Cryptography_NotValidPublicOrPrivateKey); } public override byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } return CngPkcs8.ExportEncryptedPkcs8PrivateKey(this, passwordBytes, pbeParameters); } public override byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan password, PbeParameters pbeParameters) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } System.Security.Cryptography.PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, password, ReadOnlySpan.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return ExportEncryptedPkcs8(password, pbeParameters.IterationCount); } return CngPkcs8.ExportEncryptedPkcs8PrivateKey(this, password, pbeParameters); } public override bool TryExportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, PbeParameters pbeParameters, Span destination, out int bytesWritten) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } System.Security.Cryptography.PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, ReadOnlySpan.Empty, passwordBytes); return CngPkcs8.TryExportEncryptedPkcs8PrivateKey(this, passwordBytes, pbeParameters, destination, out bytesWritten); } public override bool TryExportEncryptedPkcs8PrivateKey(ReadOnlySpan password, PbeParameters pbeParameters, Span destination, out int bytesWritten) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } System.Security.Cryptography.PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, password, ReadOnlySpan.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return TryExportEncryptedPkcs8(password, pbeParameters.IterationCount, destination, out bytesWritten); } return CngPkcs8.TryExportEncryptedPkcs8PrivateKey(this, password, pbeParameters, destination, out bytesWritten); } public ECDsaCng(ECCurve curve) { GenerateKey(curve); } public ECDsaCng() : this(521) { } public ECDsaCng(int keySize) { KeySize = keySize; } private void ForceSetKeySize(int newKeySize) { KeySizeValue = newKeySize; } protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { return CngCommon.HashData(data, offset, count, hashAlgorithm); } protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { return CngCommon.HashData(data, hashAlgorithm); } protected override bool TryHashData(ReadOnlySpan source, Span destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) { return CngCommon.TryHashData(source, destination, hashAlgorithm, out bytesWritten); } public unsafe override byte[] SignHash(byte[] hash) { if (hash == null) { throw new ArgumentNullException("hash"); } int estimatedSize = KeySize switch { 256 => 64, 384 => 96, 521 => 132, _ => KeySize / 4, }; using SafeNCryptKeyHandle keyHandle = GetDuplicatedKeyHandle(); return keyHandle.SignHash(hash, global::Interop.NCrypt.AsymmetricPaddingMode.None, null, estimatedSize); } public unsafe override bool TrySignHash(ReadOnlySpan source, Span destination, out int bytesWritten) { using (SafeNCryptKeyHandle keyHandle = GetDuplicatedKeyHandle()) { if (!keyHandle.TrySignHash(source, destination, global::Interop.NCrypt.AsymmetricPaddingMode.None, null, out bytesWritten)) { bytesWritten = 0; return false; } } return true; } public override bool VerifyHash(byte[] hash, byte[] signature) { if (hash == null) { throw new ArgumentNullException("hash"); } if (signature == null) { throw new ArgumentNullException("signature"); } return VerifyHash((ReadOnlySpan)hash, (ReadOnlySpan)signature); } public unsafe override bool VerifyHash(ReadOnlySpan hash, ReadOnlySpan signature) { using SafeNCryptKeyHandle keyHandle = GetDuplicatedKeyHandle(); return keyHandle.VerifyHash(hash, signature, global::Interop.NCrypt.AsymmetricPaddingMode.None, null); } } public enum ECKeyXmlFormat { Rfc4050 } public sealed class RSACng : RSA { private CngAlgorithmCore _core = new CngAlgorithmCore("RSACng"); private static readonly CngKeyBlobFormat s_rsaFullPrivateBlob = new CngKeyBlobFormat("RSAFULLPRIVATEBLOB"); private static readonly CngKeyBlobFormat s_rsaPrivateBlob = new CngKeyBlobFormat("RSAPRIVATEBLOB"); private static readonly CngKeyBlobFormat s_rsaPublicBlob = new CngKeyBlobFormat("RSAPUBLICBLOB"); private static readonly ConcurrentDictionary s_hashSizes = new ConcurrentDictionary(new KeyValuePair[3] { KeyValuePair.Create(HashAlgorithmName.SHA256, 32), KeyValuePair.Create(HashAlgorithmName.SHA384, 48), KeyValuePair.Create(HashAlgorithmName.SHA512, 64) }); public CngKey Key { get { return _core.GetOrGenerateKey(KeySize, CngAlgorithm.Rsa); } private set { if (value.AlgorithmGroup != CngAlgorithmGroup.Rsa) { throw new ArgumentException(System.SR.Cryptography_ArgRSARequiresRSAKey, "value"); } _core.SetKey(value); ForceSetKeySize(value.KeySize); } } public override KeySizes[] LegalKeySizes => new KeySizes[1] { new KeySizes(512, 16384, 64) }; public RSACng(CngKey key) { if (key == null) { throw new ArgumentNullException("key"); } if (key.AlgorithmGroup != CngAlgorithmGroup.Rsa) { throw new ArgumentException(System.SR.Cryptography_ArgRSARequiresRSAKey, "key"); } Key = CngAlgorithmCore.Duplicate(key); } protected override void Dispose(bool disposing) { _core.Dispose(); } private void ThrowIfDisposed() { _core.ThrowIfDisposed(); } private void ImportKeyBlob(byte[] rsaBlob, bool includePrivate) { CngKeyBlobFormat format = (includePrivate ? s_rsaPrivateBlob : s_rsaPublicBlob); CngKey cngKey = CngKey.Import(rsaBlob, format); cngKey.ExportPolicy |= CngExportPolicies.AllowPlaintextExport; Key = cngKey; } private void AcceptImport(CngPkcs8.Pkcs8Response response) { Key = response.Key; } private byte[] ExportKeyBlob(bool includePrivateParameters) { return Key.Export(includePrivateParameters ? s_rsaFullPrivateBlob : s_rsaPublicBlob); } public override bool TryExportPkcs8PrivateKey(Span destination, out int bytesWritten) { return Key.TryExportKeyBlob("PKCS8_PRIVATEKEY", destination, out bytesWritten); } private byte[] ExportEncryptedPkcs8(ReadOnlySpan pkcs8Password, int kdfCount) { return Key.ExportPkcs8KeyBlob(pkcs8Password, kdfCount); } private bool TryExportEncryptedPkcs8(ReadOnlySpan pkcs8Password, int kdfCount, Span destination, out int bytesWritten) { return Key.TryExportPkcs8KeyBlob(pkcs8Password, kdfCount, destination, out bytesWritten); } private SafeNCryptKeyHandle GetDuplicatedKeyHandle() { return Key.Handle; } public RSACng() : this(2048) { } public RSACng(int keySize) { KeySize = keySize; } protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { return CngCommon.HashData(data, offset, count, hashAlgorithm); } protected override bool TryHashData(ReadOnlySpan data, Span destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) { return CngCommon.TryHashData(data, destination, hashAlgorithm, out bytesWritten); } protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { return CngCommon.HashData(data, hashAlgorithm); } private void ForceSetKeySize(int newKeySize) { KeySizeValue = newKeySize; } public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { return EncryptOrDecrypt(data, padding, encrypt: true); } public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { return EncryptOrDecrypt(data, padding, encrypt: false); } public override bool TryEncrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding, out int bytesWritten) { return TryEncryptOrDecrypt(data, destination, padding, encrypt: true, out bytesWritten); } public override bool TryDecrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding, out int bytesWritten) { return TryEncryptOrDecrypt(data, destination, padding, encrypt: false, out bytesWritten); } private unsafe byte[] EncryptOrDecrypt(byte[] data, RSAEncryptionPadding padding, bool encrypt) { if (data == null) { throw new ArgumentNullException("data"); } if (padding == null) { throw new ArgumentNullException("padding"); } int num = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize); if (!encrypt && data.Length != num) { throw new CryptographicException(System.SR.Cryptography_RSA_DecryptWrongSize); } if (encrypt && padding.Mode == RSAEncryptionPaddingMode.Pkcs1 && data.Length > num - 11) { throw new CryptographicException(System.SR.Format(System.SR.Cryptography_Encryption_MessageTooLong, num - 11)); } using SafeNCryptKeyHandle key = GetDuplicatedKeyHandle(); if (encrypt && data.Length == 0) { byte[] array = System.Security.Cryptography.CryptoPool.Rent(num); Span span = new Span(array, 0, num); try { if (padding == RSAEncryptionPadding.Pkcs1) { RsaPaddingProcessor.PadPkcs1Encryption(data, span); } else { if (padding.Mode != RSAEncryptionPaddingMode.Oaep) { throw new CryptographicException(System.SR.Cryptography_UnsupportedPaddingMode); } RsaPaddingProcessor rsaPaddingProcessor = RsaPaddingProcessor.OpenProcessor(padding.OaepHashAlgorithm); rsaPaddingProcessor.PadOaep(data, span); } return EncryptOrDecrypt(key, span, global::Interop.NCrypt.AsymmetricPaddingMode.NCRYPT_NO_PADDING_FLAG, null, encrypt); } finally { CryptographicOperations.ZeroMemory(span); System.Security.Cryptography.CryptoPool.Return(array, 0); } } switch (padding.Mode) { case RSAEncryptionPaddingMode.Pkcs1: return EncryptOrDecrypt(key, data, global::Interop.NCrypt.AsymmetricPaddingMode.NCRYPT_PAD_PKCS1_FLAG, null, encrypt); case RSAEncryptionPaddingMode.Oaep: { IntPtr intPtr = Marshal.StringToHGlobalUni(padding.OaepHashAlgorithm.Name); try { global::Interop.BCrypt.BCRYPT_OAEP_PADDING_INFO bCRYPT_OAEP_PADDING_INFO = default(global::Interop.BCrypt.BCRYPT_OAEP_PADDING_INFO); bCRYPT_OAEP_PADDING_INFO.pszAlgId = intPtr; bCRYPT_OAEP_PADDING_INFO.pbLabel = IntPtr.Zero; bCRYPT_OAEP_PADDING_INFO.cbLabel = 0; global::Interop.BCrypt.BCRYPT_OAEP_PADDING_INFO bCRYPT_OAEP_PADDING_INFO2 = bCRYPT_OAEP_PADDING_INFO; return EncryptOrDecrypt(key, data, global::Interop.NCrypt.AsymmetricPaddingMode.NCRYPT_PAD_OAEP_FLAG, &bCRYPT_OAEP_PADDING_INFO2, encrypt); } finally { Marshal.FreeHGlobal(intPtr); } } default: throw new CryptographicException(System.SR.Cryptography_UnsupportedPaddingMode); } } private unsafe bool TryEncryptOrDecrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding, bool encrypt, out int bytesWritten) { if (padding == null) { throw new ArgumentNullException("padding"); } int num = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize); if (!encrypt && data.Length != num) { throw new CryptographicException(System.SR.Cryptography_RSA_DecryptWrongSize); } if (encrypt && padding.Mode == RSAEncryptionPaddingMode.Pkcs1 && data.Length > num - 11) { throw new CryptographicException(System.SR.Format(System.SR.Cryptography_Encryption_MessageTooLong, num - 11)); } using SafeNCryptKeyHandle key = GetDuplicatedKeyHandle(); if (encrypt && data.Length == 0) { byte[] array = System.Security.Cryptography.CryptoPool.Rent(num); Span span = new Span(array, 0, num); try { if (padding == RSAEncryptionPadding.Pkcs1) { RsaPaddingProcessor.PadPkcs1Encryption(data, span); } else { if (padding.Mode != RSAEncryptionPaddingMode.Oaep) { throw new CryptographicException(System.SR.Cryptography_UnsupportedPaddingMode); } RsaPaddingProcessor rsaPaddingProcessor = RsaPaddingProcessor.OpenProcessor(padding.OaepHashAlgorithm); rsaPaddingProcessor.PadOaep(data, span); } return TryEncryptOrDecrypt(key, span, destination, global::Interop.NCrypt.AsymmetricPaddingMode.NCRYPT_NO_PADDING_FLAG, null, encrypt, out bytesWritten); } finally { CryptographicOperations.ZeroMemory(span); System.Security.Cryptography.CryptoPool.Return(array, 0); } } switch (padding.Mode) { case RSAEncryptionPaddingMode.Pkcs1: return TryEncryptOrDecrypt(key, data, destination, global::Interop.NCrypt.AsymmetricPaddingMode.NCRYPT_PAD_PKCS1_FLAG, null, encrypt, out bytesWritten); case RSAEncryptionPaddingMode.Oaep: { IntPtr intPtr = Marshal.StringToHGlobalUni(padding.OaepHashAlgorithm.Name); try { global::Interop.BCrypt.BCRYPT_OAEP_PADDING_INFO bCRYPT_OAEP_PADDING_INFO = default(global::Interop.BCrypt.BCRYPT_OAEP_PADDING_INFO); bCRYPT_OAEP_PADDING_INFO.pszAlgId = intPtr; bCRYPT_OAEP_PADDING_INFO.pbLabel = IntPtr.Zero; bCRYPT_OAEP_PADDING_INFO.cbLabel = 0; global::Interop.BCrypt.BCRYPT_OAEP_PADDING_INFO bCRYPT_OAEP_PADDING_INFO2 = bCRYPT_OAEP_PADDING_INFO; return TryEncryptOrDecrypt(key, data, destination, global::Interop.NCrypt.AsymmetricPaddingMode.NCRYPT_PAD_OAEP_FLAG, &bCRYPT_OAEP_PADDING_INFO2, encrypt, out bytesWritten); } finally { Marshal.FreeHGlobal(intPtr); } } default: throw new CryptographicException(System.SR.Cryptography_UnsupportedPaddingMode); } } private unsafe byte[] EncryptOrDecrypt(SafeNCryptKeyHandle key, ReadOnlySpan input, global::Interop.NCrypt.AsymmetricPaddingMode paddingMode, void* paddingInfo, bool encrypt) { int num = KeySize / 8; byte[] array = new byte[num]; int bytesNeeded = 0; global::Interop.NCrypt.ErrorCode errorCode = global::Interop.NCrypt.ErrorCode.ERROR_SUCCESS; for (int i = 0; i <= 1; i++) { errorCode = EncryptOrDecrypt(key, input, array, paddingMode, paddingInfo, encrypt, out bytesNeeded); if (errorCode != global::Interop.NCrypt.ErrorCode.STATUS_UNSUCCESSFUL) { break; } } if (errorCode == global::Interop.NCrypt.ErrorCode.NTE_BUFFER_TOO_SMALL) { CryptographicOperations.ZeroMemory(array); array = new byte[bytesNeeded]; for (int j = 0; j <= 1; j++) { errorCode = EncryptOrDecrypt(key, input, array, paddingMode, paddingInfo, encrypt, out bytesNeeded); if (errorCode != global::Interop.NCrypt.ErrorCode.STATUS_UNSUCCESSFUL) { break; } } } if (errorCode != 0) { throw errorCode.ToCryptographicException(); } if (bytesNeeded != array.Length) { byte[] array2 = array.AsSpan(0, bytesNeeded).ToArray(); CryptographicOperations.ZeroMemory(array); array = array2; } return array; } private unsafe bool TryEncryptOrDecrypt(SafeNCryptKeyHandle key, ReadOnlySpan input, Span output, global::Interop.NCrypt.AsymmetricPaddingMode paddingMode, void* paddingInfo, bool encrypt, out int bytesWritten) { for (int i = 0; i <= 1; i++) { int bytesNeeded; global::Interop.NCrypt.ErrorCode errorCode = EncryptOrDecrypt(key, input, output, paddingMode, paddingInfo, encrypt, out bytesNeeded); switch (errorCode) { case global::Interop.NCrypt.ErrorCode.ERROR_SUCCESS: bytesWritten = bytesNeeded; return true; case global::Interop.NCrypt.ErrorCode.NTE_BUFFER_TOO_SMALL: bytesWritten = 0; return false; default: throw errorCode.ToCryptographicException(); case global::Interop.NCrypt.ErrorCode.STATUS_UNSUCCESSFUL: break; } } throw global::Interop.NCrypt.ErrorCode.STATUS_UNSUCCESSFUL.ToCryptographicException(); } private unsafe static global::Interop.NCrypt.ErrorCode EncryptOrDecrypt(SafeNCryptKeyHandle key, ReadOnlySpan input, Span output, global::Interop.NCrypt.AsymmetricPaddingMode paddingMode, void* paddingInfo, bool encrypt, out int bytesNeeded) { global::Interop.NCrypt.ErrorCode errorCode = (encrypt ? global::Interop.NCrypt.NCryptEncrypt(key, input, input.Length, paddingInfo, output, output.Length, out bytesNeeded, paddingMode) : global::Interop.NCrypt.NCryptDecrypt(key, input, input.Length, paddingInfo, output, output.Length, out bytesNeeded, paddingMode)); if (errorCode == global::Interop.NCrypt.ErrorCode.ERROR_SUCCESS && bytesNeeded > output.Length) { errorCode = global::Interop.NCrypt.ErrorCode.NTE_BUFFER_TOO_SMALL; } return errorCode; } public unsafe override void ImportParameters(RSAParameters parameters) { if (parameters.Exponent == null || parameters.Modulus == null) { throw new CryptographicException(System.SR.Cryptography_InvalidRsaParameters); } bool flag; if (parameters.D == null) { flag = false; if (parameters.P != null || parameters.DP != null || parameters.Q != null || parameters.DQ != null || parameters.InverseQ != null) { throw new CryptographicException(System.SR.Cryptography_InvalidRsaParameters); } } else { flag = true; if (parameters.P == null || parameters.DP == null || parameters.Q == null || parameters.DQ == null || parameters.InverseQ == null) { throw new CryptographicException(System.SR.Cryptography_InvalidRsaParameters); } int num = (parameters.Modulus.Length + 1) / 2; if (parameters.D.Length != parameters.Modulus.Length || parameters.P.Length != num || parameters.Q.Length != num || parameters.DP.Length != num || parameters.DQ.Length != num || parameters.InverseQ.Length != num) { throw new CryptographicException(System.SR.Cryptography_InvalidRsaParameters); } } int num2 = sizeof(global::Interop.BCrypt.BCRYPT_RSAKEY_BLOB) + parameters.Exponent.Length + parameters.Modulus.Length; if (flag) { num2 += parameters.P.Length + parameters.Q.Length; } byte[] array = new byte[num2]; fixed (byte* ptr = &array[0]) { global::Interop.BCrypt.BCRYPT_RSAKEY_BLOB* ptr2 = (global::Interop.BCrypt.BCRYPT_RSAKEY_BLOB*)ptr; ptr2->Magic = (flag ? global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_RSAPRIVATE_MAGIC : global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_RSAPUBLIC_MAGIC); ptr2->BitLength = parameters.Modulus.Length * 8; ptr2->cbPublicExp = parameters.Exponent.Length; ptr2->cbModulus = parameters.Modulus.Length; if (flag) { ptr2->cbPrime1 = parameters.P.Length; ptr2->cbPrime2 = parameters.Q.Length; } int offset = sizeof(global::Interop.BCrypt.BCRYPT_RSAKEY_BLOB); global::Interop.BCrypt.Emit(array, ref offset, parameters.Exponent); global::Interop.BCrypt.Emit(array, ref offset, parameters.Modulus); if (flag) { global::Interop.BCrypt.Emit(array, ref offset, parameters.P); global::Interop.BCrypt.Emit(array, ref offset, parameters.Q); } } ImportKeyBlob(array, flag); } public override void ImportPkcs8PrivateKey(ReadOnlySpan source, out int bytesRead) { ThrowIfDisposed(); int bytesRead2; CngPkcs8.Pkcs8Response response = CngPkcs8.ImportPkcs8PrivateKey(source, out bytesRead2); ProcessPkcs8Response(response); bytesRead = bytesRead2; } public override void ImportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, ReadOnlySpan source, out int bytesRead) { ThrowIfDisposed(); int bytesRead2; CngPkcs8.Pkcs8Response response = CngPkcs8.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead2); ProcessPkcs8Response(response); bytesRead = bytesRead2; } public override void ImportEncryptedPkcs8PrivateKey(ReadOnlySpan password, ReadOnlySpan source, out int bytesRead) { ThrowIfDisposed(); int bytesRead2; CngPkcs8.Pkcs8Response response = CngPkcs8.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead2); ProcessPkcs8Response(response); bytesRead = bytesRead2; } private void ProcessPkcs8Response(CngPkcs8.Pkcs8Response response) { if (response.GetAlgorithmGroup() != "RSA") { response.FreeKey(); throw new CryptographicException(System.SR.Cryptography_NotValidPublicOrPrivateKey); } AcceptImport(response); } public override byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } return CngPkcs8.ExportEncryptedPkcs8PrivateKey(this, passwordBytes, pbeParameters); } public override byte[] ExportEncryptedPkcs8PrivateKey(ReadOnlySpan password, PbeParameters pbeParameters) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } System.Security.Cryptography.PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, password, ReadOnlySpan.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return ExportEncryptedPkcs8(password, pbeParameters.IterationCount); } return CngPkcs8.ExportEncryptedPkcs8PrivateKey(this, password, pbeParameters); } public override bool TryExportEncryptedPkcs8PrivateKey(ReadOnlySpan passwordBytes, PbeParameters pbeParameters, Span destination, out int bytesWritten) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } System.Security.Cryptography.PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, ReadOnlySpan.Empty, passwordBytes); return CngPkcs8.TryExportEncryptedPkcs8PrivateKey(this, passwordBytes, pbeParameters, destination, out bytesWritten); } public override bool TryExportEncryptedPkcs8PrivateKey(ReadOnlySpan password, PbeParameters pbeParameters, Span destination, out int bytesWritten) { if (pbeParameters == null) { throw new ArgumentNullException("pbeParameters"); } System.Security.Cryptography.PasswordBasedEncryption.ValidatePbeParameters(pbeParameters, password, ReadOnlySpan.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return TryExportEncryptedPkcs8(password, pbeParameters.IterationCount, destination, out bytesWritten); } return CngPkcs8.TryExportEncryptedPkcs8PrivateKey(this, password, pbeParameters, destination, out bytesWritten); } public override RSAParameters ExportParameters(bool includePrivateParameters) { byte[] rsaBlob = ExportKeyBlob(includePrivateParameters); RSAParameters rsaParams = default(RSAParameters); ExportParameters(ref rsaParams, rsaBlob, includePrivateParameters); return rsaParams; } private unsafe static void ExportParameters(ref RSAParameters rsaParams, byte[] rsaBlob, bool includePrivateParameters) { global::Interop.BCrypt.KeyBlobMagicNumber magic = (global::Interop.BCrypt.KeyBlobMagicNumber)BitConverter.ToInt32(rsaBlob, 0); CheckMagicValueOfKey(magic, includePrivateParameters); if (rsaBlob.Length < sizeof(global::Interop.BCrypt.BCRYPT_RSAKEY_BLOB)) { throw global::Interop.NCrypt.ErrorCode.E_FAIL.ToCryptographicException(); } fixed (byte* ptr = &rsaBlob[0]) { global::Interop.BCrypt.BCRYPT_RSAKEY_BLOB* ptr2 = (global::Interop.BCrypt.BCRYPT_RSAKEY_BLOB*)ptr; int offset = sizeof(global::Interop.BCrypt.BCRYPT_RSAKEY_BLOB); rsaParams.Exponent = global::Interop.BCrypt.Consume(rsaBlob, ref offset, ptr2->cbPublicExp); rsaParams.Modulus = global::Interop.BCrypt.Consume(rsaBlob, ref offset, ptr2->cbModulus); if (includePrivateParameters) { rsaParams.P = global::Interop.BCrypt.Consume(rsaBlob, ref offset, ptr2->cbPrime1); rsaParams.Q = global::Interop.BCrypt.Consume(rsaBlob, ref offset, ptr2->cbPrime2); rsaParams.DP = global::Interop.BCrypt.Consume(rsaBlob, ref offset, ptr2->cbPrime1); rsaParams.DQ = global::Interop.BCrypt.Consume(rsaBlob, ref offset, ptr2->cbPrime2); rsaParams.InverseQ = global::Interop.BCrypt.Consume(rsaBlob, ref offset, ptr2->cbPrime1); rsaParams.D = global::Interop.BCrypt.Consume(rsaBlob, ref offset, ptr2->cbModulus); } } } private static void CheckMagicValueOfKey(global::Interop.BCrypt.KeyBlobMagicNumber magic, bool includePrivateParameters) { if (includePrivateParameters) { if (magic != global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_RSAPRIVATE_MAGIC && magic != global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_RSAFULLPRIVATE_MAGIC) { throw new CryptographicException(System.SR.Cryptography_NotValidPrivateKey); } } else if (magic != global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_RSAPUBLIC_MAGIC && magic != global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_RSAPRIVATE_MAGIC && magic != global::Interop.BCrypt.KeyBlobMagicNumber.BCRYPT_RSAFULLPRIVATE_MAGIC) { throw new CryptographicException(System.SR.Cryptography_NotValidPublicOrPrivateKey); } } private static int GetHashSizeInBytes(HashAlgorithmName hashAlgorithm) { return s_hashSizes.GetOrAdd(hashAlgorithm, delegate(HashAlgorithmName hashAlgorithm) { using HashProviderCng hashProviderCng = new HashProviderCng(hashAlgorithm.Name, null); return hashProviderCng.HashSizeInBytes; }); } public unsafe override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hash == null) { throw new ArgumentNullException("hash"); } string name = hashAlgorithm.Name; if (string.IsNullOrEmpty(name)) { throw new ArgumentException(System.SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); } if (padding == null) { throw new ArgumentNullException("padding"); } if (hash.Length != GetHashSizeInBytes(hashAlgorithm)) { throw new CryptographicException(System.SR.Cryptography_SignHash_WrongSize); } using SafeNCryptKeyHandle keyHandle = GetDuplicatedKeyHandle(); IntPtr intPtr = Marshal.StringToHGlobalUni(name); try { int estimatedSize = KeySize / 8; switch (padding.Mode) { case RSASignaturePaddingMode.Pkcs1: { global::Interop.BCrypt.BCRYPT_PKCS1_PADDING_INFO bCRYPT_PKCS1_PADDING_INFO = default(global::Interop.BCrypt.BCRYPT_PKCS1_PADDING_INFO); bCRYPT_PKCS1_PADDING_INFO.pszAlgId = intPtr; global::Interop.BCrypt.BCRYPT_PKCS1_PADDING_INFO bCRYPT_PKCS1_PADDING_INFO2 = bCRYPT_PKCS1_PADDING_INFO; return keyHandle.SignHash(hash, global::Interop.NCrypt.AsymmetricPaddingMode.NCRYPT_PAD_PKCS1_FLAG, &bCRYPT_PKCS1_PADDING_INFO2, estimatedSize); } case RSASignaturePaddingMode.Pss: { global::Interop.BCrypt.BCRYPT_PSS_PADDING_INFO bCRYPT_PSS_PADDING_INFO = default(global::Interop.BCrypt.BCRYPT_PSS_PADDING_INFO); bCRYPT_PSS_PADDING_INFO.pszAlgId = intPtr; bCRYPT_PSS_PADDING_INFO.cbSalt = hash.Length; global::Interop.BCrypt.BCRYPT_PSS_PADDING_INFO bCRYPT_PSS_PADDING_INFO2 = bCRYPT_PSS_PADDING_INFO; return keyHandle.SignHash(hash, global::Interop.NCrypt.AsymmetricPaddingMode.NCRYPT_PAD_PSS_FLAG, &bCRYPT_PSS_PADDING_INFO2, estimatedSize); } default: throw new CryptographicException(System.SR.Cryptography_UnsupportedPaddingMode); } } finally { Marshal.FreeHGlobal(intPtr); } } public unsafe override bool TrySignHash(ReadOnlySpan hash, Span destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) { string name = hashAlgorithm.Name; if (string.IsNullOrEmpty(name)) { throw new ArgumentException(System.SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); } if (padding == null) { throw new ArgumentNullException("padding"); } using SafeNCryptKeyHandle keyHandle = GetDuplicatedKeyHandle(); if (hash.Length != GetHashSizeInBytes(hashAlgorithm)) { throw new CryptographicException(System.SR.Cryptography_SignHash_WrongSize); } IntPtr intPtr = Marshal.StringToHGlobalUni(name); try { switch (padding.Mode) { case RSASignaturePaddingMode.Pkcs1: { global::Interop.BCrypt.BCRYPT_PKCS1_PADDING_INFO bCRYPT_PKCS1_PADDING_INFO = default(global::Interop.BCrypt.BCRYPT_PKCS1_PADDING_INFO); bCRYPT_PKCS1_PADDING_INFO.pszAlgId = intPtr; global::Interop.BCrypt.BCRYPT_PKCS1_PADDING_INFO bCRYPT_PKCS1_PADDING_INFO2 = bCRYPT_PKCS1_PADDING_INFO; return keyHandle.TrySignHash(hash, destination, global::Interop.NCrypt.AsymmetricPaddingMode.NCRYPT_PAD_PKCS1_FLAG, &bCRYPT_PKCS1_PADDING_INFO2, out bytesWritten); } case RSASignaturePaddingMode.Pss: { global::Interop.BCrypt.BCRYPT_PSS_PADDING_INFO bCRYPT_PSS_PADDING_INFO = default(global::Interop.BCrypt.BCRYPT_PSS_PADDING_INFO); bCRYPT_PSS_PADDING_INFO.pszAlgId = intPtr; bCRYPT_PSS_PADDING_INFO.cbSalt = hash.Length; global::Interop.BCrypt.BCRYPT_PSS_PADDING_INFO bCRYPT_PSS_PADDING_INFO2 = bCRYPT_PSS_PADDING_INFO; return keyHandle.TrySignHash(hash, destination, global::Interop.NCrypt.AsymmetricPaddingMode.NCRYPT_PAD_PSS_FLAG, &bCRYPT_PSS_PADDING_INFO2, out bytesWritten); } default: throw new CryptographicException(System.SR.Cryptography_UnsupportedPaddingMode); } } finally { Marshal.FreeHGlobal(intPtr); } } public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hash == null) { throw new ArgumentNullException("hash"); } if (signature == null) { throw new ArgumentNullException("signature"); } return VerifyHash((ReadOnlySpan)hash, (ReadOnlySpan)signature, hashAlgorithm, padding); } public unsafe override bool VerifyHash(ReadOnlySpan hash, ReadOnlySpan signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { string name = hashAlgorithm.Name; if (string.IsNullOrEmpty(name)) { throw new ArgumentException(System.SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); } if (padding == null) { throw new ArgumentNullException("padding"); } using SafeNCryptKeyHandle keyHandle = GetDuplicatedKeyHandle(); if (hash.Length != GetHashSizeInBytes(hashAlgorithm)) { return false; } IntPtr intPtr = Marshal.StringToHGlobalUni(name); try { switch (padding.Mode) { case RSASignaturePaddingMode.Pkcs1: { global::Interop.BCrypt.BCRYPT_PKCS1_PADDING_INFO bCRYPT_PKCS1_PADDING_INFO = default(global::Interop.BCrypt.BCRYPT_PKCS1_PADDING_INFO); bCRYPT_PKCS1_PADDING_INFO.pszAlgId = intPtr; global::Interop.BCrypt.BCRYPT_PKCS1_PADDING_INFO bCRYPT_PKCS1_PADDING_INFO2 = bCRYPT_PKCS1_PADDING_INFO; return keyHandle.VerifyHash(hash, signature, global::Interop.NCrypt.AsymmetricPaddingMode.NCRYPT_PAD_PKCS1_FLAG, &bCRYPT_PKCS1_PADDING_INFO2); } case RSASignaturePaddingMode.Pss: { global::Interop.BCrypt.BCRYPT_PSS_PADDING_INFO bCRYPT_PSS_PADDING_INFO = default(global::Interop.BCrypt.BCRYPT_PSS_PADDING_INFO); bCRYPT_PSS_PADDING_INFO.pszAlgId = intPtr; bCRYPT_PSS_PADDING_INFO.cbSalt = hash.Length; global::Interop.BCrypt.BCRYPT_PSS_PADDING_INFO bCRYPT_PSS_PADDING_INFO2 = bCRYPT_PSS_PADDING_INFO; return keyHandle.VerifyHash(hash, signature, global::Interop.NCrypt.AsymmetricPaddingMode.NCRYPT_PAD_PSS_FLAG, &bCRYPT_PSS_PADDING_INFO2); } default: throw new CryptographicException(System.SR.Cryptography_UnsupportedPaddingMode); } } finally { Marshal.FreeHGlobal(intPtr); } } } public sealed class TripleDESCng : TripleDES, ICngSymmetricAlgorithm { private CngSymmetricAlgorithmCore _core; public override byte[] Key { get { return _core.GetKeyIfExportable(); } set { _core.SetKey(value); } } public override int KeySize { get { return base.KeySize; } set { _core.SetKeySize(value, this); } } byte[] ICngSymmetricAlgorithm.BaseKey { get { return base.Key; } set { base.Key = value; } } int ICngSymmetricAlgorithm.BaseKeySize { get { return base.KeySize; } set { base.KeySize = value; } } public TripleDESCng() { _core = new CngSymmetricAlgorithmCore(this); } public TripleDESCng(string keyName) : this(keyName, CngProvider.MicrosoftSoftwareKeyStorageProvider) { } public TripleDESCng(string keyName, CngProvider provider) : this(keyName, provider, CngKeyOpenOptions.None) { } public TripleDESCng(string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { _core = new CngSymmetricAlgorithmCore(this, keyName, provider, openOptions); } public override ICryptoTransform CreateDecryptor() { return _core.CreateDecryptor(); } public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) { return _core.CreateDecryptor(rgbKey, rgbIV); } public override ICryptoTransform CreateEncryptor() { return _core.CreateEncryptor(); } public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) { return _core.CreateEncryptor(rgbKey, rgbIV); } public override void GenerateKey() { _core.GenerateKey(); } public override void GenerateIV() { _core.GenerateIV(); } protected override bool TryDecryptEcbCore(ReadOnlySpan ciphertext, Span destination, PaddingMode paddingMode, out int bytesWritten) { Internal.Cryptography.UniversalCryptoTransform universalCryptoTransform = _core.CreateCryptoTransform(null, encrypting: false, paddingMode, CipherMode.ECB, 0); using (universalCryptoTransform) { return universalCryptoTransform.TransformOneShot(ciphertext, destination, out bytesWritten); } } protected override bool TryEncryptEcbCore(ReadOnlySpan plaintext, Span destination, PaddingMode paddingMode, out int bytesWritten) { Internal.Cryptography.UniversalCryptoTransform universalCryptoTransform = _core.CreateCryptoTransform(null, encrypting: true, paddingMode, CipherMode.ECB, 0); using (universalCryptoTransform) { return universalCryptoTransform.TransformOneShot(plaintext, destination, out bytesWritten); } } protected override bool TryEncryptCbcCore(ReadOnlySpan plaintext, ReadOnlySpan iv, Span destination, PaddingMode paddingMode, out int bytesWritten) { Internal.Cryptography.UniversalCryptoTransform universalCryptoTransform = _core.CreateCryptoTransform(iv.ToArray(), encrypting: true, paddingMode, CipherMode.CBC, 0); using (universalCryptoTransform) { return universalCryptoTransform.TransformOneShot(plaintext, destination, out bytesWritten); } } protected override bool TryDecryptCbcCore(ReadOnlySpan ciphertext, ReadOnlySpan iv, Span destination, PaddingMode paddingMode, out int bytesWritten) { Internal.Cryptography.UniversalCryptoTransform universalCryptoTransform = _core.CreateCryptoTransform(iv.ToArray(), encrypting: false, paddingMode, CipherMode.CBC, 0); using (universalCryptoTransform) { return universalCryptoTransform.TransformOneShot(ciphertext, destination, out bytesWritten); } } protected override bool TryDecryptCfbCore(ReadOnlySpan ciphertext, ReadOnlySpan iv, Span destination, PaddingMode paddingMode, int feedbackSizeInBits, out int bytesWritten) { Internal.Cryptography.UniversalCryptoTransform universalCryptoTransform = _core.CreateCryptoTransform(iv.ToArray(), encrypting: false, paddingMode, CipherMode.CFB, feedbackSizeInBits); using (universalCryptoTransform) { return universalCryptoTransform.TransformOneShot(ciphertext, destination, out bytesWritten); } } protected override bool TryEncryptCfbCore(ReadOnlySpan plaintext, ReadOnlySpan iv, Span destination, PaddingMode paddingMode, int feedbackSizeInBits, out int bytesWritten) { Internal.Cryptography.UniversalCryptoTransform universalCryptoTransform = _core.CreateCryptoTransform(iv.ToArray(), encrypting: true, paddingMode, CipherMode.CFB, feedbackSizeInBits); using (universalCryptoTransform) { return universalCryptoTransform.TransformOneShot(plaintext, destination, out bytesWritten); } } protected override void Dispose(bool disposing) { base.Dispose(disposing); } bool ICngSymmetricAlgorithm.IsWeakKey(byte[] key) { return TripleDES.IsWeakKey(key); } int ICngSymmetricAlgorithm.GetPaddingSize(CipherMode mode, int feedbackSizeBits) { return this.GetPaddingSize(mode, feedbackSizeBits); } SafeAlgorithmHandle ICngSymmetricAlgorithm.GetEphemeralModeHandle(CipherMode mode, int feedbackSizeInBits) { return TripleDesBCryptModes.GetSharedHandle(mode, feedbackSizeInBits / 8); } string ICngSymmetricAlgorithm.GetNCryptAlgorithmIdentifier() { return "3DES"; } byte[] ICngSymmetricAlgorithm.PreprocessKey(byte[] key) { if (key.Length == 16) { byte[] array = new byte[24]; Array.Copy(key, array, 16); Array.Copy(key, 0, array, 16, 8); return array; } return key; } bool ICngSymmetricAlgorithm.IsValidEphemeralFeedbackSize(int feedbackSizeInBits) { if (feedbackSizeInBits != 8) { return feedbackSizeInBits == 64; } return true; } } internal static class CryptoPool { internal static byte[] Rent(int minimumLength) { return ArrayPool.Shared.Rent(minimumLength); } internal static void Return(ArraySegment 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.Shared.Return(array, flag); } } internal static class EccKeyFormatHelper { internal static void FromECPrivateKey(System.Security.Cryptography.Asn1.ECPrivateKey key, in System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn algId, out ECParameters ret) { ValidateParameters(key.Parameters, in algId); if (key.Version != 1) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } byte[] x = null; byte[] y = null; if (key.PublicKey.HasValue) { ReadOnlySpan span = key.PublicKey.Value.Span; if (span.Length == 0) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } if (span[0] != 4) { throw new CryptographicException(System.SR.Cryptography_NotValidPublicOrPrivateKey); } if (span.Length != 2 * key.PrivateKey.Length + 1) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } x = span.Slice(1, key.PrivateKey.Length).ToArray(); y = span.Slice(1 + key.PrivateKey.Length).ToArray(); } System.Security.Cryptography.Asn1.ECDomainParameters domainParameters = ((!key.Parameters.HasValue) ? System.Security.Cryptography.Asn1.ECDomainParameters.Decode(algId.Parameters.Value, AsnEncodingRules.DER) : key.Parameters.Value); ret = new ECParameters { Curve = GetCurve(domainParameters), Q = { X = x, Y = y }, D = key.PrivateKey.ToArray() }; ret.Validate(); } private static void ValidateParameters(System.Security.Cryptography.Asn1.ECDomainParameters? keyParameters, in System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn algId) { if (!keyParameters.HasValue && !algId.Parameters.HasValue) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } if (keyParameters.HasValue && algId.Parameters.HasValue) { ReadOnlySpan span = algId.Parameters.Value.Span; AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.DER); keyParameters.Value.Encode(asnWriter); if (!asnWriter.EncodedValueEquals(span)) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } } } private static ECCurve GetCurve(System.Security.Cryptography.Asn1.ECDomainParameters domainParameters) { if (domainParameters.Specified.HasValue) { return GetSpecifiedECCurve(domainParameters.Specified.Value); } if (domainParameters.Named == null) { throw new CryptographicException(System.SR.Cryptography_ECC_NamedCurvesOnly); } return ECCurve.CreateFromOid(domainParameters.Named switch { "1.2.840.10045.3.1.7" => System.Security.Cryptography.Oids.secp256r1Oid, "1.3.132.0.34" => System.Security.Cryptography.Oids.secp384r1Oid, "1.3.132.0.35" => System.Security.Cryptography.Oids.secp521r1Oid, _ => new Oid(domainParameters.Named, null), }); } private static ECCurve GetSpecifiedECCurve(System.Security.Cryptography.Asn1.SpecifiedECDomain specifiedParameters) { try { return GetSpecifiedECCurveCore(specifiedParameters); } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static ECCurve GetSpecifiedECCurveCore(System.Security.Cryptography.Asn1.SpecifiedECDomain specifiedParameters) { if (specifiedParameters.Version < 1 || specifiedParameters.Version > 3) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } if (specifiedParameters.Version > 1 && !specifiedParameters.Curve.Seed.HasValue) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } string fieldType = specifiedParameters.FieldID.FieldType; bool flag; byte[] array; if (!(fieldType == "1.2.840.10045.1.1")) { if (!(fieldType == "1.2.840.10045.1.2")) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } flag = false; AsnReader asnReader = new AsnReader(specifiedParameters.FieldID.Parameters, AsnEncodingRules.BER); AsnReader asnReader2 = asnReader.ReadSequence(); asnReader.ThrowIfNotEmpty(); if (!asnReader2.TryReadInt32(out var value) || value > 661 || value < 0) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } int value2 = -1; int value3 = -1; string text = asnReader2.ReadObjectIdentifier(); int value4; if (!(text == "1.2.840.10045.1.2.3.2")) { if (!(text == "1.2.840.10045.1.2.3.3")) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } AsnReader asnReader3 = asnReader2.ReadSequence(); if (!asnReader3.TryReadInt32(out value4) || !asnReader3.TryReadInt32(out value2) || !asnReader3.TryReadInt32(out value3) || value4 < 1 || value2 <= value4 || value3 <= value2 || value3 >= value) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } asnReader3.ThrowIfNotEmpty(); } else if (!asnReader2.TryReadInt32(out value4) || value4 >= value || value4 < 1) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } asnReader2.ThrowIfNotEmpty(); BitArray bitArray = new BitArray(value + 1); bitArray.Set(value, value: true); bitArray.Set(value4, value: true); bitArray.Set(0, value: true); if (value2 > 0) { bitArray.Set(value2, value: true); bitArray.Set(value3, value: true); } array = new byte[(value + 7) / 8]; bitArray.CopyTo(array, 0); Array.Reverse(array); } else { flag = true; AsnReader asnReader4 = new AsnReader(specifiedParameters.FieldID.Parameters, AsnEncodingRules.BER); ReadOnlySpan readOnlySpan = asnReader4.ReadIntegerBytes().Span; asnReader4.ThrowIfNotEmpty(); if (readOnlySpan[0] == 0) { readOnlySpan = readOnlySpan.Slice(1); } if (readOnlySpan.Length > 82) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } array = readOnlySpan.ToArray(); } ECCurve result; if (flag) { ECCurve eCCurve = default(ECCurve); eCCurve.CurveType = ECCurve.ECCurveType.PrimeShortWeierstrass; eCCurve.Prime = array; result = eCCurve; } else { ECCurve eCCurve = default(ECCurve); eCCurve.CurveType = ECCurve.ECCurveType.Characteristic2; eCCurve.Polynomial = array; result = eCCurve; } result.A = specifiedParameters.Curve.A.ToUnsignedIntegerBytes(array.Length); result.B = specifiedParameters.Curve.B.ToUnsignedIntegerBytes(array.Length); result.Order = specifiedParameters.Order.ToUnsignedIntegerBytes(array.Length); ReadOnlySpan span = specifiedParameters.Base.Span; if (span[0] != 4 || span.Length != 2 * array.Length + 1) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } result.G.X = span.Slice(1, array.Length).ToArray(); result.G.Y = span.Slice(1 + array.Length).ToArray(); if (specifiedParameters.Cofactor.HasValue) { result.Cofactor = specifiedParameters.Cofactor.Value.ToUnsignedIntegerBytes(); } return result; } private static AsnWriter WriteAlgorithmIdentifier(in ECParameters ecParameters) { AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.DER); WriteAlgorithmIdentifier(in ecParameters, asnWriter); return asnWriter; } private static void WriteAlgorithmIdentifier(in ECParameters ecParameters, AsnWriter writer) { writer.PushSequence(); writer.WriteObjectIdentifier("1.2.840.10045.2.1"); WriteEcParameters(ecParameters, writer); writer.PopSequence(); } internal static AsnWriter WritePkcs8PrivateKey(ECParameters ecParameters, System.Security.Cryptography.Asn1.AttributeAsn[] attributes = null) { ecParameters.Validate(); if (ecParameters.D == null) { throw new CryptographicException(System.SR.Cryptography_CSP_NoPrivateKey); } AsnWriter privateKeyWriter = WriteEcPrivateKey(in ecParameters, includeDomainParameters: false); AsnWriter algorithmIdentifierWriter = WriteAlgorithmIdentifier(in ecParameters); AsnWriter attributesWriter = WritePrivateKeyInfoAttributes(attributes); return System.Security.Cryptography.KeyFormatHelper.WritePkcs8(algorithmIdentifierWriter, privateKeyWriter, attributesWriter); } [return: NotNullIfNotNull("attributes")] private static AsnWriter WritePrivateKeyInfoAttributes(System.Security.Cryptography.Asn1.AttributeAsn[] attributes) { if (attributes == null) { return null; } AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.DER); Asn1Tag value = new Asn1Tag(TagClass.ContextSpecific, 0); asnWriter.PushSetOf(value); for (int i = 0; i < attributes.Length; i++) { attributes[i].Encode(asnWriter); } asnWriter.PopSetOf(value); return asnWriter; } private static void WriteEcParameters(ECParameters ecParameters, AsnWriter writer) { if (ecParameters.Curve.IsNamed) { Oid oid = ecParameters.Curve.Oid; if (string.IsNullOrEmpty(oid.Value)) { oid = Oid.FromFriendlyName(oid.FriendlyName, OidGroup.All); } writer.WriteObjectIdentifier(oid.Value); } else { if (!ecParameters.Curve.IsExplicit) { throw new CryptographicException(System.SR.Format(System.SR.Cryptography_CurveNotSupported, ecParameters.Curve.CurveType.ToString())); } WriteSpecifiedECDomain(ecParameters, writer); } } private static void WriteSpecifiedECDomain(ECParameters ecParameters, AsnWriter writer) { int k3; int k2; int k; int m = (k3 = (k2 = (k = -1))); if (ecParameters.Curve.IsCharacteristic2) { DetermineChar2Parameters(in ecParameters, ref m, ref k3, ref k2, ref k); } writer.PushSequence(); writer.WriteInteger(1L); writer.PushSequence(); if (ecParameters.Curve.IsPrime) { writer.WriteObjectIdentifier("1.2.840.10045.1.1"); writer.WriteIntegerUnsigned(ecParameters.Curve.Prime); } else { writer.WriteObjectIdentifier("1.2.840.10045.1.2"); writer.PushSequence(); writer.WriteInteger((long)m, (Asn1Tag?)null); if (k > 0) { writer.WriteObjectIdentifier("1.2.840.10045.1.2.3.3"); writer.PushSequence(); writer.WriteInteger((long)k3, (Asn1Tag?)null); writer.WriteInteger((long)k2, (Asn1Tag?)null); writer.WriteInteger((long)k, (Asn1Tag?)null); writer.PopSequence(); } else { writer.WriteObjectIdentifier("1.2.840.10045.1.2.3.2"); writer.WriteInteger((long)k3, (Asn1Tag?)null); } writer.PopSequence(); } writer.PopSequence(); WriteCurve(in ecParameters.Curve, writer); WriteUncompressedBasePoint(in ecParameters, writer); writer.WriteIntegerUnsigned(ecParameters.Curve.Order); if (ecParameters.Curve.Cofactor != null) { writer.WriteIntegerUnsigned(ecParameters.Curve.Cofactor); } writer.PopSequence(); } private static void DetermineChar2Parameters(in ECParameters ecParameters, ref int m, ref int k1, ref int k2, ref int k3) { byte[] polynomial = ecParameters.Curve.Polynomial; int num = polynomial.Length - 1; if (polynomial[0] == 0 || (polynomial[num] & 1) != 1) { throw new CryptographicException(System.SR.Cryptography_InvalidECCharacteristic2Curve); } for (int num2 = 7; num2 >= 0; num2--) { int num3 = 1 << num2; if ((polynomial[0] & num3) == num3) { m = checked(8 * num + num2); } } for (int i = 0; i < polynomial.Length; i++) { int num4 = num - i; byte b = polynomial[num4]; for (int j = 0; j < 8; j++) { int num5 = 1 << j; if ((b & num5) != num5) { continue; } int num6 = 8 * i + j; if (num6 == 0) { continue; } if (num6 == m) { break; } if (k1 < 0) { k1 = num6; continue; } if (k2 < 0) { k2 = num6; continue; } if (k3 < 0) { k3 = num6; continue; } throw new CryptographicException(System.SR.Cryptography_InvalidECCharacteristic2Curve); } } if (k3 <= 0) { if (k2 > 0) { throw new CryptographicException(System.SR.Cryptography_InvalidECCharacteristic2Curve); } if (k1 <= 0) { throw new CryptographicException(System.SR.Cryptography_InvalidECCharacteristic2Curve); } } } private static void WriteCurve(in ECCurve curve, AsnWriter writer) { writer.PushSequence(); WriteFieldElement(curve.A, writer); WriteFieldElement(curve.B, writer); if (curve.Seed != null) { writer.WriteBitString(curve.Seed); } writer.PopSequence(); } private static void WriteFieldElement(byte[] fieldElement, AsnWriter writer) { int i; for (i = 0; i < fieldElement.Length - 1 && fieldElement[i] == 0; i++) { } writer.WriteOctetString(fieldElement.AsSpan(i)); } private static void WriteUncompressedBasePoint(in ECParameters ecParameters, AsnWriter writer) { int num = ecParameters.Curve.G.X.Length * 2 + 1; byte[] array = System.Security.Cryptography.CryptoPool.Rent(num); array[0] = 4; ecParameters.Curve.G.X.CopyTo(array.AsSpan(1)); ecParameters.Curve.G.Y.CopyTo(array.AsSpan(1 + ecParameters.Curve.G.X.Length)); writer.WriteOctetString(array.AsSpan(0, num)); System.Security.Cryptography.CryptoPool.Return(array, 0); } private static void WriteUncompressedPublicKey(in ECParameters ecParameters, AsnWriter writer) { int num = ecParameters.Q.X.Length * 2 + 1; byte[] array = System.Security.Cryptography.CryptoPool.Rent(num); array[0] = 4; ecParameters.Q.X.AsSpan().CopyTo(array.AsSpan(1)); ecParameters.Q.Y.AsSpan().CopyTo(array.AsSpan(1 + ecParameters.Q.X.Length)); writer.WriteBitString(array.AsSpan(0, num)); } private static AsnWriter WriteEcPrivateKey(in ECParameters ecParameters, bool includeDomainParameters) { AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.DER); asnWriter.PushSequence(); asnWriter.WriteInteger(1L); asnWriter.WriteOctetString(ecParameters.D); if (includeDomainParameters) { Asn1Tag value = new Asn1Tag(TagClass.ContextSpecific, 0, isConstructed: true); asnWriter.PushSequence(value); WriteEcParameters(ecParameters, asnWriter); asnWriter.PopSequence(value); } if (ecParameters.Q.X != null) { Asn1Tag value2 = new Asn1Tag(TagClass.ContextSpecific, 1, isConstructed: true); asnWriter.PushSequence(value2); WriteUncompressedPublicKey(in ecParameters, asnWriter); asnWriter.PopSequence(value2); } asnWriter.PopSequence(); return asnWriter; } } internal static class KeyBlobHelpers { internal static byte[] ToUnsignedIntegerBytes(this ReadOnlyMemory memory, int length) { if (memory.Length == length) { return memory.ToArray(); } ReadOnlySpan span = memory.Span; if (memory.Length == length + 1 && span[0] == 0) { return span.Slice(1).ToArray(); } if (span.Length > length) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } byte[] array = new byte[length]; span.CopyTo(array.AsSpan(length - span.Length)); return array; } internal static byte[] ToUnsignedIntegerBytes(this ReadOnlyMemory memory) { ReadOnlySpan span = memory.Span; if (span.Length > 1 && span[0] == 0) { return span.Slice(1).ToArray(); } return span.ToArray(); } } internal static class KeyFormatHelper { internal static AsnWriter WritePkcs8(AsnWriter algorithmIdentifierWriter, AsnWriter privateKeyWriter, AsnWriter attributesWriter = null) { int encodedLength = algorithmIdentifierWriter.GetEncodedLength(); int encodedLength2 = privateKeyWriter.GetEncodedLength(); AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.DER); asnWriter.PushSequence(); asnWriter.WriteInteger(0L); algorithmIdentifierWriter.CopyTo(asnWriter); using (asnWriter.PushOctetString()) { privateKeyWriter.CopyTo(asnWriter); } attributesWriter?.CopyTo(asnWriter); asnWriter.PopSequence(); return asnWriter; } internal static AsnWriter WriteEncryptedPkcs8(ReadOnlySpan password, AsnWriter pkcs8Writer, PbeParameters pbeParameters) { return WriteEncryptedPkcs8(password, ReadOnlySpan.Empty, pkcs8Writer, pbeParameters); } internal static AsnWriter WriteEncryptedPkcs8(ReadOnlySpan passwordBytes, AsnWriter pkcs8Writer, PbeParameters pbeParameters) { return WriteEncryptedPkcs8(ReadOnlySpan.Empty, passwordBytes, pkcs8Writer, pbeParameters); } private static AsnWriter WriteEncryptedPkcs8(ReadOnlySpan password, ReadOnlySpan passwordBytes, AsnWriter pkcs8Writer, PbeParameters pbeParameters) { System.Security.Cryptography.PasswordBasedEncryption.InitiateEncryption(pbeParameters, out var cipher, out var hmacOid, out var encryptionAlgorithmOid, out var isPkcs); Span span = default(Span); AsnWriter asnWriter = null; Span span2 = stackalloc byte[cipher.BlockSize / 8]; Span span3 = stackalloc byte[16]; checked { byte[] array = System.Security.Cryptography.CryptoPool.Rent(pkcs8Writer.GetEncodedLength() + unchecked(cipher.BlockSize / 8)); try { RandomNumberGenerator.Fill(span3); int length = System.Security.Cryptography.PasswordBasedEncryption.Encrypt(password, passwordBytes, cipher, isPkcs, pkcs8Writer, pbeParameters, span3, array, span2); span = array.AsSpan(0, length); asnWriter = new AsnWriter(AsnEncodingRules.DER); asnWriter.PushSequence(); System.Security.Cryptography.PasswordBasedEncryption.WritePbeAlgorithmIdentifier(asnWriter, isPkcs, encryptionAlgorithmOid, span3, pbeParameters.IterationCount, hmacOid, span2); asnWriter.WriteOctetString(span); asnWriter.PopSequence(); return asnWriter; } finally { CryptographicOperations.ZeroMemory(span); System.Security.Cryptography.CryptoPool.Return(array, 0); cipher.Dispose(); } } } internal static ArraySegment DecryptPkcs8(ReadOnlySpan inputPassword, ReadOnlyMemory source, out int bytesRead) { return DecryptPkcs8(inputPassword, ReadOnlySpan.Empty, source, out bytesRead); } internal static ArraySegment DecryptPkcs8(ReadOnlySpan inputPasswordBytes, ReadOnlyMemory source, out int bytesRead) { return DecryptPkcs8(ReadOnlySpan.Empty, inputPasswordBytes, source, out bytesRead); } private static ArraySegment DecryptPkcs8(ReadOnlySpan inputPassword, ReadOnlySpan inputPasswordBytes, ReadOnlyMemory source, out int bytesRead) { int length; System.Security.Cryptography.Asn1.EncryptedPrivateKeyInfoAsn decoded; try { System.Formats.Asn1.AsnValueReader reader = new System.Formats.Asn1.AsnValueReader(source.Span, AsnEncodingRules.BER); length = reader.PeekEncodedValue().Length; System.Security.Cryptography.Asn1.EncryptedPrivateKeyInfoAsn.Decode(ref reader, source, out decoded); } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } byte[] array = System.Security.Cryptography.CryptoPool.Rent(decoded.EncryptedData.Length); try { int count = System.Security.Cryptography.PasswordBasedEncryption.Decrypt(in decoded.EncryptionAlgorithm, inputPassword, inputPasswordBytes, decoded.EncryptedData.Span, array); bytesRead = length; return new ArraySegment(array, 0, count); } catch (CryptographicException inner2) { System.Security.Cryptography.CryptoPool.Return(array); throw new CryptographicException(System.SR.Cryptography_Pkcs8_EncryptedReadFailed, inner2); } } internal static AsnWriter ReencryptPkcs8(ReadOnlySpan inputPassword, ReadOnlyMemory current, ReadOnlySpan newPassword, PbeParameters pbeParameters) { int bytesRead; ArraySegment arraySegment = DecryptPkcs8(inputPassword, current, out bytesRead); try { if (bytesRead != current.Length) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.BER); asnWriter.WriteEncodedValueForCrypto(arraySegment); return WriteEncryptedPkcs8(newPassword, asnWriter, pbeParameters); } catch (CryptographicException inner) { throw new CryptographicException(System.SR.Cryptography_Pkcs8_EncryptedReadFailed, inner); } finally { System.Security.Cryptography.CryptoPool.Return(arraySegment); } } internal static AsnWriter ReencryptPkcs8(ReadOnlySpan inputPassword, ReadOnlyMemory current, ReadOnlySpan newPasswordBytes, PbeParameters pbeParameters) { int bytesRead; ArraySegment arraySegment = DecryptPkcs8(inputPassword, current, out bytesRead); try { if (bytesRead != current.Length) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } AsnWriter asnWriter = new AsnWriter(AsnEncodingRules.BER); asnWriter.WriteEncodedValueForCrypto(arraySegment); return WriteEncryptedPkcs8(newPasswordBytes, asnWriter, pbeParameters); } catch (CryptographicException inner) { throw new CryptographicException(System.SR.Cryptography_Pkcs8_EncryptedReadFailed, inner); } finally { System.Security.Cryptography.CryptoPool.Return(arraySegment); } } } internal static class KeySizeHelpers { public static bool IsLegalSize(this int size, KeySizes[] legalSizes) { bool validatedByZeroSkipSizeKeySizes; return size.IsLegalSize(legalSizes, out validatedByZeroSkipSizeKeySizes); } public static bool IsLegalSize(this int size, KeySizes legalSizes, out bool validatedByZeroSkipSizeKeySizes) { validatedByZeroSkipSizeKeySizes = false; if (legalSizes.SkipSize == 0) { if (legalSizes.MinSize == size) { validatedByZeroSkipSizeKeySizes = true; return true; } } else if (size >= legalSizes.MinSize && size <= legalSizes.MaxSize) { int num = size - legalSizes.MinSize; if (num % legalSizes.SkipSize == 0) { return true; } } return false; } public static bool IsLegalSize(this int size, KeySizes[] legalSizes, out bool validatedByZeroSkipSizeKeySizes) { for (int i = 0; i < legalSizes.Length; i++) { if (size.IsLegalSize(legalSizes[i], out validatedByZeroSkipSizeKeySizes)) { return true; } } validatedByZeroSkipSizeKeySizes = false; return false; } } internal static class Oids { private static volatile Oid _secp256r1Oid; private static volatile Oid _secp384r1Oid; private static volatile Oid _secp521r1Oid; internal static Oid secp256r1Oid => _secp256r1Oid ?? (_secp256r1Oid = new Oid("1.2.840.10045.3.1.7", "nistP256")); internal static Oid secp384r1Oid => _secp384r1Oid ?? (_secp384r1Oid = new Oid("1.3.132.0.34", "nistP384")); internal static Oid secp521r1Oid => _secp521r1Oid ?? (_secp521r1Oid = new Oid("1.3.132.0.35", "nistP521")); } internal static class PasswordBasedEncryption { private static CryptographicException AlgorithmKdfRequiresChars(string algId) { return new CryptographicException(System.SR.Cryptography_AlgKdfRequiresChars, algId); } internal static void ValidatePbeParameters(PbeParameters pbeParameters, ReadOnlySpan password, ReadOnlySpan passwordBytes) { PbeEncryptionAlgorithm encryptionAlgorithm = pbeParameters.EncryptionAlgorithm; switch (encryptionAlgorithm) { case PbeEncryptionAlgorithm.Aes128Cbc: case PbeEncryptionAlgorithm.Aes192Cbc: case PbeEncryptionAlgorithm.Aes256Cbc: break; case PbeEncryptionAlgorithm.TripleDes3KeyPkcs12: if (pbeParameters.HashAlgorithm != HashAlgorithmName.SHA1) { throw new CryptographicException(System.SR.Cryptography_UnknownHashAlgorithm, pbeParameters.HashAlgorithm.Name); } if (passwordBytes.Length > 0 && password.Length == 0) { throw AlgorithmKdfRequiresChars(encryptionAlgorithm.ToString()); } break; default: throw new CryptographicException(System.SR.Cryptography_UnknownAlgorithmIdentifier, encryptionAlgorithm.ToString()); } } internal unsafe static int Decrypt(in System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn algorithmIdentifier, ReadOnlySpan password, ReadOnlySpan passwordBytes, ReadOnlySpan encryptedData, Span destination) { SymmetricAlgorithm symmetricAlgorithm = null; bool flag = false; HashAlgorithmName hashAlgorithm; switch (algorithmIdentifier.Algorithm) { case "1.2.840.113549.1.5.3": hashAlgorithm = HashAlgorithmName.MD5; symmetricAlgorithm = DES.Create(); break; case "1.2.840.113549.1.5.6": hashAlgorithm = HashAlgorithmName.MD5; symmetricAlgorithm = CreateRC2(); break; case "1.2.840.113549.1.5.10": hashAlgorithm = HashAlgorithmName.SHA1; symmetricAlgorithm = DES.Create(); break; case "1.2.840.113549.1.5.11": hashAlgorithm = HashAlgorithmName.SHA1; symmetricAlgorithm = CreateRC2(); break; case "1.2.840.113549.1.12.1.3": hashAlgorithm = HashAlgorithmName.SHA1; symmetricAlgorithm = TripleDES.Create(); flag = true; break; case "1.2.840.113549.1.12.1.4": hashAlgorithm = HashAlgorithmName.SHA1; symmetricAlgorithm = TripleDES.Create(); symmetricAlgorithm.KeySize = 128; flag = true; break; case "1.2.840.113549.1.12.1.5": hashAlgorithm = HashAlgorithmName.SHA1; symmetricAlgorithm = CreateRC2(); symmetricAlgorithm.KeySize = 128; flag = true; break; case "1.2.840.113549.1.12.1.6": hashAlgorithm = HashAlgorithmName.SHA1; symmetricAlgorithm = CreateRC2(); symmetricAlgorithm.KeySize = 40; flag = true; break; case "1.2.840.113549.1.5.13": return Pbes2Decrypt(algorithmIdentifier.Parameters, password, passwordBytes, encryptedData, destination); default: throw new CryptographicException(System.SR.Format(System.SR.Cryptography_UnknownAlgorithmIdentifier, algorithmIdentifier.Algorithm)); } using (symmetricAlgorithm) { if (flag) { if (password.IsEmpty && passwordBytes.Length > 0) { throw AlgorithmKdfRequiresChars(algorithmIdentifier.Algorithm); } return Pkcs12PbeDecrypt(algorithmIdentifier, password, hashAlgorithm, symmetricAlgorithm, encryptedData, destination); } using IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithm); Span span = stackalloc byte[128]; ReadOnlySpan password2 = default(Span); byte[] array = null; Encoding encoding = null; if (passwordBytes.Length > 0 || password.Length == 0) { password2 = passwordBytes; } else { encoding = Encoding.UTF8; int byteCount = encoding.GetByteCount(password); if (byteCount > span.Length) { array = System.Security.Cryptography.CryptoPool.Rent(byteCount); span = array.AsSpan(0, byteCount); } else { span = span.Slice(0, byteCount); } } fixed (byte* ptr = &MemoryMarshal.GetReference(span)) { if (encoding != null) { span = span[..encoding.GetBytes(password, span)]; password2 = span; } try { return Pbes1Decrypt(algorithmIdentifier.Parameters, password2, hasher, symmetricAlgorithm, encryptedData, destination); } finally { CryptographicOperations.ZeroMemory(span); if (array != null) { System.Security.Cryptography.CryptoPool.Return(array, 0); } } } } } internal static void InitiateEncryption(PbeParameters pbeParameters, out SymmetricAlgorithm cipher, out string hmacOid, out string encryptionAlgorithmOid, out bool isPkcs12) { isPkcs12 = false; switch (pbeParameters.EncryptionAlgorithm) { case PbeEncryptionAlgorithm.Aes128Cbc: cipher = Aes.Create(); cipher.KeySize = 128; encryptionAlgorithmOid = "2.16.840.1.101.3.4.1.2"; break; case PbeEncryptionAlgorithm.Aes192Cbc: cipher = Aes.Create(); cipher.KeySize = 192; encryptionAlgorithmOid = "2.16.840.1.101.3.4.1.22"; break; case PbeEncryptionAlgorithm.Aes256Cbc: cipher = Aes.Create(); cipher.KeySize = 256; encryptionAlgorithmOid = "2.16.840.1.101.3.4.1.42"; break; case PbeEncryptionAlgorithm.TripleDes3KeyPkcs12: cipher = TripleDES.Create(); cipher.KeySize = 192; encryptionAlgorithmOid = "1.2.840.113549.1.12.1.3"; isPkcs12 = true; break; default: throw new CryptographicException(System.SR.Format(System.SR.Cryptography_UnknownAlgorithmIdentifier, pbeParameters.HashAlgorithm.Name)); } HashAlgorithmName hashAlgorithm = pbeParameters.HashAlgorithm; if (hashAlgorithm == HashAlgorithmName.SHA256) { hmacOid = "1.2.840.113549.2.9"; return; } if (hashAlgorithm == HashAlgorithmName.SHA384) { hmacOid = "1.2.840.113549.2.10"; return; } if (hashAlgorithm == HashAlgorithmName.SHA512) { hmacOid = "1.2.840.113549.2.11"; return; } if (hashAlgorithm == HashAlgorithmName.SHA1) { hmacOid = "1.2.840.113549.2.7"; return; } cipher.Dispose(); throw new CryptographicException(System.SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); } internal unsafe static int Encrypt(ReadOnlySpan password, ReadOnlySpan passwordBytes, SymmetricAlgorithm cipher, bool isPkcs12, AsnWriter source, PbeParameters pbeParameters, ReadOnlySpan salt, byte[] destination, Span ivDest) { byte[] array = null; byte[] iV = cipher.IV; int encodedLength = source.GetEncodedLength(); byte[] array2 = System.Security.Cryptography.CryptoPool.Rent(encodedLength); int num = cipher.KeySize / 8; int iterationCount = pbeParameters.IterationCount; HashAlgorithmName hashAlgorithm = pbeParameters.HashAlgorithm; Encoding uTF = Encoding.UTF8; if (!isPkcs12) { array = ((passwordBytes.Length == 0 && password.Length > 0) ? new byte[uTF.GetByteCount(password)] : ((passwordBytes.Length != 0) ? new byte[passwordBytes.Length] : Array.Empty())); } fixed (byte* ptr3 = array2) { fixed (byte* ptr2 = array) { byte[] array3; if (isPkcs12) { array3 = new byte[num]; System.Security.Cryptography.Pkcs.Pkcs12Kdf.DeriveCipherKey(password, hashAlgorithm, iterationCount, salt, array3); System.Security.Cryptography.Pkcs.Pkcs12Kdf.DeriveIV(password, hashAlgorithm, iterationCount, salt, iV); ivDest.Clear(); } else { if (passwordBytes.Length > 0) { passwordBytes.CopyTo(array); } else if (password.Length > 0) { int bytes = uTF.GetBytes(password, array); if (bytes != array.Length) { throw new CryptographicException(); } } using (Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(array, salt.ToArray(), iterationCount, hashAlgorithm)) { array3 = rfc2898DeriveBytes.GetBytes(num); } iV.CopyTo(ivDest); } fixed (byte* ptr = array3) { CryptographicOperations.ZeroMemory(array); using ICryptoTransform cryptoTransform = cipher.CreateEncryptor(array3, iV); int num2 = cipher.BlockSize / 8; int num3 = encodedLength % num2; int num4 = encodedLength - num3; try { if (!source.TryEncode(array2, out var _)) { throw new CryptographicException(); } int num5 = 0; if (num4 != 0) { num5 = cryptoTransform.TransformBlock(array2, 0, num4, destination, 0); } byte[] array4 = cryptoTransform.TransformFinalBlock(array2, num5, num3); array4.AsSpan().CopyTo(destination.AsSpan(num5)); return num5 + array4.Length; } finally { System.Security.Cryptography.CryptoPool.Return(array2, encodedLength); } } } } } private unsafe static int Pbes2Decrypt(ReadOnlyMemory? algorithmParameters, ReadOnlySpan password, ReadOnlySpan passwordBytes, ReadOnlySpan encryptedData, Span destination) { Span span = stackalloc byte[128]; ReadOnlySpan password2 = default(Span); byte[] array = null; Encoding encoding = null; if (passwordBytes.Length > 0 || password.Length == 0) { password2 = passwordBytes; } else { encoding = Encoding.UTF8; int byteCount = encoding.GetByteCount(password); if (byteCount > span.Length) { array = System.Security.Cryptography.CryptoPool.Rent(byteCount); span = array.AsSpan(0, byteCount); } else { span = span.Slice(0, byteCount); } } fixed (byte* ptr = &MemoryMarshal.GetReference(span)) { if (encoding != null) { span = span[..encoding.GetBytes(password, span)]; password2 = span; } try { return Pbes2Decrypt(algorithmParameters, password2, encryptedData, destination); } finally { if (array != null) { System.Security.Cryptography.CryptoPool.Return(array, span.Length); } } } } private unsafe static int Pbes2Decrypt(ReadOnlyMemory? algorithmParameters, ReadOnlySpan password, ReadOnlySpan encryptedData, Span destination) { if (!algorithmParameters.HasValue) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } System.Security.Cryptography.Asn1.PBES2Params pBES2Params = System.Security.Cryptography.Asn1.PBES2Params.Decode(algorithmParameters.Value, AsnEncodingRules.BER); if (pBES2Params.KeyDerivationFunc.Algorithm != "1.2.840.113549.1.5.12") { throw new CryptographicException(System.SR.Format(System.SR.Cryptography_UnknownAlgorithmIdentifier, pBES2Params.EncryptionScheme.Algorithm)); } int? requestedKeyLength; Rfc2898DeriveBytes rfc2898DeriveBytes = OpenPbkdf2(password, pBES2Params.KeyDerivationFunc.Parameters, out requestedKeyLength); using (rfc2898DeriveBytes) { Span iv = stackalloc byte[16]; SymmetricAlgorithm symmetricAlgorithm = OpenCipher(pBES2Params.EncryptionScheme, requestedKeyLength, ref iv); using (symmetricAlgorithm) { byte[] bytes = rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.KeySize / 8); fixed (byte* ptr = bytes) { try { return Decrypt(symmetricAlgorithm, bytes, iv, encryptedData, destination); } finally { CryptographicOperations.ZeroMemory(bytes); } } } } } private static SymmetricAlgorithm OpenCipher(System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn encryptionScheme, int? requestedKeyLength, ref Span iv) { string algorithm = encryptionScheme.Algorithm; switch (algorithm) { case "2.16.840.1.101.3.4.1.2": case "2.16.840.1.101.3.4.1.22": case "2.16.840.1.101.3.4.1.42": { int num = algorithm switch { "2.16.840.1.101.3.4.1.2" => 16, "2.16.840.1.101.3.4.1.22" => 24, "2.16.840.1.101.3.4.1.42" => 32, _ => throw new CryptographicException(), }; if (requestedKeyLength.HasValue && requestedKeyLength != num) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } ReadIvParameter(encryptionScheme.Parameters, 16, ref iv); Aes aes = Aes.Create(); aes.KeySize = num * 8; return aes; } case "1.2.840.113549.3.7": if (requestedKeyLength.HasValue && requestedKeyLength != 24) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } ReadIvParameter(encryptionScheme.Parameters, 8, ref iv); return TripleDES.Create(); case "1.2.840.113549.3.2": { if (!encryptionScheme.Parameters.HasValue) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } if (!requestedKeyLength.HasValue) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } System.Security.Cryptography.Asn1.Rc2CbcParameters rc2CbcParameters = System.Security.Cryptography.Asn1.Rc2CbcParameters.Decode(encryptionScheme.Parameters.Value, AsnEncodingRules.BER); if (rc2CbcParameters.Iv.Length != 8) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } RC2 rC = CreateRC2(); rC.KeySize = requestedKeyLength.Value * 8; rC.EffectiveKeySize = rc2CbcParameters.GetEffectiveKeyBits(); rc2CbcParameters.Iv.Span.CopyTo(iv); iv = iv.Slice(0, rc2CbcParameters.Iv.Length); return rC; } case "1.3.14.3.2.7": if (requestedKeyLength.HasValue && requestedKeyLength != 8) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } ReadIvParameter(encryptionScheme.Parameters, 8, ref iv); return DES.Create(); default: throw new CryptographicException(System.SR.Cryptography_UnknownAlgorithmIdentifier, algorithm); } } private static void ReadIvParameter(ReadOnlyMemory? encryptionSchemeParameters, int length, ref Span iv) { if (!encryptionSchemeParameters.HasValue) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } try { ReadOnlySpan span = encryptionSchemeParameters.Value.Span; if (!AsnDecoder.TryReadOctetString(span, iv, AsnEncodingRules.BER, out var bytesConsumed, out var bytesWritten) || bytesWritten != length || bytesConsumed != span.Length) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } iv = iv.Slice(0, bytesWritten); } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private unsafe static Rfc2898DeriveBytes OpenPbkdf2(ReadOnlySpan password, ReadOnlyMemory? parameters, out int? requestedKeyLength) { if (!parameters.HasValue) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } System.Security.Cryptography.Asn1.Pbkdf2Params pbkdf2Params = System.Security.Cryptography.Asn1.Pbkdf2Params.Decode(parameters.Value, AsnEncodingRules.BER); if (pbkdf2Params.Salt.OtherSource.HasValue) { throw new CryptographicException(System.SR.Format(System.SR.Cryptography_UnknownAlgorithmIdentifier, pbkdf2Params.Salt.OtherSource.Value.Algorithm)); } if (!pbkdf2Params.Salt.Specified.HasValue) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } HashAlgorithmName hashAlgorithm = pbkdf2Params.Prf.Algorithm switch { "1.2.840.113549.2.7" => HashAlgorithmName.SHA1, "1.2.840.113549.2.9" => HashAlgorithmName.SHA256, "1.2.840.113549.2.10" => HashAlgorithmName.SHA384, "1.2.840.113549.2.11" => HashAlgorithmName.SHA512, _ => throw new CryptographicException(System.SR.Format(System.SR.Cryptography_UnknownAlgorithmIdentifier, pbkdf2Params.Prf.Algorithm)), }; if (!pbkdf2Params.Prf.HasNullEquivalentParameters()) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } int iterations = NormalizeIterationCount(pbkdf2Params.IterationCount); ReadOnlyMemory value = pbkdf2Params.Salt.Specified.Value; byte[] array = new byte[password.Length]; byte[] array2 = new byte[value.Length]; fixed (byte* ptr2 = array) { fixed (byte* ptr = array2) { password.CopyTo(array); value.CopyTo(array2); try { requestedKeyLength = pbkdf2Params.KeyLength; return new Rfc2898DeriveBytes(array, array2, iterations, hashAlgorithm); } catch (ArgumentException inner) { throw new CryptographicException(System.SR.Argument_InvalidValue, inner); } finally { CryptographicOperations.ZeroMemory(array); CryptographicOperations.ZeroMemory(array2); } } } } private static int Pbes1Decrypt(ReadOnlyMemory? algorithmParameters, ReadOnlySpan password, IncrementalHash hasher, SymmetricAlgorithm cipher, ReadOnlySpan encryptedData, Span destination) { if (!algorithmParameters.HasValue) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } System.Security.Cryptography.Asn1.PBEParameter pBEParameter = System.Security.Cryptography.Asn1.PBEParameter.Decode(algorithmParameters.Value, AsnEncodingRules.BER); if (pBEParameter.Salt.Length != 8) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } if (pBEParameter.IterationCount < 1) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } int iterationCount = NormalizeIterationCount(pBEParameter.IterationCount); Span span = stackalloc byte[16]; try { Pbkdf1(hasher, password, pBEParameter.Salt.Span, iterationCount, span); Span span2 = span.Slice(0, 8); Span span3 = span.Slice(8, 8); return Decrypt(cipher, span2, span3, encryptedData, destination); } finally { CryptographicOperations.ZeroMemory(span); } } private static int Pkcs12PbeDecrypt(System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn algorithmIdentifier, ReadOnlySpan password, HashAlgorithmName hashAlgorithm, SymmetricAlgorithm cipher, ReadOnlySpan encryptedData, Span destination) { if (!algorithmIdentifier.Parameters.HasValue) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding); } if (cipher.KeySize > 256 || cipher.BlockSize > 256) { throw new CryptographicException(); } System.Security.Cryptography.Asn1.PBEParameter pBEParameter = System.Security.Cryptography.Asn1.PBEParameter.Decode(algorithmIdentifier.Parameters.Value, AsnEncodingRules.BER); int iterationCount = NormalizeIterationCount(pBEParameter.IterationCount, 600000); Span span = stackalloc byte[cipher.BlockSize / 8]; Span span2 = stackalloc byte[cipher.KeySize / 8]; ReadOnlySpan span3 = pBEParameter.Salt.Span; try { System.Security.Cryptography.Pkcs.Pkcs12Kdf.DeriveIV(password, hashAlgorithm, iterationCount, span3, span); System.Security.Cryptography.Pkcs.Pkcs12Kdf.DeriveCipherKey(password, hashAlgorithm, iterationCount, span3, span2); return Decrypt(cipher, span2, span, encryptedData, destination); } finally { CryptographicOperations.ZeroMemory(span2); CryptographicOperations.ZeroMemory(span); } } private unsafe static int Decrypt(SymmetricAlgorithm cipher, ReadOnlySpan key, ReadOnlySpan iv, ReadOnlySpan encryptedData, Span destination) { byte[] array = new byte[key.Length]; byte[] array2 = new byte[iv.Length]; byte[] array3 = System.Security.Cryptography.CryptoPool.Rent(encryptedData.Length); byte[] array4 = System.Security.Cryptography.CryptoPool.Rent(destination.Length); fixed (byte* ptr5 = array) { fixed (byte* ptr4 = array2) { fixed (byte* ptr3 = array3) { fixed (byte* ptr2 = array4) { try { key.CopyTo(array); iv.CopyTo(array2); using ICryptoTransform cryptoTransform = cipher.CreateDecryptor(array, array2); encryptedData.CopyTo(array3); int num = cryptoTransform.TransformBlock(array3, 0, encryptedData.Length, array4, 0); array4.AsSpan(0, num).CopyTo(destination); byte[] array5 = cryptoTransform.TransformFinalBlock(Array.Empty(), 0, 0); fixed (byte* ptr = array5) { Span buffer = array5.AsSpan(); buffer.CopyTo(destination.Slice(num)); CryptographicOperations.ZeroMemory(buffer); } return num + array5.Length; } finally { CryptographicOperations.ZeroMemory(array); CryptographicOperations.ZeroMemory(array2); System.Security.Cryptography.CryptoPool.Return(array3, encryptedData.Length); System.Security.Cryptography.CryptoPool.Return(array4, destination.Length); } } } } } } private static void Pbkdf1(IncrementalHash hasher, ReadOnlySpan password, ReadOnlySpan salt, int iterationCount, Span dk) { Span span = stackalloc byte[20]; hasher.AppendData(password); hasher.AppendData(salt); if (!hasher.TryGetHashAndReset(span, out var bytesWritten)) { throw new CryptographicException(); } span = span.Slice(0, bytesWritten); for (int i = 1; i < iterationCount; i++) { hasher.AppendData(span); if (!hasher.TryGetHashAndReset(span, out bytesWritten) || bytesWritten != span.Length) { throw new CryptographicException(); } } span.Slice(0, dk.Length).CopyTo(dk); CryptographicOperations.ZeroMemory(span); } internal static void WritePbeAlgorithmIdentifier(AsnWriter writer, bool isPkcs12, string encryptionAlgorithmOid, Span salt, int iterationCount, string hmacOid, Span iv) { writer.PushSequence(); if (isPkcs12) { writer.WriteObjectIdentifierForCrypto(encryptionAlgorithmOid); writer.PushSequence(); writer.WriteOctetString(salt); writer.WriteInteger((long)iterationCount, (Asn1Tag?)null); writer.PopSequence(); } else { writer.WriteObjectIdentifierForCrypto("1.2.840.113549.1.5.13"); writer.PushSequence(); writer.PushSequence(); writer.WriteObjectIdentifierForCrypto("1.2.840.113549.1.5.12"); writer.PushSequence(); writer.WriteOctetString(salt); writer.WriteInteger((long)iterationCount, (Asn1Tag?)null); if (hmacOid != "1.2.840.113549.2.7") { writer.PushSequence(); writer.WriteObjectIdentifierForCrypto(hmacOid); writer.WriteNull(); writer.PopSequence(); } writer.PopSequence(); writer.PopSequence(); writer.PushSequence(); writer.WriteObjectIdentifierForCrypto(encryptionAlgorithmOid); writer.WriteOctetString(iv); writer.PopSequence(); writer.PopSequence(); } writer.PopSequence(); } internal static int NormalizeIterationCount(int iterationCount, int? iterationLimit = null) { if (iterationCount <= 0 || (iterationLimit.HasValue && iterationCount > iterationLimit.Value)) { throw new CryptographicException(System.SR.Argument_InvalidValue); } return iterationCount; } private static RC2 CreateRC2() { if (!Internal.Cryptography.Helpers.IsRC2Supported) { throw new PlatformNotSupportedException(System.SR.Format(System.SR.Cryptography_AlgorithmNotSupported, "RC2")); } return RC2.Create(); } } internal sealed class RsaPaddingProcessor { private static readonly byte[] s_digestInfoMD5 = new byte[18] { 48, 32, 48, 12, 6, 8, 42, 134, 72, 134, 247, 13, 2, 5, 5, 0, 4, 16 }; private static readonly byte[] s_digestInfoSha1 = new byte[15] { 48, 33, 48, 9, 6, 5, 43, 14, 3, 2, 26, 5, 0, 4, 20 }; private static readonly byte[] s_digestInfoSha256 = new byte[19] { 48, 49, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 4, 32 }; private static readonly byte[] s_digestInfoSha384 = new byte[19] { 48, 65, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 4, 48 }; private static readonly byte[] s_digestInfoSha512 = new byte[19] { 48, 81, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 4, 64 }; private static readonly ConcurrentDictionary s_lookup = new ConcurrentDictionary(); private readonly HashAlgorithmName _hashAlgorithmName; private readonly int _hLen; private readonly ReadOnlyMemory _digestInfoPrefix; private RsaPaddingProcessor(HashAlgorithmName hashAlgorithmName, int hLen, ReadOnlyMemory digestInfoPrefix) { _hashAlgorithmName = hashAlgorithmName; _hLen = hLen; _digestInfoPrefix = digestInfoPrefix; } internal static int BytesRequiredForBitCount(int keySizeInBits) { return (int)((uint)(keySizeInBits + 7) / 8u); } internal static RsaPaddingProcessor OpenProcessor(HashAlgorithmName hashAlgorithmName) { return s_lookup.GetOrAdd(hashAlgorithmName, delegate(HashAlgorithmName hashAlgorithmName) { using IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithmName); Span destination = stackalloc byte[64]; ReadOnlyMemory digestInfoPrefix; if (hashAlgorithmName == HashAlgorithmName.MD5) { digestInfoPrefix = s_digestInfoMD5; } else if (hashAlgorithmName == HashAlgorithmName.SHA1) { digestInfoPrefix = s_digestInfoSha1; } else if (hashAlgorithmName == HashAlgorithmName.SHA256) { digestInfoPrefix = s_digestInfoSha256; } else if (hashAlgorithmName == HashAlgorithmName.SHA384) { digestInfoPrefix = s_digestInfoSha384; } else { if (!(hashAlgorithmName == HashAlgorithmName.SHA512)) { throw new CryptographicException(); } digestInfoPrefix = s_digestInfoSha512; } if (incrementalHash.TryGetHashAndReset(destination, out var bytesWritten)) { return new RsaPaddingProcessor(hashAlgorithmName, bytesWritten, digestInfoPrefix); } byte[] hashAndReset = incrementalHash.GetHashAndReset(); return new RsaPaddingProcessor(hashAlgorithmName, hashAndReset.Length, digestInfoPrefix); }); } internal static void PadPkcs1Encryption(ReadOnlySpan source, Span destination) { int length = source.Length; int length2 = destination.Length; if (length > length2 - 11) { throw new CryptographicException(System.SR.Cryptography_KeyTooSmall); } Span destination2 = destination.Slice(destination.Length - source.Length); Span data = destination.Slice(2, destination.Length - source.Length - 3); destination[0] = 0; destination[1] = 2; destination[data.Length + 2] = 0; FillNonZeroBytes(data); source.CopyTo(destination2); } internal void PadOaep(ReadOnlySpan source, Span destination) { byte[] array = null; Span span = Span.Empty; try { int num = checked(destination.Length - _hLen - _hLen - 2); if (source.Length > num) { throw new CryptographicException(System.SR.Format(System.SR.Cryptography_Encryption_MessageTooLong, num)); } Span span2 = destination.Slice(1, _hLen); Span span3 = destination.Slice(1 + _hLen); using IncrementalHash incrementalHash = IncrementalHash.CreateHash(_hashAlgorithmName); Span destination2 = span3.Slice(0, _hLen); Span destination3 = span3.Slice(span3.Length - source.Length); Span span4 = span3.Slice(_hLen, span3.Length - _hLen - 1 - destination3.Length); Span span5 = span3.Slice(_hLen + span4.Length, 1); if (!incrementalHash.TryGetHashAndReset(destination2, out var bytesWritten) || bytesWritten != _hLen) { throw new CryptographicException(); } span4.Clear(); span5[0] = 1; source.CopyTo(destination3); RandomNumberGenerator.Fill(span2); array = System.Security.Cryptography.CryptoPool.Rent(span3.Length); span = new Span(array, 0, span3.Length); Mgf1(incrementalHash, span2, span); Xor(span3, span); Span span6 = stackalloc byte[_hLen]; Mgf1(incrementalHash, span3, span6); Xor(span2, span6); destination[0] = 0; } catch (Exception ex) when (!(ex is CryptographicException)) { throw new CryptographicException(); } finally { if (array != null) { CryptographicOperations.ZeroMemory(span); System.Security.Cryptography.CryptoPool.Return(array, 0); } } } private void Mgf1(IncrementalHash hasher, ReadOnlySpan mgfSeed, Span mask) { Span destination = mask; int num = 0; Span span = stackalloc byte[4]; while (destination.Length > 0) { hasher.AppendData(mgfSeed); BinaryPrimitives.WriteInt32BigEndian(span, num); hasher.AppendData(span); if (destination.Length >= _hLen) { if (!hasher.TryGetHashAndReset(destination, out var bytesWritten)) { throw new CryptographicException(); } destination = destination.Slice(bytesWritten); num++; continue; } Span destination2 = stackalloc byte[_hLen]; if (!hasher.TryGetHashAndReset(destination2, out var _)) { throw new CryptographicException(); } destination2.Slice(0, destination.Length).CopyTo(destination); break; } } private static void FillNonZeroBytes(Span data) { while (data.Length > 0) { RandomNumberGenerator.Fill(data); int num = data.Length; for (int i = 0; i < data.Length; i++) { if (data[i] == 0) { num = i; break; } } for (int j = num + 1; j < data.Length; j++) { if (data[j] != 0) { data[num++] = data[j]; } } data = data.Slice(num); } } private static void Xor(Span a, ReadOnlySpan b) { if (a.Length != b.Length) { throw new InvalidOperationException(); } for (int i = 0; i < b.Length; i++) { a[i] ^= b[i]; } } } } namespace System.Security.Cryptography.Asn1 { internal struct AlgorithmIdentifierAsn { internal string Algorithm; internal ReadOnlyMemory? Parameters; internal static readonly ReadOnlyMemory ExplicitDerNull = new byte[2] { 5, 0 }; internal static void Decode(ref System.Formats.Asn1.AsnValueReader reader, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn decoded) { Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded); } internal static void Decode(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn decoded) { try { DecodeCore(ref reader, expectedTag, rebind, out decoded); } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static void DecodeCore(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn decoded) { decoded = default(System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn); System.Formats.Asn1.AsnValueReader asnValueReader = reader.ReadSequence(expectedTag); ReadOnlySpan span = rebind.Span; decoded.Algorithm = asnValueReader.ReadObjectIdentifier(); if (asnValueReader.HasData) { ReadOnlySpan other = asnValueReader.ReadEncodedValue(); decoded.Parameters = (span.Overlaps(other, out var elementOffset) ? rebind.Slice(elementOffset, other.Length) : ((ReadOnlyMemory)other.ToArray())); } asnValueReader.ThrowIfNotEmpty(); } internal readonly bool HasNullEquivalentParameters() { return RepresentsNull(Parameters); } internal static bool RepresentsNull(ReadOnlyMemory? parameters) { if (!parameters.HasValue) { return true; } ReadOnlySpan span = parameters.Value.Span; if (span.Length != 2) { return false; } if (span[0] != 5) { return false; } return span[1] == 0; } } internal struct AttributeAsn { internal string AttrType; internal ReadOnlyMemory[] AttrValues; internal void Encode(AsnWriter writer) { Encode(writer, Asn1Tag.Sequence); } internal void Encode(AsnWriter writer, Asn1Tag tag) { writer.PushSequence(tag); try { writer.WriteObjectIdentifier(AttrType); } catch (ArgumentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } writer.PushSetOf(); for (int i = 0; i < AttrValues.Length; i++) { try { writer.WriteEncodedValue(AttrValues[i].Span); } catch (ArgumentException inner2) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner2); } } writer.PopSetOf(); writer.PopSequence(tag); } internal static void Decode(ref System.Formats.Asn1.AsnValueReader reader, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.AttributeAsn decoded) { Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded); } internal static void Decode(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.AttributeAsn decoded) { try { DecodeCore(ref reader, expectedTag, rebind, out decoded); } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static void DecodeCore(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.AttributeAsn decoded) { decoded = default(System.Security.Cryptography.Asn1.AttributeAsn); System.Formats.Asn1.AsnValueReader asnValueReader = reader.ReadSequence(expectedTag); ReadOnlySpan span = rebind.Span; decoded.AttrType = asnValueReader.ReadObjectIdentifier(); System.Formats.Asn1.AsnValueReader asnValueReader2 = asnValueReader.ReadSetOf(); List> list = new List>(); while (asnValueReader2.HasData) { ReadOnlySpan other = asnValueReader2.ReadEncodedValue(); int elementOffset; ReadOnlyMemory item = (span.Overlaps(other, out elementOffset) ? rebind.Slice(elementOffset, other.Length) : ((ReadOnlyMemory)other.ToArray())); list.Add(item); } decoded.AttrValues = list.ToArray(); asnValueReader.ThrowIfNotEmpty(); } } internal struct PBEParameter { internal ReadOnlyMemory Salt; internal int IterationCount; internal static System.Security.Cryptography.Asn1.PBEParameter Decode(ReadOnlyMemory encoded, AsnEncodingRules ruleSet) { return Decode(Asn1Tag.Sequence, encoded, ruleSet); } internal static System.Security.Cryptography.Asn1.PBEParameter Decode(Asn1Tag expectedTag, ReadOnlyMemory encoded, AsnEncodingRules ruleSet) { try { System.Formats.Asn1.AsnValueReader reader = new System.Formats.Asn1.AsnValueReader(encoded.Span, ruleSet); DecodeCore(ref reader, expectedTag, encoded, out var decoded); reader.ThrowIfNotEmpty(); return decoded; } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static void DecodeCore(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.PBEParameter decoded) { decoded = default(System.Security.Cryptography.Asn1.PBEParameter); System.Formats.Asn1.AsnValueReader asnValueReader = reader.ReadSequence(expectedTag); ReadOnlySpan span = rebind.Span; if (asnValueReader.TryReadPrimitiveOctetString(out var value)) { decoded.Salt = (span.Overlaps(value, out var elementOffset) ? rebind.Slice(elementOffset, value.Length) : ((ReadOnlyMemory)value.ToArray())); } else { decoded.Salt = asnValueReader.ReadOctetString(); } if (!asnValueReader.TryReadInt32(out decoded.IterationCount)) { asnValueReader.ThrowIfNotEmpty(); } asnValueReader.ThrowIfNotEmpty(); } } internal struct PBES2Params { internal System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn KeyDerivationFunc; internal System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn EncryptionScheme; internal static System.Security.Cryptography.Asn1.PBES2Params Decode(ReadOnlyMemory encoded, AsnEncodingRules ruleSet) { return Decode(Asn1Tag.Sequence, encoded, ruleSet); } internal static System.Security.Cryptography.Asn1.PBES2Params Decode(Asn1Tag expectedTag, ReadOnlyMemory encoded, AsnEncodingRules ruleSet) { try { System.Formats.Asn1.AsnValueReader reader = new System.Formats.Asn1.AsnValueReader(encoded.Span, ruleSet); DecodeCore(ref reader, expectedTag, encoded, out var decoded); reader.ThrowIfNotEmpty(); return decoded; } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static void DecodeCore(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.PBES2Params decoded) { decoded = default(System.Security.Cryptography.Asn1.PBES2Params); System.Formats.Asn1.AsnValueReader reader2 = reader.ReadSequence(expectedTag); System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn.Decode(ref reader2, rebind, out decoded.KeyDerivationFunc); System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn.Decode(ref reader2, rebind, out decoded.EncryptionScheme); reader2.ThrowIfNotEmpty(); } } internal struct Pbkdf2Params { internal System.Security.Cryptography.Asn1.Pbkdf2SaltChoice Salt; internal int IterationCount; internal int? KeyLength; internal System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn Prf; private static ReadOnlySpan DefaultPrf => new byte[14] { 48, 12, 6, 8, 42, 134, 72, 134, 247, 13, 2, 7, 5, 0 }; internal static System.Security.Cryptography.Asn1.Pbkdf2Params Decode(ReadOnlyMemory encoded, AsnEncodingRules ruleSet) { return Decode(Asn1Tag.Sequence, encoded, ruleSet); } internal static System.Security.Cryptography.Asn1.Pbkdf2Params Decode(Asn1Tag expectedTag, ReadOnlyMemory encoded, AsnEncodingRules ruleSet) { try { System.Formats.Asn1.AsnValueReader reader = new System.Formats.Asn1.AsnValueReader(encoded.Span, ruleSet); DecodeCore(ref reader, expectedTag, encoded, out var decoded); reader.ThrowIfNotEmpty(); return decoded; } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static void DecodeCore(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.Pbkdf2Params decoded) { decoded = default(System.Security.Cryptography.Asn1.Pbkdf2Params); System.Formats.Asn1.AsnValueReader reader2 = reader.ReadSequence(expectedTag); System.Security.Cryptography.Asn1.Pbkdf2SaltChoice.Decode(ref reader2, rebind, out decoded.Salt); if (!reader2.TryReadInt32(out decoded.IterationCount)) { reader2.ThrowIfNotEmpty(); } if (reader2.HasData && reader2.PeekTag().HasSameClassAndValue(Asn1Tag.Integer)) { if (reader2.TryReadInt32(out var value)) { decoded.KeyLength = value; } else { reader2.ThrowIfNotEmpty(); } } if (reader2.HasData && reader2.PeekTag().HasSameClassAndValue(Asn1Tag.Sequence)) { System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn.Decode(ref reader2, rebind, out decoded.Prf); } else { System.Formats.Asn1.AsnValueReader reader3 = new System.Formats.Asn1.AsnValueReader(DefaultPrf, AsnEncodingRules.DER); System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn.Decode(ref reader3, rebind, out decoded.Prf); } reader2.ThrowIfNotEmpty(); } } internal struct Pbkdf2SaltChoice { internal ReadOnlyMemory? Specified; internal System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn? OtherSource; internal static void Decode(ref System.Formats.Asn1.AsnValueReader reader, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.Pbkdf2SaltChoice decoded) { try { DecodeCore(ref reader, rebind, out decoded); } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static void DecodeCore(ref System.Formats.Asn1.AsnValueReader reader, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.Pbkdf2SaltChoice decoded) { decoded = default(System.Security.Cryptography.Asn1.Pbkdf2SaltChoice); Asn1Tag asn1Tag = reader.PeekTag(); ReadOnlySpan span = rebind.Span; if (asn1Tag.HasSameClassAndValue(Asn1Tag.PrimitiveOctetString)) { if (reader.TryReadPrimitiveOctetString(out var value)) { decoded.Specified = (span.Overlaps(value, out var elementOffset) ? rebind.Slice(elementOffset, value.Length) : ((ReadOnlyMemory)value.ToArray())); } else { decoded.Specified = reader.ReadOctetString(); } return; } if (asn1Tag.HasSameClassAndValue(Asn1Tag.Sequence)) { System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn.Decode(ref reader, rebind, out var decoded2); decoded.OtherSource = decoded2; return; } throw new CryptographicException(); } } internal struct EncryptedPrivateKeyInfoAsn { internal System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn EncryptionAlgorithm; internal ReadOnlyMemory EncryptedData; internal static void Decode(ref System.Formats.Asn1.AsnValueReader reader, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.EncryptedPrivateKeyInfoAsn decoded) { Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded); } internal static void Decode(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.EncryptedPrivateKeyInfoAsn decoded) { try { DecodeCore(ref reader, expectedTag, rebind, out decoded); } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static void DecodeCore(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.EncryptedPrivateKeyInfoAsn decoded) { decoded = default(System.Security.Cryptography.Asn1.EncryptedPrivateKeyInfoAsn); System.Formats.Asn1.AsnValueReader reader2 = reader.ReadSequence(expectedTag); ReadOnlySpan span = rebind.Span; System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn.Decode(ref reader2, rebind, out decoded.EncryptionAlgorithm); if (reader2.TryReadPrimitiveOctetString(out var value)) { decoded.EncryptedData = (span.Overlaps(value, out var elementOffset) ? rebind.Slice(elementOffset, value.Length) : ((ReadOnlyMemory)value.ToArray())); } else { decoded.EncryptedData = reader2.ReadOctetString(); } reader2.ThrowIfNotEmpty(); } } internal struct PrivateKeyInfoAsn { internal int Version; internal System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn PrivateKeyAlgorithm; internal ReadOnlyMemory PrivateKey; internal System.Security.Cryptography.Asn1.AttributeAsn[] Attributes; internal static System.Security.Cryptography.Asn1.PrivateKeyInfoAsn Decode(ReadOnlyMemory encoded, AsnEncodingRules ruleSet) { return Decode(Asn1Tag.Sequence, encoded, ruleSet); } internal static System.Security.Cryptography.Asn1.PrivateKeyInfoAsn Decode(Asn1Tag expectedTag, ReadOnlyMemory encoded, AsnEncodingRules ruleSet) { try { System.Formats.Asn1.AsnValueReader reader = new System.Formats.Asn1.AsnValueReader(encoded.Span, ruleSet); DecodeCore(ref reader, expectedTag, encoded, out var decoded); reader.ThrowIfNotEmpty(); return decoded; } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static void DecodeCore(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.PrivateKeyInfoAsn decoded) { decoded = default(System.Security.Cryptography.Asn1.PrivateKeyInfoAsn); System.Formats.Asn1.AsnValueReader reader2 = reader.ReadSequence(expectedTag); ReadOnlySpan span = rebind.Span; if (!reader2.TryReadInt32(out decoded.Version)) { reader2.ThrowIfNotEmpty(); } System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn.Decode(ref reader2, rebind, out decoded.PrivateKeyAlgorithm); if (reader2.TryReadPrimitiveOctetString(out var value)) { decoded.PrivateKey = (span.Overlaps(value, out var elementOffset) ? rebind.Slice(elementOffset, value.Length) : ((ReadOnlyMemory)value.ToArray())); } else { decoded.PrivateKey = reader2.ReadOctetString(); } if (reader2.HasData && reader2.PeekTag().HasSameClassAndValue(new Asn1Tag(TagClass.ContextSpecific, 0))) { System.Formats.Asn1.AsnValueReader reader3 = reader2.ReadSetOf(new Asn1Tag(TagClass.ContextSpecific, 0)); List list = new List(); while (reader3.HasData) { System.Security.Cryptography.Asn1.AttributeAsn.Decode(ref reader3, rebind, out var decoded2); list.Add(decoded2); } decoded.Attributes = list.ToArray(); } reader2.ThrowIfNotEmpty(); } } internal struct Rc2CbcParameters { internal int Rc2Version; internal ReadOnlyMemory Iv; private static readonly byte[] s_rc2EkbEncoding = new byte[256] { 189, 86, 234, 242, 162, 241, 172, 42, 176, 147, 209, 156, 27, 51, 253, 208, 48, 4, 182, 220, 125, 223, 50, 75, 247, 203, 69, 155, 49, 187, 33, 90, 65, 159, 225, 217, 74, 77, 158, 218, 160, 104, 44, 195, 39, 95, 128, 54, 62, 238, 251, 149, 26, 254, 206, 168, 52, 169, 19, 240, 166, 63, 216, 12, 120, 36, 175, 35, 82, 193, 103, 23, 245, 102, 144, 231, 232, 7, 184, 96, 72, 230, 30, 83, 243, 146, 164, 114, 140, 8, 21, 110, 134, 0, 132, 250, 244, 127, 138, 66, 25, 246, 219, 205, 20, 141, 80, 18, 186, 60, 6, 78, 236, 179, 53, 17, 161, 136, 142, 43, 148, 153, 183, 113, 116, 211, 228, 191, 58, 222, 150, 14, 188, 10, 237, 119, 252, 55, 107, 3, 121, 137, 98, 198, 215, 192, 210, 124, 106, 139, 34, 163, 91, 5, 93, 2, 117, 213, 97, 227, 24, 143, 85, 81, 173, 31, 11, 94, 133, 229, 194, 87, 99, 202, 61, 108, 180, 197, 204, 112, 178, 145, 89, 13, 71, 32, 200, 79, 88, 224, 1, 226, 22, 56, 196, 111, 59, 15, 101, 70, 190, 126, 45, 123, 130, 249, 64, 181, 29, 115, 248, 235, 38, 199, 135, 151, 37, 84, 177, 40, 170, 152, 157, 165, 100, 109, 122, 212, 16, 129, 68, 239, 73, 214, 174, 46, 221, 118, 92, 47, 167, 28, 201, 9, 105, 154, 131, 207, 41, 57, 185, 233, 76, 255, 67, 171 }; internal static System.Security.Cryptography.Asn1.Rc2CbcParameters Decode(ReadOnlyMemory encoded, AsnEncodingRules ruleSet) { return Decode(Asn1Tag.Sequence, encoded, ruleSet); } internal static System.Security.Cryptography.Asn1.Rc2CbcParameters Decode(Asn1Tag expectedTag, ReadOnlyMemory encoded, AsnEncodingRules ruleSet) { try { System.Formats.Asn1.AsnValueReader reader = new System.Formats.Asn1.AsnValueReader(encoded.Span, ruleSet); DecodeCore(ref reader, expectedTag, encoded, out var decoded); reader.ThrowIfNotEmpty(); return decoded; } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static void DecodeCore(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.Rc2CbcParameters decoded) { decoded = default(System.Security.Cryptography.Asn1.Rc2CbcParameters); System.Formats.Asn1.AsnValueReader asnValueReader = reader.ReadSequence(expectedTag); ReadOnlySpan span = rebind.Span; if (!asnValueReader.TryReadInt32(out decoded.Rc2Version)) { asnValueReader.ThrowIfNotEmpty(); } if (asnValueReader.TryReadPrimitiveOctetString(out var value)) { decoded.Iv = (span.Overlaps(value, out var elementOffset) ? rebind.Slice(elementOffset, value.Length) : ((ReadOnlyMemory)value.ToArray())); } else { decoded.Iv = asnValueReader.ReadOctetString(); } asnValueReader.ThrowIfNotEmpty(); } internal int GetEffectiveKeyBits() { if (Rc2Version > 255) { return Rc2Version; } return Array.IndexOf(s_rc2EkbEncoding, (byte)Rc2Version); } } internal struct ECDomainParameters { internal System.Security.Cryptography.Asn1.SpecifiedECDomain? Specified; internal string Named; internal void Encode(AsnWriter writer) { bool flag = false; if (Specified.HasValue) { if (flag) { throw new CryptographicException(); } Specified.Value.Encode(writer); flag = true; } if (Named != null) { if (flag) { throw new CryptographicException(); } try { writer.WriteObjectIdentifier(Named); } catch (ArgumentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } flag = true; } if (!flag) { throw new CryptographicException(); } } internal static System.Security.Cryptography.Asn1.ECDomainParameters Decode(ReadOnlyMemory encoded, AsnEncodingRules ruleSet) { try { System.Formats.Asn1.AsnValueReader reader = new System.Formats.Asn1.AsnValueReader(encoded.Span, ruleSet); DecodeCore(ref reader, encoded, out var decoded); reader.ThrowIfNotEmpty(); return decoded; } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } internal static void Decode(ref System.Formats.Asn1.AsnValueReader reader, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.ECDomainParameters decoded) { try { DecodeCore(ref reader, rebind, out decoded); } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static void DecodeCore(ref System.Formats.Asn1.AsnValueReader reader, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.ECDomainParameters decoded) { decoded = default(System.Security.Cryptography.Asn1.ECDomainParameters); Asn1Tag asn1Tag = reader.PeekTag(); if (asn1Tag.HasSameClassAndValue(Asn1Tag.Sequence)) { System.Security.Cryptography.Asn1.SpecifiedECDomain.Decode(ref reader, rebind, out var decoded2); decoded.Specified = decoded2; return; } if (asn1Tag.HasSameClassAndValue(Asn1Tag.ObjectIdentifier)) { decoded.Named = reader.ReadObjectIdentifier(); return; } throw new CryptographicException(); } } internal struct SpecifiedECDomain { internal int Version; internal System.Security.Cryptography.Asn1.FieldID FieldID; internal System.Security.Cryptography.Asn1.CurveAsn Curve; internal ReadOnlyMemory Base; internal ReadOnlyMemory Order; internal ReadOnlyMemory? Cofactor; internal string Hash; internal void Encode(AsnWriter writer) { Encode(writer, Asn1Tag.Sequence); } internal void Encode(AsnWriter writer, Asn1Tag tag) { writer.PushSequence(tag); writer.WriteInteger((long)Version, (Asn1Tag?)null); FieldID.Encode(writer); Curve.Encode(writer); writer.WriteOctetString(Base.Span); writer.WriteInteger(Order.Span); if (Cofactor.HasValue) { writer.WriteInteger(Cofactor.Value.Span); } if (Hash != null) { try { writer.WriteObjectIdentifier(Hash); } catch (ArgumentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } writer.PopSequence(tag); } internal static void Decode(ref System.Formats.Asn1.AsnValueReader reader, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.SpecifiedECDomain decoded) { Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded); } internal static void Decode(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.SpecifiedECDomain decoded) { try { DecodeCore(ref reader, expectedTag, rebind, out decoded); } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static void DecodeCore(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.SpecifiedECDomain decoded) { decoded = default(System.Security.Cryptography.Asn1.SpecifiedECDomain); System.Formats.Asn1.AsnValueReader reader2 = reader.ReadSequence(expectedTag); ReadOnlySpan span = rebind.Span; if (!reader2.TryReadInt32(out decoded.Version)) { reader2.ThrowIfNotEmpty(); } System.Security.Cryptography.Asn1.FieldID.Decode(ref reader2, rebind, out decoded.FieldID); System.Security.Cryptography.Asn1.CurveAsn.Decode(ref reader2, rebind, out decoded.Curve); int elementOffset; if (reader2.TryReadPrimitiveOctetString(out var value)) { decoded.Base = (span.Overlaps(value, out elementOffset) ? rebind.Slice(elementOffset, value.Length) : ((ReadOnlyMemory)value.ToArray())); } else { decoded.Base = reader2.ReadOctetString(); } value = reader2.ReadIntegerBytes(); decoded.Order = (span.Overlaps(value, out elementOffset) ? rebind.Slice(elementOffset, value.Length) : ((ReadOnlyMemory)value.ToArray())); if (reader2.HasData && reader2.PeekTag().HasSameClassAndValue(Asn1Tag.Integer)) { value = reader2.ReadIntegerBytes(); decoded.Cofactor = (span.Overlaps(value, out elementOffset) ? rebind.Slice(elementOffset, value.Length) : ((ReadOnlyMemory)value.ToArray())); } if (reader2.HasData && reader2.PeekTag().HasSameClassAndValue(Asn1Tag.ObjectIdentifier)) { decoded.Hash = reader2.ReadObjectIdentifier(); } reader2.ThrowIfNotEmpty(); } } internal struct CurveAsn { internal ReadOnlyMemory A; internal ReadOnlyMemory B; internal ReadOnlyMemory? Seed; internal void Encode(AsnWriter writer) { Encode(writer, Asn1Tag.Sequence); } internal void Encode(AsnWriter writer, Asn1Tag tag) { writer.PushSequence(tag); writer.WriteOctetString(A.Span); writer.WriteOctetString(B.Span); if (Seed.HasValue) { writer.WriteBitString(Seed.Value.Span); } writer.PopSequence(tag); } internal static void Decode(ref System.Formats.Asn1.AsnValueReader reader, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.CurveAsn decoded) { Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded); } internal static void Decode(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.CurveAsn decoded) { try { DecodeCore(ref reader, expectedTag, rebind, out decoded); } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static void DecodeCore(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.CurveAsn decoded) { decoded = default(System.Security.Cryptography.Asn1.CurveAsn); System.Formats.Asn1.AsnValueReader asnValueReader = reader.ReadSequence(expectedTag); ReadOnlySpan span = rebind.Span; int elementOffset; if (asnValueReader.TryReadPrimitiveOctetString(out var value)) { decoded.A = (span.Overlaps(value, out elementOffset) ? rebind.Slice(elementOffset, value.Length) : ((ReadOnlyMemory)value.ToArray())); } else { decoded.A = asnValueReader.ReadOctetString(); } if (asnValueReader.TryReadPrimitiveOctetString(out value)) { decoded.B = (span.Overlaps(value, out elementOffset) ? rebind.Slice(elementOffset, value.Length) : ((ReadOnlyMemory)value.ToArray())); } else { decoded.B = asnValueReader.ReadOctetString(); } if (asnValueReader.HasData && asnValueReader.PeekTag().HasSameClassAndValue(Asn1Tag.PrimitiveBitString)) { if (asnValueReader.TryReadPrimitiveBitString(out var unusedBitCount, out value)) { decoded.Seed = (span.Overlaps(value, out elementOffset) ? rebind.Slice(elementOffset, value.Length) : ((ReadOnlyMemory)value.ToArray())); } else { decoded.Seed = asnValueReader.ReadBitString(out unusedBitCount); } } asnValueReader.ThrowIfNotEmpty(); } } internal struct FieldID { internal string FieldType; internal ReadOnlyMemory Parameters; internal void Encode(AsnWriter writer) { Encode(writer, Asn1Tag.Sequence); } internal void Encode(AsnWriter writer, Asn1Tag tag) { writer.PushSequence(tag); try { writer.WriteObjectIdentifier(FieldType); } catch (ArgumentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } try { writer.WriteEncodedValue(Parameters.Span); } catch (ArgumentException inner2) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner2); } writer.PopSequence(tag); } internal static void Decode(ref System.Formats.Asn1.AsnValueReader reader, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.FieldID decoded) { Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded); } internal static void Decode(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.FieldID decoded) { try { DecodeCore(ref reader, expectedTag, rebind, out decoded); } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static void DecodeCore(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.FieldID decoded) { decoded = default(System.Security.Cryptography.Asn1.FieldID); System.Formats.Asn1.AsnValueReader asnValueReader = reader.ReadSequence(expectedTag); ReadOnlySpan span = rebind.Span; decoded.FieldType = asnValueReader.ReadObjectIdentifier(); ReadOnlySpan other = asnValueReader.ReadEncodedValue(); decoded.Parameters = (span.Overlaps(other, out var elementOffset) ? rebind.Slice(elementOffset, other.Length) : ((ReadOnlyMemory)other.ToArray())); asnValueReader.ThrowIfNotEmpty(); } } internal struct ECPrivateKey { internal int Version; internal ReadOnlyMemory PrivateKey; internal System.Security.Cryptography.Asn1.ECDomainParameters? Parameters; internal ReadOnlyMemory? PublicKey; internal static System.Security.Cryptography.Asn1.ECPrivateKey Decode(ReadOnlyMemory encoded, AsnEncodingRules ruleSet) { return Decode(Asn1Tag.Sequence, encoded, ruleSet); } internal static System.Security.Cryptography.Asn1.ECPrivateKey Decode(Asn1Tag expectedTag, ReadOnlyMemory encoded, AsnEncodingRules ruleSet) { try { System.Formats.Asn1.AsnValueReader reader = new System.Formats.Asn1.AsnValueReader(encoded.Span, ruleSet); DecodeCore(ref reader, expectedTag, encoded, out var decoded); reader.ThrowIfNotEmpty(); return decoded; } catch (AsnContentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } private static void DecodeCore(ref System.Formats.Asn1.AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out System.Security.Cryptography.Asn1.ECPrivateKey decoded) { decoded = default(System.Security.Cryptography.Asn1.ECPrivateKey); System.Formats.Asn1.AsnValueReader asnValueReader = reader.ReadSequence(expectedTag); ReadOnlySpan span = rebind.Span; if (!asnValueReader.TryReadInt32(out decoded.Version)) { asnValueReader.ThrowIfNotEmpty(); } int elementOffset; if (asnValueReader.TryReadPrimitiveOctetString(out var value)) { decoded.PrivateKey = (span.Overlaps(value, out elementOffset) ? rebind.Slice(elementOffset, value.Length) : ((ReadOnlyMemory)value.ToArray())); } else { decoded.PrivateKey = asnValueReader.ReadOctetString(); } System.Formats.Asn1.AsnValueReader reader2; if (asnValueReader.HasData && asnValueReader.PeekTag().HasSameClassAndValue(new Asn1Tag(TagClass.ContextSpecific, 0))) { reader2 = asnValueReader.ReadSequence(new Asn1Tag(TagClass.ContextSpecific, 0)); System.Security.Cryptography.Asn1.ECDomainParameters.Decode(ref reader2, rebind, out var decoded2); decoded.Parameters = decoded2; reader2.ThrowIfNotEmpty(); } if (asnValueReader.HasData && asnValueReader.PeekTag().HasSameClassAndValue(new Asn1Tag(TagClass.ContextSpecific, 1))) { reader2 = asnValueReader.ReadSequence(new Asn1Tag(TagClass.ContextSpecific, 1)); if (reader2.TryReadPrimitiveBitString(out var unusedBitCount, out value)) { decoded.PublicKey = (span.Overlaps(value, out elementOffset) ? rebind.Slice(elementOffset, value.Length) : ((ReadOnlyMemory)value.ToArray())); } else { decoded.PublicKey = reader2.ReadBitString(out unusedBitCount); } reader2.ThrowIfNotEmpty(); } asnValueReader.ThrowIfNotEmpty(); } } } namespace System.Security.Cryptography.Pkcs { internal static class Pkcs12Kdf { private static readonly (HashAlgorithmName, int, int)[] s_uvLookup = new(HashAlgorithmName, int, int)[5] { (HashAlgorithmName.MD5, 128, 512), (HashAlgorithmName.SHA1, 160, 512), (HashAlgorithmName.SHA256, 256, 512), (HashAlgorithmName.SHA384, 384, 1024), (HashAlgorithmName.SHA512, 512, 1024) }; internal static void DeriveCipherKey(ReadOnlySpan password, HashAlgorithmName hashAlgorithm, int iterationCount, ReadOnlySpan salt, Span destination) { Derive(password, hashAlgorithm, iterationCount, 1, salt, destination); } internal static void DeriveIV(ReadOnlySpan password, HashAlgorithmName hashAlgorithm, int iterationCount, ReadOnlySpan salt, Span destination) { Derive(password, hashAlgorithm, iterationCount, 2, salt, destination); } private static void Derive(ReadOnlySpan password, HashAlgorithmName hashAlgorithm, int iterationCount, byte id, ReadOnlySpan salt, Span destination) { int num = -1; int num2 = -1; (HashAlgorithmName, int, int)[] array = s_uvLookup; for (int i = 0; i < array.Length; i++) { (HashAlgorithmName, int, int) tuple = array[i]; if (tuple.Item1 == hashAlgorithm) { num = tuple.Item2; num2 = tuple.Item3; break; } } if (num == -1) { throw new CryptographicException(System.SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); } int num3 = num2 >> 3; Span span = stackalloc byte[num3]; span.Fill(id); int num4 = (salt.Length - 1 + num3) / num3 * num3; int num5 = checked((password.Length + 1) * 2); if (password == default(ReadOnlySpan)) { num5 = 0; } int num6 = (num5 - 1 + num3) / num3 * num3; int num7 = num4 + num6; Span span2 = default(Span); byte[] array2 = null; if (num7 <= 1024) { span2 = stackalloc byte[num7]; } else { array2 = System.Security.Cryptography.CryptoPool.Rent(num7); span2 = array2.AsSpan(0, num7); } IncrementalHash incrementalHash = IncrementalHash.CreateHash(hashAlgorithm); try { CircularCopy(salt, span2.Slice(0, num4)); CircularCopyUtf16BE(password, span2.Slice(num4)); Span span3 = stackalloc byte[num >> 3]; Span span4 = stackalloc byte[num3]; while (true) { incrementalHash.AppendData(span); incrementalHash.AppendData(span2); for (int num8 = iterationCount; num8 > 0; num8--) { if (!incrementalHash.TryGetHashAndReset(span3, out var bytesWritten) || bytesWritten != span3.Length) { throw new CryptographicException(); } if (num8 != 1) { incrementalHash.AppendData(span3); } } if (span3.Length >= destination.Length) { break; } span3.CopyTo(destination); destination = destination.Slice(span3.Length); CircularCopy(span3, span4); for (int num9 = span2.Length / num3 - 1; num9 >= 0; num9--) { Span into = span2.Slice(num9 * num3, num3); AddPlusOne(into, span4); } } span3.Slice(0, destination.Length).CopyTo(destination); } finally { CryptographicOperations.ZeroMemory(span2); if (array2 != null) { System.Security.Cryptography.CryptoPool.Return(array2, 0); } incrementalHash.Dispose(); } } private static void AddPlusOne(Span into, Span addend) { int num = 1; for (int num2 = into.Length - 1; num2 >= 0; num2--) { int num3 = num + into[num2] + addend[num2]; into[num2] = (byte)num3; num = num3 >> 8; } } private static void CircularCopy(ReadOnlySpan bytes, Span destination) { while (destination.Length > 0) { if (destination.Length >= bytes.Length) { bytes.CopyTo(destination); destination = destination.Slice(bytes.Length); continue; } bytes.Slice(0, destination.Length).CopyTo(destination); break; } } private static void CircularCopyUtf16BE(ReadOnlySpan password, Span destination) { int num = password.Length * 2; Encoding bigEndianUnicode = Encoding.BigEndianUnicode; while (destination.Length > 0) { if (destination.Length >= num) { int bytes = bigEndianUnicode.GetBytes(password, destination); if (bytes != num) { throw new CryptographicException(); } destination = destination.Slice(bytes); Span span = destination.Slice(0, Math.Min(2, destination.Length)); span.Clear(); destination = destination.Slice(span.Length); continue; } ReadOnlySpan chars = password.Slice(0, destination.Length / 2); int bytes2 = bigEndianUnicode.GetBytes(chars, destination); if (bytes2 != destination.Length) { throw new CryptographicException(); } break; } } } } namespace System.Formats.Asn1 { internal ref struct AsnValueReader { private static readonly byte[] s_singleByte = new byte[1]; private ReadOnlySpan _span; private readonly AsnEncodingRules _ruleSet; internal bool HasData => !_span.IsEmpty; internal AsnValueReader(ReadOnlySpan span, AsnEncodingRules ruleSet) { _span = span; _ruleSet = ruleSet; } internal void ThrowIfNotEmpty() { if (!_span.IsEmpty) { new AsnReader(s_singleByte, _ruleSet).ThrowIfNotEmpty(); } } internal Asn1Tag PeekTag() { int bytesConsumed; return Asn1Tag.Decode(_span, out bytesConsumed); } internal ReadOnlySpan PeekEncodedValue() { AsnDecoder.ReadEncodedValue(_span, _ruleSet, out var _, out var _, out var bytesConsumed); return _span.Slice(0, bytesConsumed); } internal ReadOnlySpan ReadEncodedValue() { ReadOnlySpan result = PeekEncodedValue(); _span = _span.Slice(result.Length); return result; } internal bool TryReadInt32(out int value, Asn1Tag? expectedTag = null) { int bytesConsumed; bool result = AsnDecoder.TryReadInt32(_span, _ruleSet, out value, out bytesConsumed, expectedTag); _span = _span.Slice(bytesConsumed); return result; } internal ReadOnlySpan ReadIntegerBytes(Asn1Tag? expectedTag = null) { int bytesConsumed; ReadOnlySpan result = AsnDecoder.ReadIntegerBytes(_span, _ruleSet, out bytesConsumed, expectedTag); _span = _span.Slice(bytesConsumed); return result; } internal bool TryReadPrimitiveBitString(out int unusedBitCount, out ReadOnlySpan value, Asn1Tag? expectedTag = null) { int bytesConsumed; bool result = AsnDecoder.TryReadPrimitiveBitString(_span, _ruleSet, out unusedBitCount, out value, out bytesConsumed, expectedTag); _span = _span.Slice(bytesConsumed); return result; } internal byte[] ReadBitString(out int unusedBitCount, Asn1Tag? expectedTag = null) { int bytesConsumed; byte[] result = AsnDecoder.ReadBitString(_span, _ruleSet, out unusedBitCount, out bytesConsumed, expectedTag); _span = _span.Slice(bytesConsumed); return result; } internal bool TryReadPrimitiveOctetString(out ReadOnlySpan value, Asn1Tag? expectedTag = null) { int bytesConsumed; bool result = AsnDecoder.TryReadPrimitiveOctetString(_span, _ruleSet, out value, out bytesConsumed, expectedTag); _span = _span.Slice(bytesConsumed); return result; } internal byte[] ReadOctetString(Asn1Tag? expectedTag = null) { int bytesConsumed; byte[] result = AsnDecoder.ReadOctetString(_span, _ruleSet, out bytesConsumed, expectedTag); _span = _span.Slice(bytesConsumed); return result; } internal string ReadObjectIdentifier(Asn1Tag? expectedTag = null) { int bytesConsumed; string result = AsnDecoder.ReadObjectIdentifier(_span, _ruleSet, out bytesConsumed, expectedTag); _span = _span.Slice(bytesConsumed); return result; } internal System.Formats.Asn1.AsnValueReader ReadSequence(Asn1Tag? expectedTag = null) { AsnDecoder.ReadSequence(_span, _ruleSet, out var contentOffset, out var contentLength, out var bytesConsumed, expectedTag); ReadOnlySpan span = _span.Slice(contentOffset, contentLength); _span = _span.Slice(bytesConsumed); return new System.Formats.Asn1.AsnValueReader(span, _ruleSet); } internal System.Formats.Asn1.AsnValueReader ReadSetOf(Asn1Tag? expectedTag = null) { AsnDecoder.ReadSetOf(_span, _ruleSet, out var contentOffset, out var contentLength, out var bytesConsumed, skipSortOrderValidation: false, expectedTag); ReadOnlySpan span = _span.Slice(contentOffset, contentLength); _span = _span.Slice(bytesConsumed); return new System.Formats.Asn1.AsnValueReader(span, _ruleSet); } } internal static class AsnWriterExtensions { internal static void WriteEncodedValueForCrypto(this AsnWriter writer, ReadOnlySpan value) { try { writer.WriteEncodedValue(value); } catch (ArgumentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } internal static void WriteObjectIdentifierForCrypto(this AsnWriter writer, string value) { try { writer.WriteObjectIdentifier(value); } catch (ArgumentException inner) { throw new CryptographicException(System.SR.Cryptography_Der_Invalid_Encoding, inner); } } } }