// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Diagnostics;
using System.Security.Cryptography;
//
internal abstract class BasicSymmetricCipher : IDisposable
{
- protected BasicSymmetricCipher(byte[] iv, int blockSizeInBytes)
+ protected BasicSymmetricCipher(byte[]? iv, int blockSizeInBytes)
{
IV = iv;
BlockSizeInBytes = blockSizeInBytes;
}
}
- protected byte[] IV { get; private set; }
+ protected byte[]? IV { get; private set; }
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Diagnostics;
using System.Security.Cryptography;
{
private readonly bool _encrypting;
private SafeKeyHandle _hKey;
- private byte[] _currentIv; // CNG mutates this with the updated IV for the next stage on each Encrypt/Decrypt call.
- // The base IV holds a copy of the original IV for Reset(), until it is cleared by Dispose().
+ private byte[]? _currentIv; // CNG mutates this with the updated IV for the next stage on each Encrypt/Decrypt call.
+ // The base IV holds a copy of the original IV for Reset(), until it is cleared by Dispose().
- public BasicSymmetricCipherBCrypt(SafeAlgorithmHandle algorithm, CipherMode cipherMode, int blockSizeInBytes, byte[] key, bool ownsParentHandle, byte[] iv, bool encrypting)
+ public BasicSymmetricCipherBCrypt(SafeAlgorithmHandle algorithm, CipherMode cipherMode, int blockSizeInBytes, byte[] key, bool ownsParentHandle, byte[]? iv, bool encrypting)
: base(cipherMode.GetCipherIv(iv), blockSizeInBytes)
{
Debug.Assert(algorithm != null);
if (disposing)
{
SafeKeyHandle hKey = _hKey;
- _hKey = null;
+ _hKey = null!;
if (hKey != null)
{
hKey.Dispose();
}
- byte[] currentIv = _currentIv;
+ byte[]? currentIv = _currentIv;
_currentIv = null;
if (currentIv != null)
{
{
if (IV != null)
{
- Buffer.BlockCopy(IV, 0, _currentIv, 0, IV.Length);
+ Buffer.BlockCopy(IV, 0, _currentIv!, 0, IV.Length);
}
}
}
using BCryptOpenAlgorithmProviderFlags = Interop.BCrypt.BCryptOpenAlgorithmProviderFlags;
using BCryptCreateHashFlags = Interop.BCrypt.BCryptCreateHashFlags;
+#nullable enable
namespace Internal.Cryptography
{
//
//
// - "key" activates MAC hashing if present. If null, this HashProvider performs a regular old hash.
//
- public HashProviderCng(string hashAlgId, byte[] key) : this(hashAlgId, key, isHmac: key != null)
+ public HashProviderCng(string hashAlgId, byte[]? key) : this(hashAlgId, key, isHmac: key != null)
{
}
// Win7 won't set hHash, Win8+ will; and both will set _hHash.
// So keep hHash trapped in this scope to prevent (mis-)use of it.
{
- SafeBCryptHashHandle hHash = null;
+ SafeBCryptHashHandle? hHash = null;
NTSTATUS ntStatus = Interop.BCrypt.BCryptCreateHash(_hAlgorithm, out hHash, IntPtr.Zero, 0, key, key == null ? 0 : key.Length, BCryptCreateHashFlags.BCRYPT_HASH_REUSABLE_FLAG);
if (ntStatus == NTSTATUS.STATUS_INVALID_PARAMETER)
{
{
int cbSizeOfHashSize;
int hashSize;
+ Debug.Assert(_hHash != null);
NTSTATUS ntStatus = Interop.BCrypt.BCryptGetProperty(_hHash, Interop.BCrypt.BCryptPropertyStrings.BCRYPT_HASH_LENGTH, &hashSize, sizeof(int), out cbSizeOfHashSize, 0);
if (ntStatus != NTSTATUS.STATUS_SUCCESS)
throw Interop.BCrypt.CreateCryptographicException(ntStatus);
public sealed override unsafe void AppendHashData(ReadOnlySpan<byte> source)
{
+ Debug.Assert(_hHash != null);
NTSTATUS ntStatus = Interop.BCrypt.BCryptHashData(_hHash, source, source.Length, 0);
if (ntStatus != NTSTATUS.STATUS_SUCCESS)
{
return false;
}
+ Debug.Assert(_hHash != null);
NTSTATUS ntStatus = Interop.BCrypt.BCryptFinishHash(_hHash, destination, _hashSize, 0);
if (ntStatus != NTSTATUS.STATUS_SUCCESS)
{
private void DestroyHash()
{
- SafeBCryptHashHandle hHash = _hHash;
+ SafeBCryptHashHandle? hHash = _hHash;
_hHash = null;
if (hHash != null)
{
}
private readonly SafeBCryptAlgorithmHandle _hAlgorithm;
- private SafeBCryptHashHandle _hHash;
- private byte[] _key;
+ private SafeBCryptHashHandle? _hHash;
+ private byte[]? _key;
private readonly bool _reusable;
private readonly int _hashSize;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Diagnostics;
using System.Security.Cryptography;
// Otherwise the decryption buffer is just the input data.
//
- byte[] ciphertext = null;
+ byte[]? ciphertext = null;
if (_heldoverCipher == null)
{
{
if (disposing)
{
- byte[] heldoverCipher = _heldoverCipher;
+ byte[]? heldoverCipher = _heldoverCipher;
_heldoverCipher = null;
if (heldoverCipher != null)
{
// whether this is the final block that needs depadding. This block is held (in encrypted form) in _heldoverCipher. The next call to TransformBlock
// or TransformFinalBlock must include the decryption of _heldoverCipher in the results.
//
- private byte[] _heldoverCipher;
+ private byte[]? _heldoverCipher;
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
}
}
- internal static string GetErrorDescription(SafeCFErrorHandle cfError)
+ internal static string? GetErrorDescription(SafeCFErrorHandle cfError)
{
Debug.Assert(cfError != null);
if (interiorPointer != IntPtr.Zero)
{
- return Marshal.PtrToStringUTF8(interiorPointer);
+ return Marshal.PtrToStringUTF8(interiorPointer)!;
}
SafeCFDataHandle cfData = CFStringCreateExternalRepresentation(
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
out SafeCFDataHandle cfDataOut,
out SafeCFErrorHandle cfErrorOut);
- internal static byte[] EcdhKeyAgree(
+ internal static byte[]? EcdhKeyAgree(
SafeSecKeyRefHandle privateKey,
SafeSecKeyRefHandle publicKey,
Span<byte> opportunisticDestination,
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
lock (s_lookup)
{
- SafeTemporaryKeychainHandle temporaryHandle;
+ SafeTemporaryKeychainHandle? temporaryHandle;
if (s_lookup.TryGetValue(keychain.DangerousGetHandle(), out temporaryHandle))
{
lock (s_lookup)
{
- SafeTemporaryKeychainHandle temporaryHandle;
+ SafeTemporaryKeychainHandle? temporaryHandle;
if (s_lookup.TryGetValue(keychain.DangerousGetHandle(), out temporaryHandle))
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
internal static partial class Interop
{
internal static Exception CreateExceptionForOSStatus(int osStatus)
{
- string msg = GetSecErrorString(osStatus);
+ string? msg = GetSecErrorString(osStatus);
if (msg == null)
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
[DllImport(Libraries.AppleCryptoNative)]
private static extern SafeCFStringHandle AppleCryptoNative_SecCopyErrorMessageString(int osStatus);
- internal static string GetSecErrorString(int osStatus)
+ internal static string? GetSecErrorString(int osStatus)
{
using (SafeCFStringHandle cfString = AppleCryptoNative_SecCopyErrorMessageString(osStatus))
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeyExport(
- SafeSecKeyRefHandle key,
+ SafeSecKeyRefHandle? key,
int exportPrivate,
SafeCreateHandle cfExportPassphrase,
out SafeCFDataHandle cfDataOut,
out int pOSStatus);
internal static SafeCFDataHandle SecKeyExportData(
- SafeSecKeyRefHandle key,
+ SafeSecKeyRefHandle? key,
bool exportPrivate,
ReadOnlySpan<char> password)
{
}
internal static byte[] SecKeyExport(
- SafeSecKeyRefHandle key,
+ SafeSecKeyRefHandle? key,
bool exportPrivate,
string password)
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
+using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
return new SafeBignumHandle(handle, true);
}
- internal static byte[] ExtractBignum(IntPtr bignum, int targetSize)
+ internal static byte[]? ExtractBignum(IntPtr bignum, int targetSize)
{
// Given that the only reference held to bignum is an IntPtr, create an unowned SafeHandle
// to ensure that we don't destroy the key after extraction.
}
}
- private static unsafe byte[] ExtractBignum(SafeBignumHandle bignum, int targetSize)
+ private static unsafe byte[]? ExtractBignum(SafeBignumHandle? bignum, int targetSize)
{
if (bignum == null || bignum.IsInvalid)
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
DSAParameters dsaParameters = new DSAParameters
{
- P = Crypto.ExtractBignum(p_bn, pgy_cb),
- Q = Crypto.ExtractBignum(q_bn, qx_cb),
- G = Crypto.ExtractBignum(g_bn, pgy_cb),
- Y = Crypto.ExtractBignum(y_bn, pgy_cb),
+ P = Crypto.ExtractBignum(p_bn, pgy_cb)!,
+ Q = Crypto.ExtractBignum(q_bn, qx_cb)!,
+ G = Crypto.ExtractBignum(g_bn, pgy_cb)!,
+ Y = Crypto.ExtractBignum(y_bn, pgy_cb)!,
};
if (includePrivateParameters)
int gLength,
byte[] y,
int yLength,
- byte[] x,
+ byte[]? x,
int xLength);
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
-#nullable enable
internal static partial class Interop
{
internal static partial class Crypto
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
string oid,
byte[] qx, int qxLength,
byte[] qy, int qyLength,
- byte[] d, int dLength);
+ byte[]? d, int dLength);
internal static SafeEcKeyHandle EcKeyCreateByKeyParameters(
string oid,
byte[] qx, int qxLength,
byte[] qy, int qyLength,
- byte[] d, int dLength)
+ byte[]? d, int dLength)
{
SafeEcKeyHandle key;
int rc = EcKeyCreateByKeyParameters(out key, oid, qx, qxLength, qy, qyLength, d, dLength);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyCreateByExplicitParameters")]
internal static extern SafeEcKeyHandle EcKeyCreateByExplicitParameters(
ECCurve.ECCurveType curveType,
- byte[] qx, int qxLength,
- byte[] qy, int qyLength,
- byte[] d, int dLength,
+ byte[]? qx, int qxLength,
+ byte[]? qy, int qyLength,
+ byte[]? d, int dLength,
byte[] p, int pLength,
byte[] a, int aLength,
byte[] b, int bLength,
byte[] gx, int gxLength,
byte[] gy, int gyLength,
byte[] order, int nLength,
- byte[] cofactor, int cofactorLength,
- byte[] seed, int seedLength);
+ byte[]? cofactor, int cofactorLength,
+ byte[]? seed, int seedLength);
internal static SafeEcKeyHandle EcKeyCreateByExplicitCurve(ECCurve curve)
{
byte[] p;
if (curve.IsPrime)
{
- p = curve.Prime;
+ p = curve.Prime!;
}
else if (curve.IsCharacteristic2)
{
- p = curve.Polynomial;
+ p = curve.Polynomial!;
}
else
{
null, 0,
null, 0,
p, p.Length,
- curve.A, curve.A.Length,
- curve.B, curve.B.Length,
- curve.G.X, curve.G.X.Length,
- curve.G.Y, curve.G.Y.Length,
- curve.Order, curve.Order.Length,
- curve.Cofactor, curve.Cofactor.Length,
+ curve.A!, curve.A!.Length,
+ curve.B!, curve.B!.Length,
+ curve.G.X!, curve.G.X!.Length,
+ curve.G.Y!, curve.G.Y!.Length,
+ curve.Order!, curve.Order!.Length,
+ curve.Cofactor, curve.Cofactor!.Length,
curve.Seed, curve.Seed == null ? 0 : curve.Seed.Length);
if (key == null || key.IsInvalid)
var curve = parameters.Curve;
curve.CurveType = curveType;
- curve.A = Crypto.ExtractBignum(a_bn, cbFieldLength);
- curve.B = Crypto.ExtractBignum(b_bn, cbFieldLength);
+ curve.A = Crypto.ExtractBignum(a_bn, cbFieldLength)!;
+ curve.B = Crypto.ExtractBignum(b_bn, cbFieldLength)!;
curve.G = new ECPoint
{
X = Crypto.ExtractBignum(gx_bn, cbFieldLength),
Y = Crypto.ExtractBignum(gy_bn, cbFieldLength)
};
- curve.Order = Crypto.ExtractBignum(order_bn, cbSubgroupOrder);
+ curve.Order = Crypto.ExtractBignum(order_bn, cbSubgroupOrder)!;
if (curveType == ECCurve.ECCurveType.Characteristic2)
{
- curve.Polynomial = Crypto.ExtractBignum(p_bn, pFieldLength);
+ curve.Polynomial = Crypto.ExtractBignum(p_bn, pFieldLength)!;
}
else
{
- curve.Prime = Crypto.ExtractBignum(p_bn, pFieldLength);
+ curve.Prime = Crypto.ExtractBignum(p_bn, pFieldLength)!;
}
// Optional parameters
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics;
{
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyCreateByOid")]
private static extern SafeEcKeyHandle CryptoNative_EcKeyCreateByOid(string oid);
- internal static SafeEcKeyHandle EcKeyCreateByOid(string oid)
+ internal static SafeEcKeyHandle? EcKeyCreateByOid(string oid)
{
SafeEcKeyHandle handle = CryptoNative_EcKeyCreateByOid(oid);
if (handle == null || handle.IsInvalid)
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
RSAParameters rsaParameters = new RSAParameters
{
- Modulus = Crypto.ExtractBignum(n, modulusSize),
- Exponent = Crypto.ExtractBignum(e, 0),
+ Modulus = Crypto.ExtractBignum(n, modulusSize)!,
+ Exponent = Crypto.ExtractBignum(e, 0)!,
};
if (includePrivateParameters)
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetRsaParameters(
SafeRsaHandle key,
- byte[] n,
+ byte[]? n,
int nLength,
- byte[] e,
+ byte[]? e,
int eLength,
- byte[] d,
+ byte[]? d,
int dLength,
- byte[] p,
+ byte[]? p,
int pLength,
- byte[] dmp1,
+ byte[]? dmp1,
int dmp1Length,
- byte[] q,
+ byte[]? q,
int qLength,
- byte[] dmq1,
+ byte[]? dmq1,
int dmq1Length,
- byte[] iqmp,
+ byte[]? iqmp,
int iqmpLength);
internal enum RsaPadding : int
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Text;
using System.Diagnostics;
using static Interop.BCrypt;
using Microsoft.Win32.SafeHandles;
-#nullable enable
namespace Internal.NativeCrypto
{
internal static partial class BCryptNative
public const string BCRYPT_CHAIN_MODE_GCM = "ChainingModeGCM";
public const string BCRYPT_CHAIN_MODE_CCM = "ChainingModeCCM";
- public static SafeAlgorithmHandle BCryptOpenAlgorithmProvider(string pszAlgId, string pszImplementation, OpenAlgorithmProviderFlags dwFlags)
+ public static SafeAlgorithmHandle BCryptOpenAlgorithmProvider(string pszAlgId, string? pszImplementation, OpenAlgorithmProviderFlags dwFlags)
{
SafeAlgorithmHandle hAlgorithm;
NTSTATUS ntStatus = Interop.BCryptOpenAlgorithmProvider(out hAlgorithm, pszAlgId, pszImplementation, (int)dwFlags);
internal static class Interop
{
[DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)]
- public static extern NTSTATUS BCryptOpenAlgorithmProvider(out SafeAlgorithmHandle phAlgorithm, string pszAlgId, string pszImplementation, int dwFlags);
+ public static extern NTSTATUS BCryptOpenAlgorithmProvider(out SafeAlgorithmHandle phAlgorithm, string pszAlgId, string? pszImplementation, int dwFlags);
[DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)]
public static extern unsafe NTSTATUS BCryptSetProperty(SafeAlgorithmHandle hObject, string pszProperty, string pbInput, int cbInput, int dwFlags);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
internal static partial class BCrypt
{
// Note: input and output are allowed to be the same buffer. BCryptEncrypt will correctly do the encryption in place according to CNG documentation.
- internal static int BCryptEncrypt(SafeKeyHandle hKey, byte[] input, int inputOffset, int inputCount, byte[] iv, byte[] output, int outputOffset, int outputCount)
+ internal static int BCryptEncrypt(SafeKeyHandle hKey, byte[] input, int inputOffset, int inputCount, byte[]? iv, byte[] output, int outputOffset, int outputCount)
{
Debug.Assert(input != null);
Debug.Assert(inputOffset >= 0);
}
// Note: input and output are allowed to be the same buffer. BCryptDecrypt will correctly do the decryption in place according to CNG documentation.
- internal static int BCryptDecrypt(SafeKeyHandle hKey, byte[] input, int inputOffset, int inputCount, byte[] iv, byte[] output, int outputOffset, int outputCount)
+ internal static int BCryptDecrypt(SafeKeyHandle hKey, byte[] input, int inputOffset, int inputCount, byte[]? iv, byte[] output, int outputOffset, int outputCount)
{
Debug.Assert(input != null);
Debug.Assert(inputOffset >= 0);
}
[DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)]
- public static extern unsafe 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);
+ public static extern unsafe 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(Libraries.BCrypt, CharSet = CharSet.Unicode)]
- public static extern unsafe 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);
+ public static extern unsafe 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);
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
internal partial class BCrypt
{
[DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)]
- internal static extern NTSTATUS BCryptOpenAlgorithmProvider(out SafeBCryptAlgorithmHandle phAlgorithm, string pszAlgId, string pszImplementation, BCryptOpenAlgorithmProviderFlags dwFlags);
+ internal static extern NTSTATUS BCryptOpenAlgorithmProvider(out SafeBCryptAlgorithmHandle phAlgorithm, string pszAlgId, string? pszImplementation, BCryptOpenAlgorithmProviderFlags dwFlags);
[Flags]
internal enum BCryptOpenAlgorithmProviderFlags : int
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
internal static extern ErrorCode NCryptImportKey(SafeNCryptProviderHandle hProvider, IntPtr hImportKey, string pszBlobType, ref NCryptBufferDesc pParameterList, [Out] out SafeNCryptKeyHandle phKey, ref byte pbData, int cbData, int dwFlags);
[DllImport(Interop.Libraries.NCrypt, CharSet = CharSet.Unicode)]
- internal static extern ErrorCode NCryptExportKey(SafeNCryptKeyHandle hKey, IntPtr hExportKey, string pszBlobType, IntPtr pParameterList, [Out] byte[] pbOutput, int cbOutput, [Out] out int pcbResult, int dwFlags);
+ internal static extern ErrorCode NCryptExportKey(SafeNCryptKeyHandle hKey, IntPtr hExportKey, string pszBlobType, IntPtr pParameterList, [Out] byte[]? pbOutput, int cbOutput, [Out] out int pcbResult, int dwFlags);
[DllImport(Interop.Libraries.NCrypt, CharSet = CharSet.Unicode)]
internal static extern ErrorCode NCryptExportKey(SafeNCryptKeyHandle hKey, IntPtr hExportKey, string pszBlobType, IntPtr pParameterList, ref byte pbOutput, int cbOutput, [Out] out int pcbResult, int dwFlags);
internal static extern ErrorCode NCryptDeleteKey(SafeNCryptKeyHandle hKey, int dwFlags);
[DllImport(Interop.Libraries.NCrypt, CharSet = CharSet.Unicode)]
- internal static extern ErrorCode NCryptCreatePersistedKey(SafeNCryptProviderHandle hProvider, out SafeNCryptKeyHandle phKey, string pszAlgId, string pszKeyName, int dwLegacyKeySpec, CngKeyCreationOptions dwFlags);
+ internal static extern ErrorCode NCryptCreatePersistedKey(SafeNCryptProviderHandle hProvider, out SafeNCryptKeyHandle phKey, string pszAlgId, string? pszKeyName, int dwLegacyKeySpec, CngKeyCreationOptions dwFlags);
[DllImport(Interop.Libraries.NCrypt, CharSet = CharSet.Unicode)]
internal static extern ErrorCode NCryptFinalizeKey(SafeNCryptKeyHandle hKey, int dwFlags);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
SafeNCryptSecretHandle hSharedSecret,
string pwszKDF,
[In] ref NCryptBufferDesc pParameterList,
- [Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbDerivedKey,
+ [Out, MarshalAs(UnmanagedType.LPArray)] byte[]? pbDerivedKey,
int cbDerivedKey,
[Out] out int pcbResult,
SecretAgreementFlags dwFlags);
SafeNCryptSecretHandle secretAgreement,
string kdf,
string hashAlgorithm,
- byte[] hmacKey,
- byte[] secretPrepend,
- byte[] secretAppend,
+ byte[]? hmacKey,
+ byte[]? secretPrepend,
+ byte[]? secretAppend,
SecretAgreementFlags flags)
{
// First marshal the hash algoritm
if (pHmacKey != null)
{
NCryptBuffer hmacKeyBuffer = default;
- hmacKeyBuffer.cbBuffer = hmacKey.Length;
+ hmacKeyBuffer.cbBuffer = hmacKey!.Length;
hmacKeyBuffer.BufferType = BufferType.KdfHmacKey;
hmacKeyBuffer.pvBuffer = new IntPtr(pHmacKey);
if (pSecretPrepend != null)
{
NCryptBuffer secretPrependBuffer = default;
- secretPrependBuffer.cbBuffer = secretPrepend.Length;
+ secretPrependBuffer.cbBuffer = secretPrepend!.Length;
secretPrependBuffer.BufferType = BufferType.KdfSecretPrepend;
secretPrependBuffer.pvBuffer = new IntPtr(pSecretPrepend);
if (pSecretAppend != null)
{
NCryptBuffer secretAppendBuffer = default;
- secretAppendBuffer.cbBuffer = secretAppend.Length;
+ secretAppendBuffer.cbBuffer = secretAppend!.Length;
secretAppendBuffer.BufferType = BufferType.KdfSecretAppend;
secretAppendBuffer.pvBuffer = new IntPtr(pSecretAppend);
internal static byte[] DeriveKeyMaterialHash(
SafeNCryptSecretHandle secretAgreement,
string hashAlgorithm,
- byte[] secretPrepend,
- byte[] secretAppend,
+ byte[]? secretPrepend,
+ byte[]? secretAppend,
SecretAgreementFlags flags)
{
return DeriveKeyMaterial(
internal static byte[] DeriveKeyMaterialHmac(
SafeNCryptSecretHandle secretAgreement,
string hashAlgorithm,
- byte[] hmacKey,
- byte[] secretPrepend,
- byte[] secretAppend,
+ byte[]? hmacKey,
+ byte[]? secretPrepend,
+ byte[]? secretAppend,
SecretAgreementFlags flags)
{
return DeriveKeyMaterial(
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
/// <typeparam name="T">Specifies the type of SafeHandle.</typeparam>
internal static class SafeHandleCache<T> where T : SafeHandle
{
- private static T s_invalidHandle;
+ private static T? s_invalidHandle;
/// <summary>
/// Gets a cached, invalid handle. As the instance is cached, it should either never be Disposed
/// </summary>
internal static T GetInvalidHandle(Func<T> invalidHandleFactory)
{
- T currentHandle = Volatile.Read(ref s_invalidHandle);
+ T? currentHandle = Volatile.Read(ref s_invalidHandle);
if (currentHandle == null)
{
T newHandle = invalidHandleFactory();
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
-#nullable enable
namespace Microsoft.Win32.SafeHandles
{
internal abstract class SafeInteriorHandle : SafeHandle
return true;
}
- return Parameters.Value.Span.SequenceEqual(other.Parameters.Value.Span);
+ return Parameters!.Value.Span.SequenceEqual(other.Parameters!.Value.Span);
}
internal bool HasNullEquivalentParameters()
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
#pragma warning disable SA1028 // ignore whitespace warnings for generated code
using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
-#nullable enable
namespace System.Security.Cryptography.Asn1
{
[StructLayout(LayoutKind.Sequential)]
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
#pragma warning disable SA1028 // ignore whitespace warnings for generated code
using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
-#nullable enable
namespace System.Security.Cryptography.Asn1
{
[StructLayout(LayoutKind.Sequential)]
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
#pragma warning disable SA1028 // ignore whitespace warnings for generated code
using System;<xsl:if test="asn:SequenceOf | asn:SetOf">
using System.Collections.Generic;</xsl:if>
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
-#nullable enable
namespace <xsl:value-of select="@namespace" />
{
[StructLayout(LayoutKind.Sequential)]
finally
{
CryptographicOperations.ZeroMemory(decryptedSpan);
- CryptoPool.Return(decrypted.Array);
+ CryptoPool.Return(decrypted.Array!);
}
}
}
finally
{
CryptographicOperations.ZeroMemory(decryptedSpan);
- CryptoPool.Return(decrypted.Array, clearSize: 0);
+ CryptoPool.Return(decrypted.Array!, clearSize: 0);
}
}
}
if (parameters.G.Length != keySizeInBytes || parameters.Y.Length != keySizeInBytes)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPGY);
- if (hasPrivateKey && parameters.X.Length != parameters.Q.Length)
+ if (hasPrivateKey && parameters.X!.Length != parameters.Q.Length)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedQX);
byte[] blob;
}
// The Q length is hardcoded into BCRYPT_DSA_KEY_BLOB, so check it now we can give a nicer error message.
- if (parameters.Q.Length != Sha1HashOutputSize)
+ if (parameters.Q!.Length != Sha1HashOutputSize)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_QRestriction_ShortKey);
Interop.BCrypt.Emit(blob, ref offset, parameters.Q);
Debug.Assert(offset == sizeof(BCRYPT_DSA_KEY_BLOB), $"Expected offset = sizeof(BCRYPT_DSA_KEY_BLOB), got {offset} != {sizeof(BCRYPT_DSA_KEY_BLOB)}");
- Interop.BCrypt.Emit(blob, ref offset, parameters.P);
- Interop.BCrypt.Emit(blob, ref offset, parameters.G);
- Interop.BCrypt.Emit(blob, ref offset, parameters.Y);
+ Interop.BCrypt.Emit(blob, ref offset, parameters.P!);
+ Interop.BCrypt.Emit(blob, ref offset, parameters.G!);
+ Interop.BCrypt.Emit(blob, ref offset, parameters.Y!);
if (includePrivate)
{
- Interop.BCrypt.Emit(blob, ref offset, parameters.X);
+ Interop.BCrypt.Emit(blob, ref offset, parameters.X!);
}
Debug.Assert(offset == blobSize, $"Expected offset = blobSize, got {offset} != {blobSize}");
{
int blobSize =
sizeof(BCRYPT_DSA_KEY_BLOB_V2) +
- (parameters.Seed == null ? parameters.Q.Length : parameters.Seed.Length) + // Use Q size if Seed is not present
- parameters.Q.Length +
- parameters.P.Length +
- parameters.G.Length +
- parameters.Y.Length +
- (includePrivateParameters ? parameters.X.Length : 0);
+ (parameters.Seed == null ? parameters.Q!.Length : parameters.Seed.Length) + // Use Q size if Seed is not present
+ parameters.Q!.Length +
+ parameters.P!.Length +
+ parameters.G!.Length +
+ parameters.Y!.Length +
+ (includePrivateParameters ? parameters.X!.Length : 0);
blob = new byte[blobSize];
fixed (byte* pDsaBlob = &blob[0])
if (includePrivateParameters)
{
- Interop.BCrypt.Emit(blob, ref offset, parameters.X);
+ Interop.BCrypt.Emit(blob, ref offset, parameters.X!);
}
Debug.Assert(offset == blobSize, $"Expected offset = blobSize, got {offset} != {blobSize}");
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using Internal.Cryptography;
using System.Diagnostics;
using System.IO;
}
public override string SignatureAlgorithm => "DSA";
- public override string KeyExchangeAlgorithm => null;
+ public override string? KeyExchangeAlgorithm => null;
// Need to override since base methods throw a "override me" exception: makes SignData/VerifyData function.
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) =>
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Buffers;
using System.Diagnostics;
using System.Numerics;
writer.PopSequence();
}
- private static void WriteKeyComponent(AsnWriter writer, byte[] component, bool bitString)
+ private static void WriteKeyComponent(AsnWriter writer, byte[]? component, bool bitString)
{
using (AsnWriter inner = new AsnWriter(AsnEncodingRules.DER))
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Diagnostics;
using System.IO;
using Internal.Cryptography;
if (parameters.G.Length != keySize || parameters.Y.Length != keySize)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPGY);
- if (hasPrivateKey && parameters.X.Length != parameters.Q.Length)
+ if (hasPrivateKey && parameters.X!.Length != parameters.Q.Length)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedQX);
ThrowIfDisposed();
if (disposing)
{
FreeKey();
- _key = null;
+ _key = null!;
}
base.Dispose(disposing);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Buffers;
using System.Diagnostics;
using System.IO;
{
public sealed partial class DSASecurityTransforms : DSA
{
- private SecKeyPair _keys;
+ private SecKeyPair? _keys;
private bool _disposed;
public DSASecurityTransforms()
if (parameters.G.Length != keySize || parameters.Y.Length != keySize)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedPGY);
- if (hasPrivateKey && parameters.X.Length != parameters.Q.Length)
+ if (hasPrivateKey && parameters.X!.Length != parameters.Q.Length)
throw new ArgumentException(SR.Cryptography_InvalidDsaParameters_MismatchedQX);
if (!(8 * parameters.P.Length).IsLegalSize(LegalKeySizes))
{
ThrowIfDisposed();
- SecKeyPair current = _keys;
+ SecKeyPair? current = _keys;
if (current != null)
{
{
ThrowIfDisposed();
- SecKeyPair current = _keys;
+ SecKeyPair? current = _keys;
_keys = newKeyPair;
current?.Dispose();
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Diagnostics;
using Internal.NativeCrypto;
using static Interop.Crypt32;
/// </summary>
internal static Interop.BCrypt.ECC_CURVE_ALG_ID_ENUM GetHashAlgorithmId(HashAlgorithmName? name)
{
- if (name.HasValue == false || string.IsNullOrEmpty(name.Value.Name))
+ if (name.HasValue == false || string.IsNullOrEmpty(name!.Value.Name))
{
return Interop.BCrypt.ECC_CURVE_ALG_ID_ENUM.BCRYPT_NO_CURVE_GENERATION_ALG_ID;
}
/// <summary>
/// Is the curve named, or once of the special nist curves
/// </summary>
- internal static bool IsECNamedCurve(string algorithm)
+ internal static bool IsECNamedCurve(string? algorithm)
{
return (algorithm == BCryptNative.AlgorithmName.ECDH ||
algorithm == BCryptNative.AlgorithmName.ECDsa);
/// <summary>
/// Maps algorithm to curve name accounting for the special nist curves
/// </summary>
- internal static string SpecialNistAlgorithmToCurveName(string algorithm, out string oidValue)
+ internal static string SpecialNistAlgorithmToCurveName(string? algorithm, out string oidValue)
{
switch (algorithm)
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using Internal.Cryptography;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
// byte[cbKey] D
int blobSize = sizeof(BCRYPT_ECCKEY_BLOB) +
- parameters.Q.X.Length +
- parameters.Q.Y.Length;
+ parameters.Q.X!.Length +
+ parameters.Q.Y!.Length;
if (includePrivateParameters)
{
- blobSize += parameters.D.Length;
+ blobSize += parameters.D!.Length;
}
blob = new byte[blobSize];
Interop.BCrypt.Emit(blob, ref offset, parameters.Q.Y);
if (includePrivateParameters)
{
- Interop.BCrypt.Emit(blob, ref offset, parameters.D);
+ Interop.BCrypt.Emit(blob, ref offset, parameters.D!);
}
// We better have computed the right allocation size above!
// byte[cbSubgroupOrder] D
int blobSize = sizeof(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.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 ? 0 : curve.Seed.Length) +
- parameters.Q.X.Length +
- parameters.Q.Y.Length;
+ parameters.Q.X!.Length +
+ parameters.Q.Y!.Length;
if (includePrivateParameters)
{
- blobSize += parameters.D.Length;
+ blobSize += parameters.D!.Length;
}
blob = new byte[blobSize];
Interop.BCrypt.Emit(blob, ref offset, parameters.Q.Y);
if (includePrivateParameters)
{
- Interop.BCrypt.Emit(blob, ref offset, parameters.D);
+ Interop.BCrypt.Emit(blob, ref offset, parameters.D!);
}
// We better have computed the right allocation size above!
// byte[cbSeed] Seed
int blobSize = sizeof(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.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 ? 0 : curve.Seed.Length);
byte[] blob = new byte[blobSize];
/// to the pre-Win10 magic numbers to support import on pre-Win10 environments
/// that don't have the named curve functionality.
/// </summary>
- private static KeyBlobMagicNumber EcdsaCurveNameToMagicNumber(string name, bool includePrivateParameters) =>
+ private static KeyBlobMagicNumber EcdsaCurveNameToMagicNumber(string? name, bool includePrivateParameters) =>
EcdsaCurveNameToAlgorithm(name) switch
{
AlgorithmName.ECDsaP256 => includePrivateParameters ?
/// to the pre-Win10 magic numbers to support import on pre-Win10 environments
/// that don't have the named curve functionality.
/// </summary>
- private static KeyBlobMagicNumber EcdhCurveNameToMagicNumber(string name, bool includePrivateParameters) =>
+ private static KeyBlobMagicNumber EcdhCurveNameToMagicNumber(string? name, bool includePrivateParameters) =>
EcdhCurveNameToAlgorithm(name) switch
{
AlgorithmName.ECDHP256 => includePrivateParameters ?
/// Map a curve name to algorithm. This enables curves that worked pre-Win10
/// to work with newer APIs for import and export.
/// </summary>
- internal static string EcdsaCurveNameToAlgorithm(string algorithm)
+ internal static string EcdsaCurveNameToAlgorithm(string? algorithm)
{
switch (algorithm)
{
/// Map a curve name to algorithm. This enables curves that worked pre-Win10
/// to work with newer APIs for import and export.
/// </summary>
- internal static string EcdhCurveNameToAlgorithm(string algorithm)
+ internal static string EcdhCurveNameToAlgorithm(string? algorithm)
{
switch (algorithm)
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using Internal.NativeCrypto;
namespace System.Security.Cryptography
{
ECParameters ecparams = default;
- string curveName = GetCurveName(out string oidValue);
- byte[] blob = null;
+ string? curveName = GetCurveName(out string? oidValue);
+ byte[]? blob = null;
try
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography
public override byte[] DeriveKeyFromHash(
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
- byte[] secretPrepend,
- byte[] secretAppend)
+ byte[]? secretPrepend,
+ byte[]? secretAppend)
{
if (otherPartyPublicKey == null)
throw new ArgumentNullException(nameof(otherPartyPublicKey));
public override byte[] DeriveKeyFromHmac(
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
- byte[] hmacKey,
- byte[] secretPrepend,
- byte[] secretAppend)
+ byte[]? hmacKey,
+ byte[]? secretPrepend,
+ byte[]? secretAppend)
{
if (otherPartyPublicKey == null)
throw new ArgumentNullException(nameof(otherPartyPublicKey));
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Diagnostics;
using System.Runtime.InteropServices;
/// <summary>
/// Derive the raw ECDH value into <paramref name="hasher"/>, if present, otherwise returning the value.
/// </summary>
- internal delegate byte[] DeriveSecretAgreement(ECDiffieHellmanPublicKey otherPartyPublicKey, IncrementalHash hasher);
+ internal delegate byte[]? DeriveSecretAgreement(ECDiffieHellmanPublicKey otherPartyPublicKey, IncrementalHash? hasher);
internal static byte[] DeriveKeyFromHash(
ECDiffieHellmanPublicKey otherPartyPublicKey,
{
hash.AppendData(secretPrepend);
- byte[] secretAgreement = deriveSecretAgreement(otherPartyPublicKey, hash);
+ byte[]? secretAgreement = deriveSecretAgreement(otherPartyPublicKey, hash);
// We want the side effect, and it should not have returned the answer.
Debug.Assert(secretAgreement == null);
internal static unsafe byte[] DeriveKeyFromHmac(
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
- byte[] hmacKey,
+ byte[]? hmacKey,
ReadOnlySpan<byte> secretPrepend,
ReadOnlySpan<byte> secretAppend,
DeriveSecretAgreement deriveSecretAgreement)
if (useSecretAsKey)
{
hmacKey = deriveSecretAgreement(otherPartyPublicKey, null);
- Debug.Assert(hmacKey != null);
}
+ Debug.Assert(hmacKey != null);
// Reduce the likelihood of the value getting copied during heap compaction.
fixed (byte* pinnedHmacKey = hmacKey)
}
else
{
- byte[] secretAgreement = deriveSecretAgreement(otherPartyPublicKey, hash);
+ byte[]? secretAgreement = deriveSecretAgreement(otherPartyPublicKey, hash);
// We want the side effect, and it should not have returned the answer.
Debug.Assert(secretAgreement == null);
}
const int Sha1Size = 20;
const int Md5Size = 16;
- byte[] secretAgreement = deriveSecretAgreement(otherPartyPublicKey, null);
+ byte[]? secretAgreement = deriveSecretAgreement(otherPartyPublicKey, null);
Debug.Assert(secretAgreement != null);
// Reduce the likelihood of the value getting copied during heap compaction.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Diagnostics;
using Microsoft.Win32.SafeHandles;
public override byte[] DeriveKeyFromHash(
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
- byte[] secretPrepend,
- byte[] secretAppend)
+ byte[]? secretPrepend,
+ byte[]? secretAppend)
{
if (otherPartyPublicKey == null)
throw new ArgumentNullException(nameof(otherPartyPublicKey));
public override byte[] DeriveKeyFromHmac(
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
- byte[] hmacKey,
- byte[] secretPrepend,
- byte[] secretAppend)
+ byte[]? hmacKey,
+ byte[]? secretPrepend,
+ byte[]? secretAppend)
{
if (otherPartyPublicKey == null)
throw new ArgumentNullException(nameof(otherPartyPublicKey));
/// <summary>
/// Get the secret agreement generated between two parties
/// </summary>
- private byte[] DeriveSecretAgreement(ECDiffieHellmanPublicKey otherPartyPublicKey, IncrementalHash hasher)
+ private byte[]? DeriveSecretAgreement(ECDiffieHellmanPublicKey otherPartyPublicKey, IncrementalHash? hasher)
{
Debug.Assert(otherPartyPublicKey != null);
// which will throw an OpenSslCryptoException if no private key is available
ECParameters thisKeyExplicit = ExportExplicitParameters(true);
bool thisIsNamed = Interop.Crypto.EcKeyHasCurveName(_key.Value);
- ECDiffieHellmanOpenSslPublicKey otherKey = otherPartyPublicKey as ECDiffieHellmanOpenSslPublicKey;
+ ECDiffieHellmanOpenSslPublicKey? otherKey = otherPartyPublicKey as ECDiffieHellmanOpenSslPublicKey;
bool disposeOtherKey = false;
if (otherKey == null)
bool otherIsNamed = otherKey.HasCurveName;
- SafeEvpPKeyHandle ourKey = null;
- SafeEvpPKeyHandle theirKey = null;
- byte[] rented = null;
+ SafeEvpPKeyHandle? ourKey = null;
+ SafeEvpPKeyHandle? theirKey = null;
+ byte[]? rented = null;
int secretLength = 0;
try
if (disposing)
{
_key?.Dispose();
- _key = null;
+ _key = null!;
}
base.Dispose(disposing);
if (disposing)
{
_key?.Dispose();
- _key = null;
+ _key = null!;
}
base.Dispose(disposing);
public override byte[] DeriveKeyFromHash(
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
- byte[] secretPrepend,
- byte[] secretAppend)
+ byte[]? secretPrepend,
+ byte[]? secretAppend)
{
if (otherPartyPublicKey == null)
throw new ArgumentNullException(nameof(otherPartyPublicKey));
public override byte[] DeriveKeyFromHmac(
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
- byte[] hmacKey,
- byte[] secretPrepend,
- byte[] secretAppend)
+ byte[]? hmacKey,
+ byte[]? secretPrepend,
+ byte[]? secretAppend)
{
if (otherPartyPublicKey == null)
throw new ArgumentNullException(nameof(otherPartyPublicKey));
(pubKey, hasher) => DeriveSecretAgreement(pubKey, hasher));
}
- private byte[] DeriveSecretAgreement(ECDiffieHellmanPublicKey otherPartyPublicKey, IncrementalHash hasher)
+ private byte[]? DeriveSecretAgreement(ECDiffieHellmanPublicKey otherPartyPublicKey, IncrementalHash? hasher)
{
if (!(otherPartyPublicKey is ECDiffieHellmanSecurityTransformsPublicKey secTransPubKey))
{
nameof(otherPartyPublicKey));
}
- SafeSecKeyRefHandle thisPrivate = GetKeys().PrivateKey;
+ SafeSecKeyRefHandle? thisPrivate = GetKeys().PrivateKey;
if (thisPrivate == null)
{
// 66 bytes ((521 + 7) / 8), the Span path will always succeed.
Span<byte> secretSpan = stackalloc byte[66];
- byte[] secret = Interop.AppleCrypto.EcdhKeyAgree(
+ byte[]? secret = Interop.AppleCrypto.EcdhKeyAgree(
thisPrivate,
otherPublic,
secretSpan,
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using Internal.NativeCrypto;
namespace System.Security.Cryptography
{
// FriendlyName is required; an attempt was already made to default it in ECCurve
if (string.IsNullOrEmpty(curve.Oid.FriendlyName))
- throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value.ToString()));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value!.ToString()));
byte[] ecNamedCurveBlob = ECCng.GetNamedCurveBlob(ref parameters, ecdh: false);
ImportKeyBlob(ecNamedCurveBlob, curve.Oid.FriendlyName, includePrivateParameters);
{
ECParameters ecparams = default;
- string curveName = GetCurveName(out string oidValue);
+ string? curveName = GetCurveName(out string? oidValue);
if (string.IsNullOrEmpty(curveName))
{
if (disposing)
{
_key?.Dispose();
- _key = null;
+ _key = null!;
}
base.Dispose(disposing);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
// Use oid Value first if present, otherwise FriendlyName
string oid = !string.IsNullOrEmpty(parameters.Curve.Oid.Value) ?
- parameters.Curve.Oid.Value : parameters.Curve.Oid.FriendlyName;
+ parameters.Curve.Oid.Value : parameters.Curve.Oid.FriendlyName!;
SafeEcKeyHandle key = Interop.Crypto.EcKeyCreateByKeyParameters(
oid,
- parameters.Q.X, parameters.Q.X.Length,
- parameters.Q.Y, parameters.Q.Y.Length,
+ parameters.Q.X!, parameters.Q.X!.Length,
+ parameters.Q.Y!, parameters.Q.Y!.Length,
parameters.D, parameters.D == null ? 0 : parameters.D.Length);
return key;
Debug.Assert(parameters.Curve.IsPrime);
SafeEcKeyHandle key = Interop.Crypto.EcKeyCreateByExplicitParameters(
parameters.Curve.CurveType,
- parameters.Q.X, parameters.Q.X.Length,
- parameters.Q.Y, parameters.Q.Y.Length,
+ parameters.Q.X, parameters.Q.X!.Length,
+ parameters.Q.Y, parameters.Q.Y!.Length,
parameters.D, parameters.D == null ? 0 : parameters.D.Length,
- parameters.Curve.Prime, parameters.Curve.Prime.Length,
- parameters.Curve.A, parameters.Curve.A.Length,
- parameters.Curve.B, parameters.Curve.B.Length,
- parameters.Curve.G.X, parameters.Curve.G.X.Length,
- parameters.Curve.G.Y, parameters.Curve.G.Y.Length,
- parameters.Curve.Order, parameters.Curve.Order.Length,
- parameters.Curve.Cofactor, parameters.Curve.Cofactor.Length,
+ parameters.Curve.Prime!, parameters.Curve.Prime!.Length,
+ parameters.Curve.A!, parameters.Curve.A!.Length,
+ parameters.Curve.B!, parameters.Curve.B!.Length,
+ parameters.Curve.G.X!, parameters.Curve.G.X!.Length,
+ parameters.Curve.G.Y!, parameters.Curve.G.Y!.Length,
+ parameters.Curve.Order!, parameters.Curve.Order!.Length,
+ parameters.Curve.Cofactor, parameters.Curve.Cofactor!.Length,
parameters.Curve.Seed, parameters.Curve.Seed == null ? 0 : parameters.Curve.Seed.Length);
return key;
Debug.Assert(parameters.Curve.IsCharacteristic2);
SafeEcKeyHandle key = Interop.Crypto.EcKeyCreateByExplicitParameters(
parameters.Curve.CurveType,
- parameters.Q.X, parameters.Q.X.Length,
- parameters.Q.Y, parameters.Q.Y.Length,
+ parameters.Q.X, parameters.Q.X!.Length,
+ parameters.Q.Y, parameters.Q.Y!.Length,
parameters.D, parameters.D == null ? 0 : parameters.D.Length,
- parameters.Curve.Polynomial, parameters.Curve.Polynomial.Length,
- parameters.Curve.A, parameters.Curve.A.Length,
- parameters.Curve.B, parameters.Curve.B.Length,
- parameters.Curve.G.X, parameters.Curve.G.X.Length,
- parameters.Curve.G.Y, parameters.Curve.G.Y.Length,
- parameters.Curve.Order, parameters.Curve.Order.Length,
- parameters.Curve.Cofactor, parameters.Curve.Cofactor.Length,
+ parameters.Curve.Polynomial!, parameters.Curve.Polynomial!.Length,
+ parameters.Curve.A!, parameters.Curve.A!.Length,
+ parameters.Curve.B!, parameters.Curve.B!.Length,
+ parameters.Curve.G.X!, parameters.Curve.G.X!.Length,
+ parameters.Curve.G.Y!, parameters.Curve.G.Y!.Length,
+ parameters.Curve.Order!, parameters.Curve.Order!.Length,
+ parameters.Curve.Cofactor, parameters.Curve.Cofactor!.Length,
parameters.Curve.Seed, parameters.Curve.Seed == null ? 0 : parameters.Curve.Seed.Length);
return key;
public static SafeEcKeyHandle GenerateKeyByKeySize(int keySize)
{
- string oid = null;
+ string oid;
switch (keySize)
{
case 256: oid = ECDSA_P256_OID_VALUE; break;
throw new InvalidOperationException(SR.Cryptography_InvalidKeySize);
}
- SafeEcKeyHandle key = Interop.Crypto.EcKeyCreateByOid(oid);
+ SafeEcKeyHandle? key = Interop.Crypto.EcKeyCreateByOid(oid);
if (key == null || key.IsInvalid)
throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, oid));
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Diagnostics;
using Microsoft.Win32.SafeHandles;
{
internal sealed partial class ECOpenSsl : IDisposable
{
- private Lazy<SafeEcKeyHandle> _key;
+ private Lazy<SafeEcKeyHandle> _key = null!; // Always initialized
public ECOpenSsl(ECCurve curve)
{
if (curve.IsNamed)
{
- string oid = null;
// Use oid Value first if present, otherwise FriendlyName because Oid maintains a hard-coded
// cache that may have different casing for FriendlyNames than OpenSsl
- oid = !string.IsNullOrEmpty(curve.Oid.Value) ? curve.Oid.Value : curve.Oid.FriendlyName;
+ string oid = !string.IsNullOrEmpty(curve.Oid.Value) ? curve.Oid.Value : curve.Oid.FriendlyName!;
- SafeEcKeyHandle key = Interop.Crypto.EcKeyCreateByOid(oid);
+ SafeEcKeyHandle? key = Interop.Crypto.EcKeyCreateByOid(oid);
if (key == null || key.IsInvalid)
{
_key.Value?.Dispose();
}
- _key = null;
+ _key = null!;
}
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Buffers;
using System.Collections;
using System.Diagnostics;
}
else
{
- domainParameters = ECDomainParameters.Decode(algId.Parameters.Value, AsnEncodingRules.DER);
+ domainParameters = ECDomainParameters.Decode(algId.Parameters!.Value, AsnEncodingRules.DER);
}
ret = new ECParameters
// On Windows the FriendlyName is populated in places where the Value mightn't be.
if (string.IsNullOrEmpty(oid.Value))
{
+ Debug.Assert(oid.FriendlyName != null);
oid = Oid.FromFriendlyName(oid.FriendlyName, OidGroup.All);
}
- writer.WriteObjectIdentifier(oid.Value);
+ writer.WriteObjectIdentifier(oid.Value!);
}
else if (ecParameters.Curve.IsExplicit)
{
ref int k2,
ref int k3)
{
- byte[] polynomial = ecParameters.Curve.Polynomial;
+ byte[] polynomial = ecParameters.Curve.Polynomial!;
int lastIndex = polynomial.Length - 1;
// The most significant byte needs a set bit, and the least significant bit must be set.
private static void WriteCurve(in ECCurve curve, AsnWriter writer)
{
writer.PushSequence();
- WriteFieldElement(curve.A, writer);
- WriteFieldElement(curve.B, writer);
+ WriteFieldElement(curve.A!, writer);
+ WriteFieldElement(curve.B!, writer);
if (curve.Seed != null)
{
private static void WriteUncompressedBasePoint(in ECParameters ecParameters, AsnWriter writer)
{
- int basePointLength = ecParameters.Curve.G.X.Length * 2 + 1;
+ int basePointLength = ecParameters.Curve.G.X!.Length * 2 + 1;
byte[] tmp = CryptoPool.Rent(basePointLength);
tmp[0] = 0x04;
ecParameters.Curve.G.X.CopyTo(tmp.AsSpan(1));
private static void WriteUncompressedPublicKey(in ECParameters ecParameters, AsnWriter writer)
{
- int publicKeyLength = ecParameters.Q.X.Length * 2 + 1;
+ int publicKeyLength = ecParameters.Q.X!.Length * 2 + 1;
writer.WriteBitString(
publicKeyLength,
{
publicKeyBytes[0] = 0x04;
point.X.AsSpan().CopyTo(publicKeyBytes.Slice(1));
- point.Y.AsSpan().CopyTo(publicKeyBytes.Slice(1 + point.X.Length));
+ point.Y.AsSpan().CopyTo(publicKeyBytes.Slice(1 + point.X!.Length));
});
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
{
internal sealed class EccSecurityTransforms : IDisposable
{
- private SecKeyPair _keys;
+ private SecKeyPair? _keys;
private bool _disposed;
private readonly string _disposedName;
{
ThrowIfDisposed();
- SecKeyPair current = _keys;
+ SecKeyPair? current = _keys;
if (current != null)
{
{
ThrowIfDisposed();
- SecKeyPair current = _keys;
+ SecKeyPair? current = _keys;
_keys = keyPair;
current?.Dispose();
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
if (innerRead != decryptedMemory.Length)
{
- ret = default;
+ ret = default!;
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
out string encryptionAlgorithmOid,
out bool isPkcs12);
- byte[] encryptedRent = null;
+ byte[]? encryptedRent = null;
Span<byte> encryptedSpan = default;
- AsnWriter writer = null;
+ AsnWriter? writer = null;
try
{
finally
{
CryptographicOperations.ZeroMemory(encryptedSpan);
- CryptoPool.Return(encryptedRent, clearSize: 0);
+ CryptoPool.Return(encryptedRent!, clearSize: 0);
writer?.Dispose();
cipher.Dispose();
finally
{
CryptographicOperations.ZeroMemory(decrypted);
- CryptoPool.Return(decrypted.Array, clearSize: 0);
+ CryptoPool.Return(decrypted.Array!, clearSize: 0);
}
}
finally
{
CryptographicOperations.ZeroMemory(decrypted);
- CryptoPool.Return(decrypted.Array, clearSize: 0);
+ CryptoPool.Return(decrypted.Array!, clearSize: 0);
}
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
// Maybe some future PBES3 will have one with a default.
HashAlgorithmName digestAlgorithmName;
- SymmetricAlgorithm cipher = null;
+ SymmetricAlgorithm? cipher = null;
bool pkcs12 = false;
{
Span<byte> buf = stackalloc byte[128];
ReadOnlySpan<byte> effectivePasswordBytes = stackalloc byte[0];
- byte[] rented = null;
- System.Text.Encoding encoding = null;
+ byte[]? rented = null;
+ System.Text.Encoding? encoding = null;
if (passwordBytes.Length > 0 || password.Length == 0)
{
byte[] destination,
Span<byte> ivDest)
{
- byte[] pwdTmpBytes = null;
+ byte[]? pwdTmpBytes = null;
byte[] derivedKey;
byte[] iv = cipher.IV;
{
if (passwordBytes.Length > 0)
{
- Debug.Assert(pwdTmpBytes.Length == passwordBytes.Length);
+ Debug.Assert(pwdTmpBytes!.Length == passwordBytes.Length);
passwordBytes.CopyTo(pwdTmpBytes);
}
else if (password.Length > 0)
{
int length = encoding.GetBytes(password, pwdTmpBytes);
- if (length != pwdTmpBytes.Length)
+ if (length != pwdTmpBytes!.Length)
{
Debug.Fail($"UTF-8 encoding size changed between GetByteCount and GetBytes");
throw new CryptographicException();
}
else
{
- Debug.Assert(pwdTmpBytes.Length == 0);
+ Debug.Assert(pwdTmpBytes!.Length == 0);
}
using (var pbkdf2 = new Rfc2898DeriveBytes(pwdTmpBytes, salt.ToArray(), iterationCount, prf))
{
Span<byte> buf = stackalloc byte[128];
ReadOnlySpan<byte> effectivePasswordBytes = stackalloc byte[0];
- byte[] rented = null;
- System.Text.Encoding encoding = null;
+ byte[]? rented = null;
+ System.Text.Encoding? encoding = null;
if (passwordBytes.Length > 0 || password.Length == 0)
{
byte? requestedKeyLength,
ref Span<byte> iv)
{
- string algId = encryptionScheme.Algorithm.Value;
+ string? algId = encryptionScheme.Algorithm.Value;
if (algId == Oids.Aes128Cbc ||
algId == Oids.Aes192Cbc ||
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
// https://tools.ietf.org/html/rfc7292#appendix-B.2
Debug.Assert(iterationCount >= 1);
- if (!s_uvLookup.TryGetValue(hashAlgorithm, out Tuple<int, int> uv))
+ if (!s_uvLookup.TryGetValue(hashAlgorithm, out Tuple<int, int>? uv))
{
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name);
}
// 4. Set I=S||P to be the concatenation of S and P.
int ILen = SLen + PLen;
Span<byte> I = stackalloc byte[0];
- byte[] IRented = null;
+ byte[]? IRented = null;
if (ILen <= 1024)
{
parameters.Modulus.Length;
if (includePrivate)
{
- blobSize += parameters.P.Length +
- parameters.Q.Length;
+ blobSize += parameters.P!.Length +
+ parameters.Q!.Length;
}
byte[] rsaBlob = new byte[blobSize];
if (includePrivate)
{
- pBcryptBlob->cbPrime1 = parameters.P.Length;
- pBcryptBlob->cbPrime2 = parameters.Q.Length;
+ pBcryptBlob->cbPrime1 = parameters.P!.Length;
+ pBcryptBlob->cbPrime2 = parameters.Q!.Length;
}
int offset = sizeof(BCRYPT_RSAKEY_BLOB);
if (includePrivate)
{
- Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.P);
- Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.Q);
+ Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.P!);
+ Interop.BCrypt.Emit(rsaBlob, ref offset, parameters.Q!);
}
// We better have computed the right allocation size above!
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.InteropServices;
hashAlgorithm,
alg =>
{
- using (HashProviderCng hashProvider = new HashProviderCng(alg.Name, null))
+ using (HashProviderCng hashProvider = new HashProviderCng(alg.Name!, null))
{
return hashProvider.HashSizeInBytes;
}
throw new ArgumentNullException(nameof(hash));
}
- string hashAlgorithmName = hashAlgorithm.Name;
+ string? hashAlgorithmName = hashAlgorithm.Name;
if (string.IsNullOrEmpty(hashAlgorithmName))
{
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
public override unsafe bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten)
{
- string hashAlgorithmName = hashAlgorithm.Name;
+ string? hashAlgorithmName = hashAlgorithm.Name;
if (string.IsNullOrEmpty(hashAlgorithmName))
{
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
public override unsafe bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
- string hashAlgorithmName = hashAlgorithm.Name;
+ string? hashAlgorithmName = hashAlgorithm.Name;
if (string.IsNullOrEmpty(hashAlgorithmName))
{
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Buffers;
using System.Diagnostics;
using System.IO;
if (padding == null)
throw new ArgumentNullException(nameof(padding));
- Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor oaepProcessor);
+ Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor? oaepProcessor);
SafeRsaHandle key = GetKey();
int rsaSize = Interop.Crypto.RsaSize(key);
- byte[] buf = null;
+ byte[]? buf = null;
Span<byte> destination = default;
try
finally
{
CryptographicOperations.ZeroMemory(destination);
- CryptoPool.Return(buf, clearSize: 0);
+ CryptoPool.Return(buf!, clearSize: 0);
}
}
throw new ArgumentNullException(nameof(padding));
}
- Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor oaepProcessor);
+ Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor? oaepProcessor);
SafeRsaHandle key = GetKey();
int keySizeBytes = Interop.Crypto.RsaSize(key);
if (destination.Length < keySizeBytes)
{
Span<byte> tmp = stackalloc byte[0];
- byte[] rent = null;
+ byte[]? rent = null;
// RSA up through 4096 stackalloc
if (keySizeBytes <= 512)
ReadOnlySpan<byte> data,
Span<byte> destination,
Interop.Crypto.RsaPadding rsaPadding,
- RsaPaddingProcessor rsaPaddingProcessor,
+ RsaPaddingProcessor? rsaPaddingProcessor,
out int bytesWritten)
{
// If rsaPadding is PKCS1 or OAEP-SHA1 then no depadding method should be present.
}
Span<byte> decryptBuf = destination;
- byte[] paddingBuf = null;
+ byte[]? paddingBuf = null;
if (rsaPaddingProcessor != null)
{
if (padding == null)
throw new ArgumentNullException(nameof(padding));
- Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor oaepProcessor);
+ Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor? oaepProcessor);
SafeRsaHandle key = GetKey();
byte[] buf = new byte[Interop.Crypto.RsaSize(key)];
throw new ArgumentNullException(nameof(padding));
}
- Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor oaepProcessor);
+ Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor? oaepProcessor);
SafeRsaHandle key = GetKey();
return TryEncrypt(key, data, destination, rsaPadding, oaepProcessor, out bytesWritten);
ReadOnlySpan<byte> data,
Span<byte> destination,
Interop.Crypto.RsaPadding rsaPadding,
- RsaPaddingProcessor rsaPaddingProcessor,
+ RsaPaddingProcessor? rsaPaddingProcessor,
out int bytesWritten)
{
int rsaSize = Interop.Crypto.RsaSize(key);
private static Interop.Crypto.RsaPadding GetInteropPadding(
RSAEncryptionPadding padding,
- out RsaPaddingProcessor rsaPaddingProcessor)
+ out RsaPaddingProcessor? rsaPaddingProcessor)
{
if (padding == RSAEncryptionPadding.Pkcs1)
{
if (disposing)
{
FreeKey();
- _key = null;
+ _key = null!;
}
base.Dispose(disposing);
hashAlgorithm, padding,
true,
out int bytesWritten,
- out byte[] signature))
+ out byte[]? signature))
{
Debug.Fail("TrySignHash should not return false in allocation mode");
throw new CryptographicException();
padding,
false,
out bytesWritten,
- out byte[] alloced);
+ out byte[]? alloced);
Debug.Assert(alloced == null);
return ret;
RSASignaturePadding padding,
bool allocateSignature,
out int bytesWritten,
- out byte[] signature)
+ out byte[]? signature)
{
Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));
Debug.Assert(padding != null);
{
// All of the current HashAlgorithmName values correspond to the SN values in OpenSSL 0.9.8.
// If there's ever a new one that doesn't, translate it here.
- string sn = hashAlgorithmName.Name;
+ string sn = hashAlgorithmName.Name!;
int nid = Interop.Crypto.ObjSn2Nid(sn);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Buffers;
using System.Diagnostics;
using System.IO;
{
public sealed partial class RSASecurityTransforms : RSA
{
- private SecKeyPair _keys;
+ private SecKeyPair? _keys;
public RSASecurityTransforms()
: this(2048)
out bytesWritten);
}
- RsaPaddingProcessor processor;
+ RsaPaddingProcessor? processor;
switch (padding.Mode)
{
ThrowIfDisposed();
- RsaPaddingProcessor processor = null;
+ RsaPaddingProcessor? processor = null;
if (padding.Mode == RSASignaturePaddingMode.Pss)
{
private void ThrowIfDisposed()
{
- SecKeyPair current = _keys;
+ SecKeyPair? current = _keys;
if (current != null && current.PublicKey == null)
{
internal SecKeyPair GetKeys()
{
ThrowIfDisposed();
- SecKeyPair current = _keys;
+ SecKeyPair? current = _keys;
if (current != null)
{
{
ThrowIfDisposed();
- SecKeyPair current = _keys;
+ SecKeyPair? current = _keys;
_keys = newKeyPair;
current?.Dispose();
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Buffers.Binary;
using System.Collections.Concurrent;
using System.Diagnostics;
{
// https://tools.ietf.org/html/rfc3447#section-7.1.1
- byte[] dbMask = null;
+ byte[]? dbMask = null;
Span<byte> dbMaskSpan = Span<byte>.Empty;
try
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Security.Cryptography.Apple;
namespace System.Security.Cryptography
internal sealed class SecKeyPair : IDisposable
{
internal SafeSecKeyRefHandle PublicKey { get; private set; }
- internal SafeSecKeyRefHandle PrivateKey { get; private set; }
+ internal SafeSecKeyRefHandle? PrivateKey { get; private set; }
- private SecKeyPair(SafeSecKeyRefHandle publicKey, SafeSecKeyRefHandle privateKey)
+ private SecKeyPair(SafeSecKeyRefHandle publicKey, SafeSecKeyRefHandle? privateKey)
{
PublicKey = publicKey;
PrivateKey = privateKey;
PrivateKey?.Dispose();
PrivateKey = null;
PublicKey?.Dispose();
- PublicKey = null;
+ PublicKey = null!;
}
internal static SecKeyPair PublicPrivatePair(SafeSecKeyRefHandle publicKey, SafeSecKeyRefHandle privateKey)
{
protected Aes() { }
public static new System.Security.Cryptography.Aes Create() { throw null; }
- public static new System.Security.Cryptography.Aes Create(string algorithmName) { throw null; }
+ public static new System.Security.Cryptography.Aes? Create(string algorithmName) { throw null; }
}
public sealed partial class AesCcm : System.IDisposable
{
public AesCcm(System.ReadOnlySpan<byte> key) { }
public static System.Security.Cryptography.KeySizes NonceByteSizes { get { throw null; } }
public static System.Security.Cryptography.KeySizes TagByteSizes { get { throw null; } }
- public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[] associatedData = null) { }
+ public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[]? associatedData = null) { }
public void Decrypt(System.ReadOnlySpan<byte> nonce, System.ReadOnlySpan<byte> ciphertext, System.ReadOnlySpan<byte> tag, System.Span<byte> plaintext, System.ReadOnlySpan<byte> associatedData = default(System.ReadOnlySpan<byte>)) { }
public void Dispose() { }
- public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[] associatedData = null) { }
+ public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[]? associatedData = null) { }
public void Encrypt(System.ReadOnlySpan<byte> nonce, System.ReadOnlySpan<byte> plaintext, System.Span<byte> ciphertext, System.Span<byte> tag, System.ReadOnlySpan<byte> associatedData = default(System.ReadOnlySpan<byte>)) { }
}
public sealed partial class AesGcm : System.IDisposable
public AesGcm(System.ReadOnlySpan<byte> key) { }
public static System.Security.Cryptography.KeySizes NonceByteSizes { get { throw null; } }
public static System.Security.Cryptography.KeySizes TagByteSizes { get { throw null; } }
- public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[] associatedData = null) { }
+ public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[]? associatedData = null) { }
public void Decrypt(System.ReadOnlySpan<byte> nonce, System.ReadOnlySpan<byte> ciphertext, System.ReadOnlySpan<byte> tag, System.Span<byte> plaintext, System.ReadOnlySpan<byte> associatedData = default(System.ReadOnlySpan<byte>)) { }
public void Dispose() { }
- public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[] associatedData = null) { }
+ public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[]? associatedData = null) { }
public void Encrypt(System.ReadOnlySpan<byte> nonce, System.ReadOnlySpan<byte> plaintext, System.Span<byte> ciphertext, System.Span<byte> tag, System.ReadOnlySpan<byte> associatedData = default(System.ReadOnlySpan<byte>)) { }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } }
public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; }
- public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
+ public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; }
- public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
+ public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) { throw null; }
protected override void Dispose(bool disposing) { }
public override void GenerateIV() { }
public override void GenerateKey() { }
public abstract partial class AsymmetricKeyExchangeDeformatter
{
protected AsymmetricKeyExchangeDeformatter() { }
- public abstract string Parameters { get; set; }
+ public abstract string? Parameters { get; set; }
public abstract byte[] DecryptKeyExchange(byte[] rgb);
public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key);
}
public abstract partial class AsymmetricKeyExchangeFormatter
{
protected AsymmetricKeyExchangeFormatter() { }
- public abstract string Parameters { get; }
+ public abstract string? Parameters { get; }
public abstract byte[] CreateKeyExchange(byte[] data);
- public abstract byte[] CreateKeyExchange(byte[] data, System.Type symAlgType);
+ public abstract byte[] CreateKeyExchange(byte[] data, System.Type? symAlgType);
public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key);
}
public abstract partial class AsymmetricSignatureDeformatter
public static bool AllowOnlyFipsAlgorithms { get { throw null; } }
public static void AddAlgorithm(System.Type algorithm, params string[] names) { }
public static void AddOID(string oid, params string[] names) { }
- public static object CreateFromName(string name) { throw null; }
- public static object CreateFromName(string name, params object[] args) { throw null; }
+ public static object? CreateFromName(string name) { throw null; }
+ public static object? CreateFromName(string name, params object?[]? args) { throw null; }
public static byte[] EncodeOID(string str) { throw null; }
- public static string MapNameToOID(string name) { throw null; }
+ public static string? MapNameToOID(string name) { throw null; }
}
public abstract partial class DeriveBytes : System.IDisposable
{
protected DES() { }
public override byte[] Key { get { throw null; } set { } }
public static new System.Security.Cryptography.DES Create() { throw null; }
- public static new System.Security.Cryptography.DES Create(string algName) { throw null; }
+ public static new System.Security.Cryptography.DES? Create(string algName) { throw null; }
public static bool IsSemiWeakKey(byte[] rgbKey) { throw null; }
public static bool IsWeakKey(byte[] rgbKey) { throw null; }
}
public static new System.Security.Cryptography.DSA Create() { throw null; }
public static System.Security.Cryptography.DSA Create(int keySizeInBits) { throw null; }
public static System.Security.Cryptography.DSA Create(System.Security.Cryptography.DSAParameters parameters) { throw null; }
- public static new System.Security.Cryptography.DSA Create(string algName) { throw null; }
+ public static new System.Security.Cryptography.DSA? Create(string algName) { throw null; }
public abstract byte[] CreateSignature(byte[] rgbHash);
public abstract System.Security.Cryptography.DSAParameters ExportParameters(bool includePrivateParameters);
public override void FromXmlString(string xmlString) { }
{
public int Counter;
public byte[] G;
- public byte[] J;
+ public byte[]? J;
public byte[] P;
public byte[] Q;
- public byte[] Seed;
- public byte[] X;
+ public byte[]? Seed;
+ public byte[]? X;
public byte[] Y;
}
public partial class DSASignatureDeformatter : System.Security.Cryptography.AsymmetricSignatureDeformatter
private int _dummyPrimitive;
public byte[] A;
public byte[] B;
- public byte[] Cofactor;
+ public byte[]? Cofactor;
public System.Security.Cryptography.ECCurve.ECCurveType CurveType;
public System.Security.Cryptography.ECPoint G;
public System.Security.Cryptography.HashAlgorithmName? Hash;
public byte[] Order;
public byte[] Polynomial;
public byte[] Prime;
- public byte[] Seed;
+ public byte[]? Seed;
public bool IsCharacteristic2 { get { throw null; } }
public bool IsExplicit { get { throw null; } }
public bool IsNamed { get { throw null; } }
protected ECDiffieHellman() { }
public override string KeyExchangeAlgorithm { get { throw null; } }
public abstract System.Security.Cryptography.ECDiffieHellmanPublicKey PublicKey { get; }
- public override string SignatureAlgorithm { get { throw null; } }
+ public override string? SignatureAlgorithm { get { throw null; } }
public static new System.Security.Cryptography.ECDiffieHellman Create() { throw null; }
public static System.Security.Cryptography.ECDiffieHellman Create(System.Security.Cryptography.ECCurve curve) { throw null; }
public static System.Security.Cryptography.ECDiffieHellman Create(System.Security.Cryptography.ECParameters parameters) { throw null; }
- public static new System.Security.Cryptography.ECDiffieHellman Create(string algorithm) { throw null; }
+ public static new System.Security.Cryptography.ECDiffieHellman? Create(string algorithm) { throw null; }
public byte[] DeriveKeyFromHash(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
- public virtual byte[] DeriveKeyFromHash(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] secretPrepend, byte[] secretAppend) { throw null; }
- public byte[] DeriveKeyFromHmac(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] hmacKey) { throw null; }
- public virtual byte[] DeriveKeyFromHmac(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] hmacKey, byte[] secretPrepend, byte[] secretAppend) { throw null; }
+ public virtual byte[] DeriveKeyFromHash(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[]? secretPrepend, byte[]? secretAppend) { throw null; }
+ public byte[] DeriveKeyFromHmac(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[]? hmacKey) { throw null; }
+ public virtual byte[] DeriveKeyFromHmac(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[]? hmacKey, byte[]? secretPrepend, byte[]? secretAppend) { throw null; }
public virtual byte[] DeriveKeyMaterial(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey) { throw null; }
public virtual byte[] DeriveKeyTls(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed) { throw null; }
public virtual byte[] ExportECPrivateKey() { throw null; }
public abstract partial class ECDsa : System.Security.Cryptography.AsymmetricAlgorithm
{
protected ECDsa() { }
- public override string KeyExchangeAlgorithm { get { throw null; } }
+ public override string? KeyExchangeAlgorithm { get { throw null; } }
public override string SignatureAlgorithm { get { throw null; } }
public static new System.Security.Cryptography.ECDsa Create() { throw null; }
public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECCurve curve) { throw null; }
public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECParameters parameters) { throw null; }
- public static new System.Security.Cryptography.ECDsa Create(string algorithm) { throw null; }
+ public static new System.Security.Cryptography.ECDsa? Create(string algorithm) { throw null; }
public virtual byte[] ExportECPrivateKey() { throw null; }
public virtual System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw null; }
public virtual System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { throw null; }
public partial struct ECParameters
{
public System.Security.Cryptography.ECCurve Curve;
- public byte[] D;
+ public byte[]? D;
public System.Security.Cryptography.ECPoint Q;
public void Validate() { }
}
public partial struct ECPoint
{
- public byte[] X;
- public byte[] Y;
+ public byte[]? X;
+ public byte[]? Y;
}
public static class HKDF
{
- public static byte[] Extract(HashAlgorithmName hashAlgorithmName, byte[] ikm, byte[] salt = null) { throw null; }
+ public static byte[] Extract(HashAlgorithmName hashAlgorithmName, byte[] ikm, byte[]? salt = null) { throw null; }
public static int Extract(HashAlgorithmName hashAlgorithmName, ReadOnlySpan<byte> ikm, ReadOnlySpan<byte> salt, Span<byte> prk) { throw null; }
- public static byte[] Expand(HashAlgorithmName hashAlgorithmName, byte[] prk, int outputLength, byte[] info = null) { throw null; }
+ public static byte[] Expand(HashAlgorithmName hashAlgorithmName, byte[] prk, int outputLength, byte[]? info = null) { throw null; }
public static void Expand(HashAlgorithmName hashAlgorithmName, ReadOnlySpan<byte> prk, Span<byte> output, ReadOnlySpan<byte> info) { throw null; }
- public static byte[] DeriveKey(HashAlgorithmName hashAlgorithmName, byte[] ikm, int outputLength, byte[] salt = null, byte[] info = null) { throw null; }
+ public static byte[] DeriveKey(HashAlgorithmName hashAlgorithmName, byte[] ikm, int outputLength, byte[]? salt = null, byte[]? info = null) { throw null; }
public static void DeriveKey(HashAlgorithmName hashAlgorithmName, ReadOnlySpan<byte> ikm, Span<byte> output, ReadOnlySpan<byte> salt, ReadOnlySpan<byte> info) { throw null; }
}
public partial class HMACMD5 : System.Security.Cryptography.HMAC
{
protected MD5() { }
public static new System.Security.Cryptography.MD5 Create() { throw null; }
- public static new System.Security.Cryptography.MD5 Create(string algName) { throw null; }
+ public static new System.Security.Cryptography.MD5? Create(string algName) { throw null; }
}
public partial class PKCS1MaskGenerationMethod : System.Security.Cryptography.MaskGenerationMethod
{
{
protected RandomNumberGenerator() { }
public static System.Security.Cryptography.RandomNumberGenerator Create() { throw null; }
- public static System.Security.Cryptography.RandomNumberGenerator Create(string rngName) { throw null; }
+ public static System.Security.Cryptography.RandomNumberGenerator? Create(string rngName) { throw null; }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public static void Fill(System.Span<byte> data) { }
public virtual int EffectiveKeySize { get { throw null; } set { } }
public override int KeySize { get { throw null; } set { } }
public static new System.Security.Cryptography.RC2 Create() { throw null; }
- public static new System.Security.Cryptography.RC2 Create(string AlgName) { throw null; }
+ public static new System.Security.Cryptography.RC2? Create(string AlgName) { throw null; }
}
public partial class Rfc2898DeriveBytes : System.Security.Cryptography.DeriveBytes
{
{
protected Rijndael() { }
public static new System.Security.Cryptography.Rijndael Create() { throw null; }
- public static new System.Security.Cryptography.Rijndael Create(string algName) { throw null; }
+ public static new System.Security.Cryptography.Rijndael? Create(string algName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class RijndaelManaged : System.Security.Cryptography.Rijndael
public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } }
public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; }
- public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
+ public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; }
- public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
+ public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) { throw null; }
protected override void Dispose(bool disposing) { }
public override void GenerateIV() { }
public override void GenerateKey() { }
public static new System.Security.Cryptography.RSA Create() { throw null; }
public static System.Security.Cryptography.RSA Create(int keySizeInBits) { throw null; }
public static System.Security.Cryptography.RSA Create(System.Security.Cryptography.RSAParameters parameters) { throw null; }
- public static new System.Security.Cryptography.RSA Create(string algName) { throw null; }
+ public static new System.Security.Cryptography.RSA? Create(string algName) { throw null; }
public virtual byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; }
public virtual byte[] DecryptValue(byte[] rgb) { throw null; }
public virtual byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; }
public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA512 { get { throw null; } }
public static System.Security.Cryptography.RSAEncryptionPadding Pkcs1 { get { throw null; } }
public static System.Security.Cryptography.RSAEncryptionPadding CreateOaep(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
- public override bool Equals(object obj) { throw null; }
- public bool Equals(System.Security.Cryptography.RSAEncryptionPadding other) { throw null; }
+ public override bool Equals(object? obj) { throw null; }
+ public bool Equals(System.Security.Cryptography.RSAEncryptionPadding? other) { throw null; }
public override int GetHashCode() { throw null; }
- public static bool operator ==(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { throw null; }
- public static bool operator !=(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { throw null; }
+ public static bool operator ==(System.Security.Cryptography.RSAEncryptionPadding? left, System.Security.Cryptography.RSAEncryptionPadding? right) { throw null; }
+ public static bool operator !=(System.Security.Cryptography.RSAEncryptionPadding? left, System.Security.Cryptography.RSAEncryptionPadding? right) { throw null; }
public override string ToString() { throw null; }
}
public enum RSAEncryptionPaddingMode
{
public RSAOAEPKeyExchangeDeformatter() { }
public RSAOAEPKeyExchangeDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
- public override string Parameters { get { throw null; } set { } }
+ public override string? Parameters { get { throw null; } set { } }
public override byte[] DecryptKeyExchange(byte[] rgbData) { throw null; }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
{
public RSAOAEPKeyExchangeFormatter() { }
public RSAOAEPKeyExchangeFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
- public byte[] Parameter { get { throw null; } set { } }
- public override string Parameters { get { throw null; } }
- public System.Security.Cryptography.RandomNumberGenerator Rng { get { throw null; } set { } }
+ public byte[]? Parameter { get { throw null; } set { } }
+ public override string? Parameters { get { throw null; } }
+ public System.Security.Cryptography.RandomNumberGenerator? Rng { get { throw null; } set { } }
public override byte[] CreateKeyExchange(byte[] rgbData) { throw null; }
- public override byte[] CreateKeyExchange(byte[] rgbData, System.Type symAlgType) { throw null; }
+ public override byte[] CreateKeyExchange(byte[] rgbData, System.Type? symAlgType) { throw null; }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
public partial struct RSAParameters
{
- public byte[] D;
- public byte[] DP;
- public byte[] DQ;
+ public byte[]? D;
+ public byte[]? DP;
+ public byte[]? DQ;
public byte[] Exponent;
- public byte[] InverseQ;
+ public byte[]? InverseQ;
public byte[] Modulus;
- public byte[] P;
- public byte[] Q;
+ public byte[]? P;
+ public byte[]? Q;
}
public partial class RSAPKCS1KeyExchangeDeformatter : System.Security.Cryptography.AsymmetricKeyExchangeDeformatter
{
public RSAPKCS1KeyExchangeDeformatter() { }
public RSAPKCS1KeyExchangeDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
- public override string Parameters { get { throw null; } set { } }
- public System.Security.Cryptography.RandomNumberGenerator RNG { get { throw null; } set { } }
+ public override string? Parameters { get { throw null; } set { } }
+ public System.Security.Cryptography.RandomNumberGenerator? RNG { get { throw null; } set { } }
public override byte[] DecryptKeyExchange(byte[] rgbIn) { throw null; }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
public RSAPKCS1KeyExchangeFormatter() { }
public RSAPKCS1KeyExchangeFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { }
public override string Parameters { get { throw null; } }
- public System.Security.Cryptography.RandomNumberGenerator Rng { get { throw null; } set { } }
+ public System.Security.Cryptography.RandomNumberGenerator? Rng { get { throw null; } set { } }
public override byte[] CreateKeyExchange(byte[] rgbData) { throw null; }
- public override byte[] CreateKeyExchange(byte[] rgbData, System.Type symAlgType) { throw null; }
+ public override byte[] CreateKeyExchange(byte[] rgbData, System.Type? symAlgType) { throw null; }
public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { }
}
public partial class RSAPKCS1SignatureDeformatter : System.Security.Cryptography.AsymmetricSignatureDeformatter
public System.Security.Cryptography.RSASignaturePaddingMode Mode { get { throw null; } }
public static System.Security.Cryptography.RSASignaturePadding Pkcs1 { get { throw null; } }
public static System.Security.Cryptography.RSASignaturePadding Pss { get { throw null; } }
- public override bool Equals(object obj) { throw null; }
- public bool Equals(System.Security.Cryptography.RSASignaturePadding other) { throw null; }
+ public override bool Equals(object? obj) { throw null; }
+ public bool Equals(System.Security.Cryptography.RSASignaturePadding? other) { throw null; }
public override int GetHashCode() { throw null; }
- public static bool operator ==(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { throw null; }
- public static bool operator !=(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { throw null; }
+ public static bool operator ==(System.Security.Cryptography.RSASignaturePadding? left, System.Security.Cryptography.RSASignaturePadding? right) { throw null; }
+ public static bool operator !=(System.Security.Cryptography.RSASignaturePadding? left, System.Security.Cryptography.RSASignaturePadding? right) { throw null; }
public override string ToString() { throw null; }
}
public enum RSASignaturePaddingMode
{
protected SHA1() { }
public static new System.Security.Cryptography.SHA1 Create() { throw null; }
- public static new System.Security.Cryptography.SHA1 Create(string hashName) { throw null; }
+ public static new System.Security.Cryptography.SHA1? Create(string hashName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class SHA1Managed : System.Security.Cryptography.SHA1
{
protected SHA256() { }
public static new System.Security.Cryptography.SHA256 Create() { throw null; }
- public static new System.Security.Cryptography.SHA256 Create(string hashName) { throw null; }
+ public static new System.Security.Cryptography.SHA256? Create(string hashName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class SHA256Managed : System.Security.Cryptography.SHA256
{
protected SHA384() { }
public static new System.Security.Cryptography.SHA384 Create() { throw null; }
- public static new System.Security.Cryptography.SHA384 Create(string hashName) { throw null; }
+ public static new System.Security.Cryptography.SHA384? Create(string hashName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class SHA384Managed : System.Security.Cryptography.SHA384
{
protected SHA512() { }
public static new System.Security.Cryptography.SHA512 Create() { throw null; }
- public static new System.Security.Cryptography.SHA512 Create(string hashName) { throw null; }
+ public static new System.Security.Cryptography.SHA512? Create(string hashName) { throw null; }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed partial class SHA512Managed : System.Security.Cryptography.SHA512
{
public SignatureDescription() { }
public SignatureDescription(System.Security.SecurityElement el) { }
- public string DeformatterAlgorithm { get { throw null; } set { } }
- public string DigestAlgorithm { get { throw null; } set { } }
- public string FormatterAlgorithm { get { throw null; } set { } }
- public string KeyAlgorithm { get { throw null; } set { } }
+ public string? DeformatterAlgorithm { get { throw null; } set { } }
+ public string? DigestAlgorithm { get { throw null; } set { } }
+ public string? FormatterAlgorithm { get { throw null; } set { } }
+ public string? KeyAlgorithm { get { throw null; } set { } }
public virtual System.Security.Cryptography.AsymmetricSignatureDeformatter CreateDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { throw null; }
- public virtual System.Security.Cryptography.HashAlgorithm CreateDigest() { throw null; }
+ public virtual System.Security.Cryptography.HashAlgorithm? CreateDigest() { throw null; }
public virtual System.Security.Cryptography.AsymmetricSignatureFormatter CreateFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { throw null; }
}
public abstract partial class TripleDES : System.Security.Cryptography.SymmetricAlgorithm
protected TripleDES() { }
public override byte[] Key { get { throw null; } set { } }
public static new System.Security.Cryptography.TripleDES Create() { throw null; }
- public static new System.Security.Cryptography.TripleDES Create(string str) { throw null; }
+ public static new System.Security.Cryptography.TripleDES? Create(string str) { throw null; }
public static bool IsWeakKey(byte[] rgbKey) { throw null; }
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent)</TargetFrameworks>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="System.Security.Cryptography.Algorithms.cs" />
CipherMode cipherMode,
PaddingMode paddingMode,
byte[] key,
- byte[] iv,
+ byte[]? iv,
int blockSize,
bool encrypting)
{
CipherMode cipherMode,
PaddingMode paddingMode,
byte[] key,
- byte[] iv,
+ byte[]? iv,
int blockSize,
bool encrypting)
{
CipherMode cipherMode,
PaddingMode paddingMode,
byte[] key,
- byte[] iv,
+ byte[]? iv,
int blockSize,
bool encrypting)
{
return CreateTransform(Key, IV, encrypting: false);
}
- public sealed override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV)
+ public sealed override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV)
{
return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: false);
}
return CreateTransform(Key, IV, encrypting: true);
}
- public sealed override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV)
+ public sealed override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV)
{
return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: true);
}
base.Dispose(disposing);
}
- private ICryptoTransform CreateTransform(byte[] rgbKey, byte[] rgbIV, bool encrypting)
+ private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encrypting)
{
// note: rbgIV is guaranteed to be cloned before this method, so no need to clone it again
internal sealed class AppleCCCryptor : BasicSymmetricCipher
{
private readonly bool _encrypting;
- private SafeAppleCryptorHandle _cryptor;
+ private SafeAppleCryptorHandle _cryptor = null!;
public AppleCCCryptor(
Interop.AppleCrypto.PAL_SymmetricAlgorithm algorithm,
CipherMode cipherMode,
int blockSizeInBytes,
byte[] key,
- byte[] iv,
+ byte[]? iv,
bool encrypting)
: base(cipherMode.GetCipherIv(iv), blockSizeInBytes)
{
if (disposing)
{
_cryptor?.Dispose();
- _cryptor = null;
+ _cryptor = null!;
}
base.Dispose(disposing);
int ret;
int ccStatus;
- byte[] iv = IV;
+ byte[]? iv = IV;
fixed (byte* pbKey = key)
fixed (byte* pbIv = iv)
int ret;
int ccStatus;
- byte[] iv = IV;
+ byte[]? iv = IV;
fixed (byte* pbIv = iv)
{
CipherMode cipherMode,
PaddingMode paddingMode,
byte[] key,
- byte[] iv,
+ byte[]? iv,
int blockSize,
bool encrypting)
{
CipherMode cipherMode,
PaddingMode paddingMode,
byte[] key,
- byte[] iv,
+ byte[]? iv,
int blockSize,
bool encrypting)
{
CipherMode cipherMode,
PaddingMode paddingMode,
byte[] key,
- byte[] iv,
+ byte[]? iv,
int blockSize,
bool encrypting)
{
return CreateTransform(Key, IV, encrypting: false);
}
- public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV)
+ public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV)
{
return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: false);
}
return CreateTransform(Key, IV, encrypting: true);
}
- public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV)
+ public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV)
{
return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: true);
}
KeyValue = key;
}
- private ICryptoTransform CreateTransform(byte[] rgbKey, byte[] rgbIV, bool encrypting)
+ private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encrypting)
{
// note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again
ActualKey = ChangeKeyImpl(key);
}
- private byte[] ChangeKeyImpl(ReadOnlySpan<byte> key)
+ private byte[]? ChangeKeyImpl(ReadOnlySpan<byte> key)
{
- byte[] modifiedKey = null;
+ byte[]? modifiedKey = null;
// If _blockSize is -1 the key isn't going to be extractable by the object holder,
// so there's no point in recalculating it in managed code.
}
HashProvider oldHashProvider = _hMacProvider;
- _hMacProvider = null;
+ _hMacProvider = null!;
oldHashProvider?.Dispose(true);
_hMacProvider = HashProviderDispenser.CreateMacProvider(_hashAlgorithmId, key);
// The actual key used for hashing. This will not be the same as the original key passed to ChangeKey() if the original key exceeded the
// hash algorithm's block size. (See RFC 2104, section 2)
- public byte[] ActualKey { get; private set; }
+ public byte[]? ActualKey { get; private set; }
// Adds new data to be hashed. This can be called repeatedly in order to hash data from noncontiguous sources.
public void AppendHashData(byte[] data, int offset, int count) =>
if (disposing && _hMacProvider != null)
{
_hMacProvider.Dispose(true);
- _hMacProvider = null;
+ _hMacProvider = null!;
}
}
private readonly string _hashAlgorithmId;
- private HashProvider _hMacProvider;
- private volatile HashProvider _lazyHashProvider;
+ private HashProvider _hMacProvider = null!; // Initialized in helper
+ private volatile HashProvider? _lazyHashProvider;
private readonly int _blockSize;
}
}
/// <summary>
/// Map HashAlgorithm type to string; .NET Framework uses CryptoConfig functionality.
/// </summary>
- public static string ToAlgorithmName(this HashAlgorithm hashAlgorithm)
+ public static string? ToAlgorithmName(this HashAlgorithm hashAlgorithm)
{
if (hashAlgorithm is SHA1)
return HashAlgorithmNames.SHA1;
if (disposing && _hmacCtx != null)
{
_hmacCtx.Dispose();
- _hmacCtx = null;
+ _hmacCtx = null!;
}
}
}
return cipherMode != CipherMode.ECB;
}
- public static byte[] GetCipherIv(this CipherMode cipherMode, byte[] iv)
+ public static byte[]? GetCipherIv(this CipherMode cipherMode, byte[]? iv)
{
if (cipherMode.UsesIv())
{
internal class OpenSslCipher : BasicSymmetricCipher
{
private readonly bool _encrypting;
- private SafeEvpCipherCtxHandle _ctx;
+ private SafeEvpCipherCtxHandle _ctx = null!;
- public OpenSslCipher(IntPtr algorithm, CipherMode cipherMode, int blockSizeInBytes, byte[] key, int effectiveKeyLength, byte[] iv, bool encrypting)
+ public OpenSslCipher(IntPtr algorithm, CipherMode cipherMode, int blockSizeInBytes, byte[] key, int effectiveKeyLength, byte[]? iv, bool encrypting)
: base(cipherMode.GetCipherIv(iv), blockSizeInBytes)
{
Debug.Assert(algorithm != IntPtr.Zero);
if (_ctx != null)
{
_ctx.Dispose();
- _ctx = null;
+ _ctx = null!;
}
}
PaddingMode paddingMode,
byte[] key,
int effectiveKeyLength,
- byte[] iv,
+ byte[]? iv,
int blockSize,
bool encrypting)
{
PaddingMode paddingMode,
byte[] key,
int effectiveKeyLength,
- byte[] iv,
+ byte[]? iv,
int blockSize,
bool encrypting)
{
PaddingMode paddingMode,
byte[] key,
int effectiveKeyLength,
- byte[] iv,
+ byte[]? iv,
int blockSize,
bool encrypting)
{
return CreateTransform(Key, IV, encrypting: false);
}
- public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV)
+ public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV)
{
return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: false);
}
return CreateTransform(Key, IV, encrypting: true);
}
- public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV)
+ public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV)
{
return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: true);
}
Key = key;
}
- private ICryptoTransform CreateTransform(byte[] rgbKey, byte[] rgbIV, bool encrypting)
+ private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encrypting)
{
// note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again
public override KeySizes[] LegalKeySizes => _impl.LegalKeySizes;
public override ICryptoTransform CreateEncryptor() => _impl.CreateEncryptor();
- public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) => _impl.CreateEncryptor(rgbKey, rgbIV);
+ public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) => _impl.CreateEncryptor(rgbKey, rgbIV);
public override ICryptoTransform CreateDecryptor() => _impl.CreateDecryptor();
- public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) => _impl.CreateDecryptor(rgbKey, rgbIV);
+ public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) => _impl.CreateDecryptor(rgbKey, rgbIV);
public override void GenerateIV() => _impl.GenerateIV();
public override void GenerateKey() => _impl.GenerateKey();
CipherMode cipherMode,
PaddingMode paddingMode,
byte[] key,
- byte[] iv,
+ byte[]? iv,
int blockSize,
bool encrypting)
{
CipherMode cipherMode,
PaddingMode paddingMode,
byte[] key,
- byte[] iv,
+ byte[]? iv,
int blockSize,
bool encrypting)
{
CipherMode cipherMode,
PaddingMode paddingMode,
byte[] key,
- byte[] iv,
+ byte[]? iv,
int blockSize,
bool encrypting)
{
return CreateTransform(Key, IV, encrypting: false);
}
- public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV)
+ public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV)
{
return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: false);
}
return CreateTransform(Key, IV, encrypting: true);
}
- public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV)
+ public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV)
{
return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: true);
}
Key = key;
}
- private ICryptoTransform CreateTransform(byte[] rgbKey, byte[] rgbIV, bool encrypting)
+ private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encrypting)
{
// note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again
<DefineConstants>$(DefineConstants);INTERNAL_ASYMMETRIC_IMPLEMENTATIONS</DefineConstants>
<NoWarn>CS1573;CS3016;CA5350;CA5351;CA5379;CA5384;CA5385;$(NoWarn)</NoWarn>
<TargetFrameworks>$(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-OSX</TargetFrameworks>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<Import Project="$(CommonPath)System\Security\Cryptography\Asn1\AsnXml.targets"/>
<Import Project="$(CommonPath)System\Security\Cryptography\Asn1Reader\System.Security.Cryptography.Asn1Reader.Shared.projitems" />
return new AesImplementation();
}
- public static new Aes Create(string algorithmName)
+ public static new Aes? Create(string algorithmName)
{
- return (Aes)CryptoConfig.CreateFromName(algorithmName);
+ return (Aes?)CryptoConfig.CreateFromName(algorithmName);
}
private static readonly KeySizes[] s_legalBlockSizes = { new KeySizes(128, 128, 0) };
{
public sealed partial class AesCcm
{
- private byte[] _key;
+ private byte[] _key = null!;
private void ImportKey(ReadOnlySpan<byte> key)
{
public sealed partial class AesCcm
{
private static readonly SafeAlgorithmHandle s_aesCcm = AesBCryptModes.OpenAesAlgorithm(Cng.BCRYPT_CHAIN_MODE_CCM);
- private SafeKeyHandle _keyHandle;
+ private SafeKeyHandle _keyHandle = null!; // Always initialized in helper
private void ImportKey(ReadOnlySpan<byte> key)
{
ImportKey(key);
}
- public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[] associatedData = null)
+ public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[]? associatedData = null)
{
AesAEAD.CheckArgumentsForNull(nonce, plaintext, ciphertext, tag);
Encrypt((ReadOnlySpan<byte>)nonce, plaintext, ciphertext, tag, associatedData);
EncryptInternal(nonce, plaintext, ciphertext, tag, associatedData);
}
- public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[] associatedData = null)
+ public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[]? associatedData = null)
{
AesAEAD.CheckArgumentsForNull(nonce, plaintext, ciphertext, tag);
Decrypt((ReadOnlySpan<byte>)nonce, ciphertext, tag, plaintext, associatedData);
{
public sealed partial class AesGcm
{
- private SafeEvpCipherCtxHandle _ctxHandle;
+ private SafeEvpCipherCtxHandle _ctxHandle = null!;
private void ImportKey(ReadOnlySpan<byte> key)
{
public partial class AesGcm
{
private static readonly SafeAlgorithmHandle s_aesGcm = AesBCryptModes.OpenAesAlgorithm(Cng.BCRYPT_CHAIN_MODE_GCM);
- private SafeKeyHandle _keyHandle;
+ private SafeKeyHandle _keyHandle = null!; // Always initialized in helper
private void ImportKey(ReadOnlySpan<byte> key)
{
ImportKey(key);
}
- public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[] associatedData = null)
+ public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[]? associatedData = null)
{
AesAEAD.CheckArgumentsForNull(nonce, plaintext, ciphertext, tag);
Encrypt((ReadOnlySpan<byte>)nonce, plaintext, ciphertext, tag, associatedData);
EncryptInternal(nonce, plaintext, ciphertext, tag, associatedData);
}
- public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[] associatedData = null)
+ public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[]? associatedData = null)
{
AesAEAD.CheckArgumentsForNull(nonce, plaintext, ciphertext, tag);
Decrypt((ReadOnlySpan<byte>)nonce, ciphertext, tag, plaintext, associatedData);
public override KeySizes[] LegalBlockSizes => _impl.LegalBlockSizes;
public override KeySizes[] LegalKeySizes => _impl.LegalKeySizes;
public override ICryptoTransform CreateEncryptor() => _impl.CreateEncryptor();
- public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) => _impl.CreateEncryptor(rgbKey, rgbIV);
+ public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) => _impl.CreateEncryptor(rgbKey, rgbIV);
public override ICryptoTransform CreateDecryptor() => _impl.CreateDecryptor();
- public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) => _impl.CreateDecryptor(rgbKey, rgbIV);
+ public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) => _impl.CreateDecryptor(rgbKey, rgbIV);
public override void GenerateIV() => _impl.GenerateIV();
public override void GenerateKey() => _impl.GenerateKey();
public abstract class AsymmetricKeyExchangeDeformatter
{
protected AsymmetricKeyExchangeDeformatter() { }
- public abstract string Parameters { get; set; }
+ public abstract string? Parameters { get; set; }
public abstract void SetKey(AsymmetricAlgorithm key);
public abstract byte[] DecryptKeyExchange(byte[] rgb);
}
{
protected AsymmetricKeyExchangeFormatter() { }
- public abstract string Parameters { get; }
+ public abstract string? Parameters { get; }
public abstract void SetKey(AsymmetricAlgorithm key);
public abstract byte[] CreateKeyExchange(byte[] data);
// For .NET Framework compat, keep this even though symAlgType is not used.
- public abstract byte[] CreateKeyExchange(byte[] data, Type symAlgType);
+ public abstract byte[] CreateKeyExchange(byte[] data, Type? symAlgType);
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using Internal.Cryptography;
namespace System.Security.Cryptography
if (hash == null)
throw new ArgumentNullException(nameof(hash));
- SetHashAlgorithm(hash.ToAlgorithmName());
+ SetHashAlgorithm(hash.ToAlgorithmName()!);
+ Debug.Assert(hash.Hash != null);
return VerifySignature(hash.Hash, rgbSignature);
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using Internal.Cryptography;
namespace System.Security.Cryptography
if (hash == null)
throw new ArgumentNullException(nameof(hash));
- SetHashAlgorithm(hash.ToAlgorithmName());
+ SetHashAlgorithm(hash.ToAlgorithmName()!);
+ Debug.Assert(hash.Hash != null);
return CreateSignature(hash.Hash);
}
kdfCount,
Span<byte>.Empty,
out _,
- out byte[] allocated);
+ out byte[]? allocated);
Debug.Assert(ret);
- return allocated;
+ return allocated!;
}
internal static bool TryExportPkcs8KeyBlob(
int kdfCount,
Span<byte> destination,
out int bytesWritten,
- out byte[] allocated)
+ out byte[]? allocated)
{
using (SafeUnicodeStringHandle stringHandle = new SafeUnicodeStringHandle(password))
{
/// null - if property not defined on key.
/// throws - for any other type of error.
/// </returns>
- private static byte[] GetProperty(SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options)
+ private static byte[]? GetProperty(SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options)
{
Debug.Assert(!ncryptHandle.IsInvalid);
unsafe
/// Retrieve a well-known CNG string property. (Note: .NET Framework compat: this helper likes to return special values rather than throw exceptions for missing
/// or ill-formatted property values. Only use it for well-known properties that are unlikely to be ill-formatted.)
/// </summary>
- internal static string GetPropertyAsString(SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options)
+ internal static string? GetPropertyAsString(SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options)
{
Debug.Assert(!ncryptHandle.IsInvalid);
- byte[] value = GetProperty(ncryptHandle, propertyName, options);
+ byte[]? value = GetProperty(ncryptHandle, propertyName, options);
if (value == null)
return null; // .NET Framework compat: return null if key not present.
if (value.Length == 0)
{
fixed (byte* pValue = &value[0])
{
- string valueAsString = Marshal.PtrToStringUni((IntPtr)pValue);
+ string valueAsString = Marshal.PtrToStringUni((IntPtr)pValue)!;
return valueAsString;
}
}
}
- internal static string GetCurveName(SafeNCryptHandle ncryptHandle)
+ internal static string? GetCurveName(SafeNCryptHandle ncryptHandle)
{
Debug.Assert(!ncryptHandle.IsInvalid);
return GetPropertyAsString(ncryptHandle, KeyPropertyName.ECCCurveName, CngPropertyOptions.None);
{
internal SafeNCryptKeyHandle KeyHandle;
- internal string GetAlgorithmGroup()
+ internal string? GetAlgorithmGroup()
{
return CngKeyLite.GetPropertyAsString(
KeyHandle,
private const string ECDsaIdentifier = "ECDsa";
- private static volatile Dictionary<string, string> s_defaultOidHT;
- private static volatile Dictionary<string, object> s_defaultNameHT;
+ private static volatile Dictionary<string, string>? s_defaultOidHT;
+ private static volatile Dictionary<string, object>? s_defaultNameHT;
private static readonly ConcurrentDictionary<string, Type> appNameHT = new ConcurrentDictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
private static readonly ConcurrentDictionary<string, string> appOidHT = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
}
- public static object CreateFromName(string name, params object[] args)
+ public static object? CreateFromName(string name, params object?[]? args)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
// Check to see if we have an application defined mapping
- appNameHT.TryGetValue(name, out Type retvalType);
+ appNameHT.TryGetValue(name, out Type? retvalType);
// We allow the default table to Types and Strings
// Types get used for types in .Algorithms assembly.
// strings get used for delay-loaded stuff in other assemblies such as .Csp.
- if (retvalType == null && DefaultNameHT.TryGetValue(name, out object retvalObj))
+ if (retvalType == null && DefaultNameHT.TryGetValue(name, out object? retvalObj))
{
retvalType = retvalObj as Type;
cons = candidates.ToArray();
// Bind to matching ctor.
- ConstructorInfo rci = Type.DefaultBinder.BindToMethod(
+ ConstructorInfo? rci = Type.DefaultBinder.BindToMethod(
ConstructorDefault,
cons,
ref args,
null,
null,
null,
- out object state) as ConstructorInfo;
+ out object? state) as ConstructorInfo;
// Check for ctor we don't like (non-existent, delegate or decorated with declarative linktime demand).
if (rci == null || typeof(Delegate).IsAssignableFrom(rci.DeclaringType))
return retval;
}
- public static object CreateFromName(string name)
+ public static object? CreateFromName(string name)
{
return CreateFromName(name, null);
}
}
}
- public static string MapNameToOID(string name)
+ public static string? MapNameToOID(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
- appOidHT.TryGetValue(name, out string oidName);
+ appOidHT.TryGetValue(name, out string? oidName);
if (string.IsNullOrEmpty(oidName) && !DefaultOidHT.TryGetValue(name, out oidName))
{
return encodedOidNums;
}
- private static void EncodeSingleOidNum(uint value, byte[] destination, ref int index)
+ private static void EncodeSingleOidNum(uint value, byte[]? destination, ref int index)
{
// Write directly to destination starting at index, and update index based on how many bytes written.
// If destination is null, just return updated index.
return new DesImplementation();
}
- public static new DES Create(string algName)
+ public static new DES? Create(string algName)
{
- return (DES)CryptoConfig.CreateFromName(algName);
+ return (DES?)CryptoConfig.CreateFromName(algName);
}
public override byte[] Key
return false;
}
- private static bool IsLegalKeySize(byte[] rgbKey)
+ private static bool IsLegalKeySize(byte[]? rgbKey)
{
if (rgbKey != null && rgbKey.Length == 8)
return true;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using System.Text;
namespace System.Security.Cryptography
string name,
int sizeHint = -1)
{
- byte[] ret = XmlKeyHelper.ReadCryptoBinary(ref state, name, sizeHint);
+ byte[]? ret = XmlKeyHelper.ReadCryptoBinary(ref state, name, sizeHint);
if (ret == null)
{
byte[] q = ReadRequiredElement(ref state, nameof(DSAParameters.Q));
byte[] g = ReadRequiredElement(ref state, nameof(DSAParameters.G), p.Length);
byte[] y = ReadRequiredElement(ref state, nameof(DSAParameters.Y), p.Length);
- byte[] j = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(DSAParameters.J));
- byte[] seed = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(DSAParameters.Seed));
+ byte[]? j = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(DSAParameters.J));
+ byte[]? seed = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(DSAParameters.Seed));
int counter = 0;
- byte[] x = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(DSAParameters.X), q.Length);
+ byte[]? x = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(DSAParameters.X), q.Length);
if (seed != null)
{
// StringBuilder to need to grow.
DSAParameters keyParameters = ExportParameters(includePrivateParameters);
+ Debug.Assert(keyParameters.P != null);
StringBuilder builder = new StringBuilder((keyParameters.P.Length << 1) / 3);
builder.Append("<DSAKeyValue>");
XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.P), keyParameters.P, builder);
protected DSA() { }
- public static new DSA Create(string algName)
+ public static new DSA? Create(string algName)
{
- return (DSA)CryptoConfig.CreateFromName(algName);
+ return (DSA?)CryptoConfig.CreateFromName(algName);
}
public static DSA Create(int keySizeInBits)
{
public sealed partial class DSACng : DSA
{
- private SafeNCryptKeyHandle _keyHandle;
+ private SafeNCryptKeyHandle? _keyHandle;
private int _lastKeySize;
private bool _disposed;
_lastKeySize = keySize;
}
- return new DuplicateSafeNCryptKeyHandle(_keyHandle);
+ return new DuplicateSafeNCryptKeyHandle(_keyHandle!);
}
private byte[] ExportKeyBlob(bool includePrivateParameters)
// so you cannot accidently send it along with the public parameters.
public struct DSAParameters
{
- public byte[] P;
- public byte[] Q;
- public byte[] G;
- public byte[] Y;
- public byte[] J;
- public byte[] X;
- public byte[] Seed;
+ public byte[]? P;
+ public byte[]? Q;
+ public byte[]? G;
+ public byte[]? Y;
+ public byte[]? J;
+ public byte[]? X;
+ public byte[]? Seed;
public int Counter;
}
}
{
public class DSASignatureDeformatter : AsymmetricSignatureDeformatter
{
- private DSA _dsaKey;
+ private DSA? _dsaKey;
public DSASignatureDeformatter() { }
{
public class DSASignatureFormatter : AsymmetricSignatureFormatter
{
- private DSA _dsaKey;
+ private DSA? _dsaKey;
public DSASignatureFormatter() { }
{
internal sealed partial class ECCngKey
{
- private SafeNCryptKeyHandle _keyHandle;
+ private SafeNCryptKeyHandle? _keyHandle;
private int _lastKeySize;
- private string _lastAlgorithm;
+ private string? _lastAlgorithm;
private bool _disposed;
private readonly string _algorithmGroup;
private readonly string _disposedName;
internal int KeySize { get; private set; }
- internal string GetCurveName(int callerKeySizeProperty, out string oidValue)
+ internal string? GetCurveName(int callerKeySizeProperty, out string? oidValue)
{
// Ensure key\handle is created
using (SafeNCryptKeyHandle keyHandle = GetDuplicatedKeyHandle(callerKeySizeProperty))
{
- string algorithm = _lastAlgorithm;
+ string? algorithm = _lastAlgorithm;
if (ECCng.IsECNamedCurve(algorithm))
{
if (ECCng.IsECNamedCurve(_lastAlgorithm))
{
// Curve was previously created, so use that
- return new DuplicateSafeNCryptKeyHandle(_keyHandle);
+ return new DuplicateSafeNCryptKeyHandle(_keyHandle!);
}
else
{
KeySize = callerKeySizeProperty;
}
- return new DuplicateSafeNCryptKeyHandle(_keyHandle);
+ return new DuplicateSafeNCryptKeyHandle(_keyHandle!);
}
}
DisposeKey();
}
- string algorithm = null;
+ string algorithm;
int keySize = 0;
if (curve.IsNamed)
_lastKeySize = 0;
}
- internal void SetHandle(SafeNCryptKeyHandle keyHandle, string algorithmName)
+ internal void SetHandle(SafeNCryptKeyHandle keyHandle, string? algorithmName)
{
ThrowIfDisposed();
/// <summary>
/// Coefficient A. Applies only to Explicit curves.
/// </summary>
- public byte[] A;
+ public byte[]? A;
/// <summary>
/// Coefficient B. Applies only to Explicit curves.
/// </summary>
- public byte[] B;
+ public byte[]? B;
/// <summary>
/// Base Point. Applies only to Explicit curves.
/// <summary>
/// Order of the group generated by G = (x,y). Applies only to Explicit curves.
/// </summary>
- public byte[] Order;
+ public byte[]? Order;
/// <summary>
/// Cofactor (optional). Applies only to Explicit curves.
/// </summary>
- public byte[] Cofactor;
+ public byte[]? Cofactor;
/// <summary>
/// Seed of the curve (optional). Applies only to Explicit curves.
/// </summary>
- public byte[] Seed;
+ public byte[]? Seed;
/// <summary>
/// Curve Type.
/// <summary>
/// The binary polynomial. Applies only to Characteristic2 curves.
/// </summary>
- public byte[] Polynomial;
+ public byte[]? Polynomial;
/// <summary>
/// The prime specifying the base field. Applies only to Prime curves.
/// </summary>
- public byte[] Prime;
+ public byte[]? Prime;
private Oid _oid;
/// <summary>
return ECCurve.CreateFromValueAndName(oidValue, null);
}
- private static ECCurve CreateFromValueAndName(string oidValue, string oidFriendlyName)
+ private static ECCurve CreateFromValueAndName(string? oidValue, string? oidFriendlyName)
{
- Oid oid = null;
+ Oid? oid = null;
if (oidValue == null && oidFriendlyName != null)
{
{
if (!hasErrors)
{
- if (Prime == null || Prime.Length != A.Length)
+ if (Prime == null || Prime.Length != A!.Length)
{
hasErrors = true;
}
get { return "ECDiffieHellman"; }
}
- public override string SignatureAlgorithm
+ public override string? SignatureAlgorithm
{
get { return null; }
}
- public static new ECDiffieHellman Create(string algorithm)
+ public static new ECDiffieHellman? Create(string algorithm)
{
if (algorithm == null)
{
public virtual byte[] DeriveKeyFromHash(
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
- byte[] secretPrepend,
- byte[] secretAppend)
+ byte[]? secretPrepend,
+ byte[]? secretAppend)
{
throw DerivedClassMustOverride();
}
public byte[] DeriveKeyFromHmac(
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
- byte[] hmacKey)
+ byte[]? hmacKey)
{
return DeriveKeyFromHmac(otherPartyPublicKey, hashAlgorithm, hmacKey, null, null);
}
public virtual byte[] DeriveKeyFromHmac(
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
- byte[] hmacKey,
- byte[] secretPrepend,
- byte[] secretAppend)
+ byte[]? hmacKey,
+ byte[]? secretPrepend,
+ byte[]? secretAppend)
{
throw DerivedClassMustOverride();
}
using (ECDiffieHellmanCng otherPartyCng = (ECDiffieHellmanCng)Create(otherPartyParameters))
using (SafeNCryptKeyHandle otherPartyHandle = otherPartyCng.GetDuplicatedKeyHandle())
{
- string importedKeyAlgorithmGroup =
+ string? importedKeyAlgorithmGroup =
CngKeyLite.GetPropertyAsString(
otherPartyHandle,
CngKeyLite.KeyPropertyName.AlgorithmGroup,
{
private readonly ECCngKey _key = new ECCngKey(BCryptNative.AlgorithmName.ECDH, nameof(ECDiffieHellman));
- private string GetCurveName(out string oidValue) => _key.GetCurveName(KeySize, out oidValue);
+ private string? GetCurveName(out string? oidValue) => _key.GetCurveName(KeySize, out oidValue);
public override void GenerateKey(ECCurve curve)
{
{
get
{
- string curveName = GetCurveName(out _);
+ string? curveName = GetCurveName(out _);
return new ECDiffieHellmanCngPublicKey(
curveName == null
public sealed partial class ECDiffieHellmanCngPublicKey : ECDiffieHellmanPublicKey
{
private byte[] _keyBlob;
- internal string _curveName;
+ internal string? _curveName;
protected override void Dispose(bool disposing)
{
- _keyBlob = null;
+ _keyBlob = null!;
base.Dispose(disposing);
}
throw new PlatformNotSupportedException();
}
- internal ECDiffieHellmanCngPublicKey(byte[] keyBlob, string curveName) : base(keyBlob)
+ internal ECDiffieHellmanCngPublicKey(byte[] keyBlob, string? curveName) : base(keyBlob)
{
Debug.Assert(keyBlob != null);
throw new ArgumentNullException(nameof(keyBlob));
}
- _keyBlob = keyBlob.Clone() as byte[];
+ _keyBlob = (byte[])keyBlob.Clone();
}
public void Dispose()
public virtual byte[] ToByteArray()
{
- return _keyBlob.Clone() as byte[];
+ return (byte[])_keyBlob.Clone();
}
// This method must be implemented by derived classes. In order to conform to the contract, it cannot be abstract.
protected ECDsa() { }
- public static new ECDsa Create(string algorithm)
+ public static new ECDsa? Create(string algorithm)
{
if (algorithm == null)
{
public abstract byte[] SignHash(byte[] hash);
public abstract bool VerifyHash(byte[] hash, byte[] signature);
- public override string KeyExchangeAlgorithm => null;
+ public override string? KeyExchangeAlgorithm => null;
public override string SignatureAlgorithm => "ECDsa";
protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
private readonly ECCngKey _key = new ECCngKey(AlgorithmName.ECDsa, nameof(ECDsa));
- private string GetCurveName(out string oidValue) => _key.GetCurveName(KeySize, out oidValue);
+ private string? GetCurveName(out string? oidValue) => _key.GetCurveName(KeySize, out oidValue);
public override void GenerateKey(ECCurve curve)
{
/// <summary>
/// Private Key. Not always present.
/// </summary>
- public byte[] D;
+ public byte[]? D;
/// <summary>
/// The Curve.
if (Curve.IsExplicit)
{
// Explicit curves require D length to match Curve.Order
- hasErrors = (D != null && (D.Length != Curve.Order.Length));
+ hasErrors = (D != null && (D.Length != Curve.Order!.Length));
}
else if (Curve.IsNamed)
{
// Named curves require D length to match Q.X and Q.Y
- hasErrors = (D != null && (D.Length != Q.X.Length));
+ hasErrors = (D != null && (D.Length != Q.X!.Length));
}
}
/// </summary>
public struct ECPoint
{
- public byte[] X;
- public byte[] Y;
+ public byte[]? X;
+ public byte[]? Y;
}
}
/// <param name="ikm">The input keying material.</param>
/// <param name="salt">The optional salt value (a non-secret random value). If not provided it defaults to a byte array of <see cref="HashLength"/> zeros.</param>
/// <returns>The pseudo random key (prk).</returns>
- public static byte[] Extract(HashAlgorithmName hashAlgorithmName, byte[] ikm, byte[] salt = null)
+ public static byte[] Extract(HashAlgorithmName hashAlgorithmName, byte[] ikm, byte[]? salt = null)
{
if (ikm == null)
throw new ArgumentNullException(nameof(ikm));
/// <param name="outputLength">The length of the output keying material.</param>
/// <param name="info">The optional context and application specific information.</param>
/// <returns>The output keying material.</returns>
- public static byte[] Expand(HashAlgorithmName hashAlgorithmName, byte[] prk, int outputLength, byte[] info = null)
+ public static byte[] Expand(HashAlgorithmName hashAlgorithmName, byte[] prk, int outputLength, byte[]? info = null)
{
if (prk == null)
throw new ArgumentNullException(nameof(prk));
/// <param name="salt">The optional salt value (a non-secret random value). If not provided it defaults to a byte array of <see cref="HashLength"/> zeros.</param>
/// <param name="info">The optional context and application specific information.</param>
/// <returns>The output keying material.</returns>
- public static byte[] DeriveKey(HashAlgorithmName hashAlgorithmName, byte[] ikm, int outputLength, byte[] salt = null, byte[] info = null)
+ public static byte[] DeriveKey(HashAlgorithmName hashAlgorithmName, byte[] ikm, int outputLength, byte[]? salt = null, byte[]? info = null)
{
if (ikm == null)
throw new ArgumentNullException(nameof(ikm));
this.HashName = HashAlgorithmNames.MD5;
_hMacCommon = new HMACCommon(HashAlgorithmNames.MD5, key, BlockSize);
- base.Key = _hMacCommon.ActualKey;
+ base.Key = _hMacCommon.ActualKey!;
// this not really needed as it'll initialize BlockSizeValue with same value it has which is 64.
// we just want to be explicit in all HMAC extended classes
BlockSizeValue = BlockSize;
}
_hMacCommon.ChangeKey(value);
- base.Key = _hMacCommon.ActualKey;
+ base.Key = _hMacCommon.ActualKey!;
}
}
HMACCommon hMacCommon = _hMacCommon;
if (hMacCommon != null)
{
- _hMacCommon = null;
+ _hMacCommon = null!;
hMacCommon.Dispose(disposing);
}
}
this.HashName = HashAlgorithmNames.SHA1;
_hMacCommon = new HMACCommon(HashAlgorithmNames.SHA1, key, BlockSize);
- base.Key = _hMacCommon.ActualKey;
+ base.Key = _hMacCommon.ActualKey!;
// this not really needed as it'll initialize BlockSizeValue with same value it has which is 64.
// we just want to be explicit in all HMAC extended classes
BlockSizeValue = BlockSize;
}
_hMacCommon.ChangeKey(value);
- base.Key = _hMacCommon.ActualKey;
+ base.Key = _hMacCommon.ActualKey!;
}
}
HMACCommon hMacCommon = _hMacCommon;
if (hMacCommon != null)
{
- _hMacCommon = null;
+ _hMacCommon = null!;
hMacCommon.Dispose(disposing);
}
}
this.HashName = HashAlgorithmNames.SHA256;
_hMacCommon = new HMACCommon(HashAlgorithmNames.SHA256, key, BlockSize);
- base.Key = _hMacCommon.ActualKey;
+ base.Key = _hMacCommon.ActualKey!;
// this not really needed as it'll initialize BlockSizeValue with same value it has which is 64.
// we just want to be explicit in all HMAC extended classes
BlockSizeValue = BlockSize;
}
_hMacCommon.ChangeKey(value);
- base.Key = _hMacCommon.ActualKey;
+ base.Key = _hMacCommon.ActualKey!;
}
}
HMACCommon hMacCommon = _hMacCommon;
if (hMacCommon != null)
{
- _hMacCommon = null;
+ _hMacCommon = null!;
hMacCommon.Dispose(disposing);
}
}
this.HashName = HashAlgorithmNames.SHA384;
_hMacCommon = new HMACCommon(HashAlgorithmNames.SHA384, key, BlockSize);
- base.Key = _hMacCommon.ActualKey;
+ base.Key = _hMacCommon.ActualKey!;
// change the default value of BlockSizeValue to 128 instead of 64
BlockSizeValue = BlockSize;
HashSizeValue = _hMacCommon.HashSizeInBits;
}
_hMacCommon.ChangeKey(value);
- base.Key = _hMacCommon.ActualKey;
+ base.Key = _hMacCommon.ActualKey!;
}
}
HMACCommon hMacCommon = _hMacCommon;
if (hMacCommon != null)
{
- _hMacCommon = null;
+ _hMacCommon = null!;
hMacCommon.Dispose(disposing);
}
}
this.HashName = HashAlgorithmNames.SHA512;
_hMacCommon = new HMACCommon(HashAlgorithmNames.SHA512, key, BlockSize);
- base.Key = _hMacCommon.ActualKey;
+ base.Key = _hMacCommon.ActualKey!;
// change the default value of BlockSizeValue to 128 instead of 64
BlockSizeValue = BlockSize;
HashSizeValue = _hMacCommon.HashSizeInBits;
}
_hMacCommon.ChangeKey(value);
- base.Key = _hMacCommon.ActualKey;
+ base.Key = _hMacCommon.ActualKey!;
}
}
HMACCommon hMacCommon = _hMacCommon;
if (hMacCommon != null)
{
- _hMacCommon = null;
+ _hMacCommon = null!;
hMacCommon.Dispose(disposing);
}
}
public sealed class IncrementalHash : IDisposable
{
private readonly HashAlgorithmName _algorithmName;
- private HashProvider _hash;
- private HMACCommon _hmac;
+ private HashProvider? _hash;
+ private HMACCommon? _hmac;
private bool _disposed;
private IncrementalHash(HashAlgorithmName name, HashProvider hash)
}
else
{
- _hmac.AppendHashData(data);
+ _hmac!.AppendHashData(data);
}
}
Debug.Assert((_hash != null) ^ (_hmac != null));
return _hash != null ?
_hash.FinalizeHashAndReset() :
- _hmac.FinalizeHashAndReset();
+ _hmac!.FinalizeHashAndReset();
}
public bool TryGetHashAndReset(Span<byte> destination, out int bytesWritten)
Debug.Assert((_hash != null) ^ (_hmac != null));
return _hash != null ?
_hash.TryFinalizeHashAndReset(destination, out bytesWritten) :
- _hmac.TryFinalizeHashAndReset(destination, out bytesWritten);
+ _hmac!.TryFinalizeHashAndReset(destination, out bytesWritten);
}
/// <summary>
public static new MD5 Create() => new Implementation();
- public static new MD5 Create(string algName) => (MD5)CryptoConfig.CreateFromName(algName);
+ public static new MD5? Create(string algName) => (MD5?)CryptoConfig.CreateFromName(algName);
private sealed class Implementation : MD5
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using Internal.Cryptography;
namespace System.Security.Cryptography
public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn)
{
- using (HashAlgorithm hasher = CryptoConfig.CreateFromName(_hashNameValue) as HashAlgorithm)
+ using (HashAlgorithm? hasher = CryptoConfig.CreateFromName(_hashNameValue) as HashAlgorithm)
{
if (hasher is null)
{
Helpers.ConvertIntToByteArray(counter++, rgbCounter);
hasher.TransformBlock(rgbSeed, 0, rgbSeed.Length, rgbSeed, 0);
hasher.TransformFinalBlock(rgbCounter, 0, 4);
+ Debug.Assert(hasher.Hash != null);
byte[] hash = hasher.Hash;
hasher.Initialize();
Buffer.BlockCopy(hash, 0, rgbT, ib, Math.Min(rgbT.Length - ib, hash.Length));
return new RC2Implementation();
}
- public static new RC2 Create(string AlgName)
+ public static new RC2? Create(string AlgName)
{
- return (RC2)CryptoConfig.CreateFromName(AlgName);
+ return (RC2?)CryptoConfig.CreateFromName(AlgName);
}
string name,
int sizeHint = -1)
{
- byte[] ret = XmlKeyHelper.ReadCryptoBinary(ref state, name, sizeHint);
+ byte[]? ret = XmlKeyHelper.ReadCryptoBinary(ref state, name, sizeHint);
if (ret == null)
{
// .NET Framework doesn't report any element other than Modulus/Exponent as required,
// it just lets import fail if they're imbalanced.
- byte[] p = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(RSAParameters.P), halfN);
- byte[] q = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(RSAParameters.Q), halfN);
- byte[] dp = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(RSAParameters.DP), halfN);
- byte[] dq = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(RSAParameters.DQ), halfN);
- byte[] qInv = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(RSAParameters.InverseQ), halfN);
- byte[] d = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(RSAParameters.D), n.Length);
+ byte[]? p = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(RSAParameters.P), halfN);
+ byte[]? q = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(RSAParameters.Q), halfN);
+ byte[]? dp = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(RSAParameters.DP), halfN);
+ byte[]? dq = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(RSAParameters.DQ), halfN);
+ byte[]? qInv = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(RSAParameters.InverseQ), halfN);
+ byte[]? d = XmlKeyHelper.ReadCryptoBinary(ref state, nameof(RSAParameters.D), n.Length);
RSAParameters keyParameters = new RSAParameters
{
{
public abstract partial class RSA : AsymmetricAlgorithm
{
- public static new RSA Create(string algName)
+ public static new RSA? Create(string algName)
{
- return (RSA)CryptoConfig.CreateFromName(algName);
+ return (RSA?)CryptoConfig.CreateFromName(algName);
}
public static RSA Create(int keySizeInBits)
{
public sealed partial class RSACng : RSA
{
- private SafeNCryptKeyHandle _keyHandle;
+ private SafeNCryptKeyHandle? _keyHandle;
private int _lastKeySize;
private bool _disposed;
_lastKeySize = keySize;
}
- return new DuplicateSafeNCryptKeyHandle(_keyHandle);
+ return new DuplicateSafeNCryptKeyHandle(_keyHandle!);
}
private byte[] ExportKeyBlob(bool includePrivateParameters)
if (disposing)
{
_keyHandle?.Dispose();
- _keyHandle = null;
+ _keyHandle = null!;
_disposed = true;
}
return (((h1 << 5) + h1) ^ h2);
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
return Equals(obj as RSAEncryptionPadding);
}
- public bool Equals(RSAEncryptionPadding other)
+ public bool Equals(RSAEncryptionPadding? other)
{
return !object.ReferenceEquals(other, null)
&& _mode == other._mode
&& _oaepHashAlgorithm == other._oaepHashAlgorithm;
}
- public static bool operator ==(RSAEncryptionPadding left, RSAEncryptionPadding right)
+ public static bool operator ==(RSAEncryptionPadding? left, RSAEncryptionPadding? right)
{
if (object.ReferenceEquals(left, null))
{
return left.Equals(right);
}
- public static bool operator !=(RSAEncryptionPadding left, RSAEncryptionPadding right)
+ public static bool operator !=(RSAEncryptionPadding? left, RSAEncryptionPadding? right)
{
return !(left == right);
}
{
public class RSAOAEPKeyExchangeDeformatter : AsymmetricKeyExchangeDeformatter
{
- private RSA _rsaKey;
+ private RSA? _rsaKey;
public RSAOAEPKeyExchangeDeformatter() { }
public RSAOAEPKeyExchangeDeformatter(AsymmetricAlgorithm key)
_rsaKey = (RSA)key;
}
- public override string Parameters
+ public override string? Parameters
{
get { return null; }
set { }
{
public class RSAOAEPKeyExchangeFormatter : AsymmetricKeyExchangeFormatter
{
- private byte[] ParameterValue;
- private RSA _rsaKey;
- private RandomNumberGenerator RngValue;
+ private byte[]? ParameterValue;
+ private RSA? _rsaKey;
+ private RandomNumberGenerator? RngValue;
public RSAOAEPKeyExchangeFormatter() { }
public RSAOAEPKeyExchangeFormatter(AsymmetricAlgorithm key)
_rsaKey = (RSA)key;
}
- public byte[] Parameter
+ public byte[]? Parameter
{
get
{
}
}
- public override string Parameters
+ public override string? Parameters
{
get { return null; }
}
- public RandomNumberGenerator Rng
+ public RandomNumberGenerator? Rng
{
get { return RngValue; }
set { RngValue = value; }
_rsaKey = (RSA)key;
}
- public override byte[] CreateKeyExchange(byte[] rgbData, Type symAlgType)
+ public override byte[] CreateKeyExchange(byte[] rgbData, Type? symAlgType)
{
return CreateKeyExchange(rgbData);
}
{
public class RSAPKCS1KeyExchangeDeformatter : AsymmetricKeyExchangeDeformatter
{
- private RSA _rsaKey;
- private RandomNumberGenerator RngValue;
+ private RSA? _rsaKey;
+ private RandomNumberGenerator? RngValue;
public RSAPKCS1KeyExchangeDeformatter() { }
_rsaKey = (RSA)key;
}
- public RandomNumberGenerator RNG
+ public RandomNumberGenerator? RNG
{
get { return RngValue; }
set { RngValue = value; }
}
- public override string Parameters
+ public override string? Parameters
{
get { return null; }
set { }
{
public class RSAPKCS1KeyExchangeFormatter : AsymmetricKeyExchangeFormatter
{
- private RSA _rsaKey;
- private RandomNumberGenerator RngValue;
+ private RSA? _rsaKey;
+ private RandomNumberGenerator? RngValue;
public RSAPKCS1KeyExchangeFormatter() { }
}
}
- public RandomNumberGenerator Rng
+ public RandomNumberGenerator? Rng
{
get { return RngValue; }
set { RngValue = value; }
_rsaKey = (RSA)key;
}
- public override byte[] CreateKeyExchange(byte[] rgbData, Type symAlgType)
+ public override byte[] CreateKeyExchange(byte[] rgbData, Type? symAlgType)
{
return CreateKeyExchange(rgbData);
}
{
public class RSAPKCS1SignatureDeformatter : AsymmetricSignatureDeformatter
{
- private RSA _rsaKey;
- private string _algName;
+ private RSA? _rsaKey;
+ private string? _algName;
public RSAPKCS1SignatureDeformatter() { }
public RSAPKCS1SignatureDeformatter(AsymmetricAlgorithm key)
{
public class RSAPKCS1SignatureFormatter : AsymmetricSignatureFormatter
{
- private RSA _rsaKey;
- private string _algName;
+ private RSA? _rsaKey;
+ private string? _algName;
public RSAPKCS1SignatureFormatter() { }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct RSAParameters
{
- public byte[] D;
- public byte[] DP;
- public byte[] DQ;
- public byte[] Exponent;
- public byte[] InverseQ;
- public byte[] Modulus;
- public byte[] P;
- public byte[] Q;
+ public byte[]? D;
+ public byte[]? DP;
+ public byte[]? DQ;
+ public byte[]? Exponent;
+ public byte[]? InverseQ;
+ public byte[]? Modulus;
+ public byte[]? P;
+ public byte[]? Q;
}
}
return _mode.GetHashCode();
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
return Equals(obj as RSASignaturePadding);
}
- public bool Equals(RSASignaturePadding other)
+ public bool Equals(RSASignaturePadding? other)
{
return !object.ReferenceEquals(other, null) && _mode == other._mode;
}
- public static bool operator ==(RSASignaturePadding left, RSASignaturePadding right)
+ public static bool operator ==(RSASignaturePadding? left, RSASignaturePadding? right)
{
if (object.ReferenceEquals(left, null))
{
return left.Equals(right);
}
- public static bool operator !=(RSASignaturePadding left, RSASignaturePadding right)
+ public static bool operator !=(RSASignaturePadding? left, RSASignaturePadding? right)
{
return !(left == right);
}
return new RandomNumberGeneratorImplementation();
}
- public static RandomNumberGenerator Create(string rngName)
+ public static RandomNumberGenerator? Create(string rngName)
{
- return (RandomNumberGenerator)CryptoConfig.CreateFromName(rngName);
+ return (RandomNumberGenerator?)CryptoConfig.CreateFromName(rngName);
}
public void Dispose()
private HMAC _hmac;
private readonly int _blockSize;
- private byte[] _buffer;
+ private byte[] _buffer = null!; // Initialized in helper
private uint _block;
private int _startIndex;
private int _endIndex;
if (_hmac != null)
{
_hmac.Dispose();
- _hmac = null;
+ _hmac = null!;
}
if (_buffer != null)
return new RijndaelImplementation();
}
- public static new Rijndael Create(string algName)
+ public static new Rijndael? Create(string algName)
{
- return (Rijndael)CryptoConfig.CreateFromName(algName);
+ return (Rijndael?)CryptoConfig.CreateFromName(algName);
}
protected Rijndael()
// LegalBlockSizes not forwarded because base has correct information
public override KeySizes[] LegalKeySizes => _impl.LegalKeySizes;
public override ICryptoTransform CreateEncryptor() => _impl.CreateEncryptor();
- public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) => _impl.CreateEncryptor(rgbKey, rgbIV);
+ public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) => _impl.CreateEncryptor(rgbKey, rgbIV);
public override ICryptoTransform CreateDecryptor() => _impl.CreateDecryptor();
- public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) => _impl.CreateDecryptor(rgbKey, rgbIV);
+ public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) => _impl.CreateDecryptor(rgbKey, rgbIV);
public override void GenerateIV() => _impl.GenerateIV();
public override void GenerateKey() => _impl.GenerateKey();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "This is the implementaton of SHA1")]
public static new SHA1 Create() => new Implementation();
- public static new SHA1 Create(string hashName) => (SHA1)CryptoConfig.CreateFromName(hashName);
+ public static new SHA1? Create(string hashName) => (SHA1?)CryptoConfig.CreateFromName(hashName);
private sealed class Implementation : SHA1
{
public static new SHA256 Create() => new Implementation();
- public static new SHA256 Create(string hashName) => (SHA256)CryptoConfig.CreateFromName(hashName);
+ public static new SHA256? Create(string hashName) => (SHA256?)CryptoConfig.CreateFromName(hashName);
private sealed class Implementation : SHA256
{
public static new SHA384 Create() => new Implementation();
- public static new SHA384 Create(string hashName) => (SHA384)CryptoConfig.CreateFromName(hashName);
+ public static new SHA384? Create(string hashName) => (SHA384?)CryptoConfig.CreateFromName(hashName);
private sealed class Implementation : SHA384
{
public static new SHA512 Create() => new Implementation();
- public static new SHA512 Create(string hashName) => (SHA512)CryptoConfig.CreateFromName(hashName);
+ public static new SHA512? Create(string hashName) => (SHA512?)CryptoConfig.CreateFromName(hashName);
private sealed class Implementation : SHA512
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
+
namespace System.Security.Cryptography
{
public class SignatureDescription
{
- public string KeyAlgorithm { get; set; }
- public string DigestAlgorithm { get; set; }
- public string FormatterAlgorithm { get; set; }
- public string DeformatterAlgorithm { get; set; }
+ public string? KeyAlgorithm { get; set; }
+ public string? DigestAlgorithm { get; set; }
+ public string? FormatterAlgorithm { get; set; }
+ public string? DeformatterAlgorithm { get; set; }
public SignatureDescription()
{
public virtual AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key)
{
- AsymmetricSignatureDeformatter item = (AsymmetricSignatureDeformatter)CryptoConfig.CreateFromName(DeformatterAlgorithm);
- item.SetKey(key);
+ AsymmetricSignatureDeformatter? item = (AsymmetricSignatureDeformatter?)CryptoConfig.CreateFromName(DeformatterAlgorithm!);
+ item!.SetKey(key);
return item;
}
public virtual AsymmetricSignatureFormatter CreateFormatter(AsymmetricAlgorithm key)
{
- AsymmetricSignatureFormatter item = (AsymmetricSignatureFormatter)CryptoConfig.CreateFromName(FormatterAlgorithm);
- item.SetKey(key);
+ AsymmetricSignatureFormatter? item = (AsymmetricSignatureFormatter?)CryptoConfig.CreateFromName(FormatterAlgorithm!);
+ item!.SetKey(key);
return item;
}
- public virtual HashAlgorithm CreateDigest()
+ public virtual HashAlgorithm? CreateDigest()
{
- return (HashAlgorithm)CryptoConfig.CreateFromName(DigestAlgorithm);
+ return (HashAlgorithm?)CryptoConfig.CreateFromName(DigestAlgorithm!);
}
}
-}
\ No newline at end of file
+}
return new TripleDesImplementation();
}
- public static new TripleDES Create(string str)
+ public static new TripleDES? Create(string str)
{
- return (TripleDES)CryptoConfig.CreateFromName(str);
+ return (TripleDES?)CryptoConfig.CreateFromName(str);
}
public override byte[] Key
return state.HasElement(name);
}
- internal static byte[] ReadCryptoBinary(ref ParseState state, string name, int sizeHint = -1)
+ internal static byte[]? ReadCryptoBinary(ref ParseState state, string name, int sizeHint = -1)
{
- string value = state.GetValue(name);
+ string? value = state.GetValue(name);
if (value == null)
{
internal struct ParseState
{
- private IEnumerable _enumerable;
- private IEnumerator _enumerator;
+ private IEnumerable? _enumerable;
+ private IEnumerator? _enumerator;
private int _index;
internal static ParseState ParseDocument(string xmlString)
{
- object rootElement = Functions.ParseDocument(xmlString);
+ object? rootElement = Functions.ParseDocument(xmlString);
return new ParseState
{
internal bool HasElement(string localName)
{
- string value = GetValue(localName);
+ string? value = GetValue(localName);
bool ret = value != null;
return ret;
}
- internal string GetValue(string localName)
+ internal string? GetValue(string localName)
{
if (_enumerable == null)
{
while (idx != origIdx)
{
- string curName = Functions.GetLocalName(_enumerator.Current);
+ string? curName = Functions.GetLocalName(_enumerator.Current);
if (localName == curName)
{
private static class Functions
{
- private static readonly Type s_xDocument = Type.GetType("System.Xml.Linq.XDocument, System.Private.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51");
+ private static readonly Type s_xDocument = Type.GetType("System.Xml.Linq.XDocument, System.Private.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")!;
private static readonly Func<string, object> s_xDocumentCreate =
(Func<string, object>)s_xDocument.GetMethod(
"Parse",
BindingFlags.Static | BindingFlags.Public,
null,
new[] { typeof(string) },
- null).CreateDelegate(typeof(Func<string, object>));
- private static readonly PropertyInfo s_docRootProperty = s_xDocument.GetProperty("Root");
+ null)!.CreateDelegate(typeof(Func<string, object>));
+ private static readonly PropertyInfo s_docRootProperty = s_xDocument.GetProperty("Root")!;
private static readonly MethodInfo s_getElementsMethod = s_docRootProperty.PropertyType.GetMethod(
"Elements",
BindingFlags.Instance | BindingFlags.Public,
null,
Array.Empty<Type>(),
- null);
- private static readonly PropertyInfo s_elementNameProperty = s_docRootProperty.PropertyType.GetProperty("Name");
- private static readonly PropertyInfo s_nameNameProperty = s_elementNameProperty.PropertyType.GetProperty("LocalName");
- private static readonly PropertyInfo s_elementValueProperty = s_docRootProperty.PropertyType.GetProperty("Value");
+ null)!;
+ private static readonly PropertyInfo s_elementNameProperty = s_docRootProperty.PropertyType.GetProperty("Name")!;
+ private static readonly PropertyInfo s_nameNameProperty = s_elementNameProperty.PropertyType.GetProperty("LocalName")!;
+ private static readonly PropertyInfo s_elementValueProperty = s_docRootProperty.PropertyType.GetProperty("Value")!;
- internal static object ParseDocument(string xmlString) =>
+ internal static object? ParseDocument(string xmlString) =>
s_docRootProperty.GetValue(s_xDocumentCreate(xmlString));
- internal static IEnumerable GetElements(object element) =>
- (IEnumerable)s_getElementsMethod.Invoke(element, Array.Empty<object>());
+ internal static IEnumerable? GetElements(object? element) =>
+ (IEnumerable?)s_getElementsMethod.Invoke(element, Array.Empty<object>());
- internal static string GetLocalName(object element) =>
- (string)s_nameNameProperty.GetValue(s_elementNameProperty.GetValue(element));
+ internal static string? GetLocalName(object? element) =>
+ (string?)s_nameNameProperty.GetValue(s_elementNameProperty.GetValue(element));
- internal static string GetValue(object element) =>
- (string)s_elementValueProperty.GetValue(element);
+ internal static string? GetValue(object? element) =>
+ (string?)s_elementValueProperty.GetValue(element);
}
}
}