internal static extern bool CertGetCertificateContextProperty(
SafeCertContextHandle pCertContext,
CertContextPropId dwPropId,
- [Out] byte[] pvData,
+ [Out] byte[]? pvData,
[In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
{
internal static partial class Crypt32
{
- internal static unsafe bool CryptEncodeObject(MsgEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, void* pvStructInfo, byte[] pbEncoded, ref int pcbEncoded)
+ internal static unsafe bool CryptEncodeObject(MsgEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, void* pvStructInfo, byte[]? pbEncoded, ref int pcbEncoded)
{
return CryptEncodeObject(dwCertEncodingType, (IntPtr)lpszStructType, pvStructInfo, pbEncoded, ref pcbEncoded);
}
MsgEncodingType dwCertEncodingType,
IntPtr lpszStructType,
void* pvStructInfo,
- [Out] byte[] pbEncoded,
+ [Out] byte[]? pbEncoded,
[In, Out] ref int pcbEncoded);
}
}
SafeCryptMsgHandle hCryptMsg,
CryptMsgParamType dwParamType,
int dwIndex,
- [Out] byte[] pvData,
+ [Out] byte[]? pvData,
[In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
// 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.Security.Cryptography.Pkcs;
public sealed partial class CryptographicAttributeObject
{
public CryptographicAttributeObject(System.Security.Cryptography.Oid oid) { }
- public CryptographicAttributeObject(System.Security.Cryptography.Oid oid, System.Security.Cryptography.AsnEncodedDataCollection values) { }
+ public CryptographicAttributeObject(System.Security.Cryptography.Oid oid, System.Security.Cryptography.AsnEncodedDataCollection? values) { }
public System.Security.Cryptography.Oid Oid { get { throw null; } }
public System.Security.Cryptography.AsnEncodedDataCollection Values { get { throw null; } }
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public CmsSigner(System.Security.Cryptography.CspParameters parameters) { }
public CmsSigner(System.Security.Cryptography.Pkcs.SubjectIdentifierType signerIdentifierType) { }
- public CmsSigner(System.Security.Cryptography.Pkcs.SubjectIdentifierType signerIdentifierType, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
- public CmsSigner(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { }
- public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { throw null; } set { } }
+ public CmsSigner(System.Security.Cryptography.Pkcs.SubjectIdentifierType signerIdentifierType, System.Security.Cryptography.X509Certificates.X509Certificate2? certificate) { }
+ public CmsSigner(System.Security.Cryptography.X509Certificates.X509Certificate2? certificate) { }
+ public System.Security.Cryptography.X509Certificates.X509Certificate2? Certificate { get { throw null; } set { } }
public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { get { throw null; } }
public System.Security.Cryptography.Oid DigestAlgorithm { get { throw null; } set { } }
public System.Security.Cryptography.X509Certificates.X509IncludeOption IncludeOption { get { throw null; } set { } }
public override byte[] EncryptedKey { get { throw null; } }
public override System.Security.Cryptography.Pkcs.AlgorithmIdentifier KeyEncryptionAlgorithm { get { throw null; } }
public System.Security.Cryptography.Pkcs.SubjectIdentifierOrKey OriginatorIdentifierOrKey { get { throw null; } }
- public System.Security.Cryptography.CryptographicAttributeObject OtherKeyAttribute { get { throw null; } }
+ public System.Security.Cryptography.CryptographicAttributeObject? OtherKeyAttribute { get { throw null; } }
public override System.Security.Cryptography.Pkcs.SubjectIdentifier RecipientIdentifier { get { throw null; } }
public override int Version { get { throw null; } }
}
public Pkcs9AttributeObject(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
public Pkcs9AttributeObject(System.Security.Cryptography.Oid oid, byte[] encodedData) { }
public Pkcs9AttributeObject(string oid, byte[] encodedData) { }
- public new System.Security.Cryptography.Oid Oid { get { throw null; } }
+ public new System.Security.Cryptography.Oid? Oid { get { throw null; } }
public override void CopyFrom(System.Security.Cryptography.AsnEncodedData asnEncodedData) { }
}
public sealed partial class Pkcs9ContentType : System.Security.Cryptography.Pkcs.Pkcs9AttributeObject
public sealed partial class SignerInfo
{
internal SignerInfo() { }
- public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get { throw null; } }
+ public System.Security.Cryptography.X509Certificates.X509Certificate2? Certificate { get { throw null; } }
public System.Security.Cryptography.Pkcs.SignerInfoCollection CounterSignerInfos { get { throw null; } }
public System.Security.Cryptography.Oid DigestAlgorithm { get { throw null; } }
public System.Security.Cryptography.CryptographicAttributeObjectCollection SignedAttributes { get { throw null; } }
{
internal SubjectIdentifier() { }
public System.Security.Cryptography.Pkcs.SubjectIdentifierType Type { get { throw null; } }
- public object Value { get { throw null; } }
+ public object? Value { get { throw null; } }
}
public sealed partial class SubjectIdentifierOrKey
{
<TargetFrameworks>netcoreapp3.0;netstandard2.1;net461;$(NetFrameworkCurrent);$(NetCoreAppCurrent)</TargetFrameworks>
<ExcludeCurrentNetCoreAppFromPackage>true</ExcludeCurrentNetCoreAppFromPackage>
<ExcludeCurrentFullFrameworkFromPackage>true</ExcludeCurrentFullFrameworkFromPackage>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="System.Security.Cryptography.Pkcs.cs" />
/// to a valid Exception object. Do not throw the exception as EnvelopedCms will want to continue decryption attempts against other recipients. Only if all the recipients fail to
/// decrypt will then EnvelopedCms throw the exception from the last failed attempt.
/// </summary>
- public abstract ContentInfo TryDecrypt(
+ public abstract ContentInfo? TryDecrypt(
RecipientInfo recipientInfo,
- X509Certificate2 cert,
- AsymmetricAlgorithm privateKey,
+ X509Certificate2? cert,
+ AsymmetricAlgorithm? privateKey,
X509Certificate2Collection originatorCerts,
X509Certificate2Collection extraStore,
- out Exception exception);
+ out Exception? exception);
public abstract void Dispose();
}
public abstract DateTime Date { get; }
public abstract SubjectIdentifierOrKey OriginatorIdentifierOrKey { get; }
- public abstract CryptographicAttributeObject OtherKeyAttribute { get; }
+ public abstract CryptographicAttributeObject? OtherKeyAttribute { get; }
}
}
break;
case Oids.RsaOaep when !asn.HasNullEquivalentParameters():
keyLength = 0;
+ Debug.Assert(asn.Parameters != null);
parameters = asn.Parameters.Value.ToArray();
break;
default:
_envelopedData = envelopedDataAsn;
}
- public override unsafe ContentInfo TryDecrypt(
+ public override unsafe ContentInfo? TryDecrypt(
RecipientInfo recipientInfo,
- X509Certificate2 cert,
- AsymmetricAlgorithm privateKey,
+ X509Certificate2? cert,
+ AsymmetricAlgorithm? privateKey,
X509Certificate2Collection originatorCerts,
X509Certificate2Collection extraStore,
- out Exception exception)
+ out Exception? exception)
{
// When encryptedContent is null Windows seems to decrypt the CEK first,
// then return a 0 byte answer.
if (recipientInfo.Pal is ManagedKeyTransPal ktri)
{
- RSA key = privateKey as RSA;
+ RSA? key = privateKey as RSA;
if (privateKey != null && key == null)
{
return null;
}
- byte[] cek = ktri.DecryptCek(cert, key, out exception);
+ byte[]? cek = ktri.DecryptCek(cert, key, out exception);
// Pin CEK to prevent it from getting copied during heap compaction.
fixed (byte* pinnedCek = cek)
{
}
return TryDecryptCore(
- cek,
+ cek!,
_envelopedData.EncryptedContentInfo.ContentType,
_envelopedData.EncryptedContentInfo.EncryptedContent,
_envelopedData.EncryptedContentInfo.ContentEncryptionAlgorithm,
}
}
- public static unsafe ContentInfo TryDecryptCore(
+ public static unsafe ContentInfo? TryDecryptCore(
byte[] cek,
string contentType,
ReadOnlyMemory<byte>? content,
AlgorithmIdentifierAsn contentEncryptionAlgorithm,
- out Exception exception)
+ out Exception? exception)
{
if (content == null)
{
Array.Empty<byte>());
}
- byte[] decrypted = DecryptContent(content.Value, cek, contentEncryptionAlgorithm, out exception);
+ byte[]? decrypted = DecryptContent(content.Value, cek, contentEncryptionAlgorithm, out exception);
if (exception != null)
{
// existing CMS that have the incorrect wrapping, we attempt to remove it.
if (contentType == Oids.Pkcs7Data)
{
- byte[] tmp = null;
+ byte[]? tmp = null;
try
{
}
else
{
- tmp = CryptoPool.Rent(decrypted.Length);
+ tmp = CryptoPool.Rent(decrypted!.Length);
if (reader.TryCopyOctetStringBytes(tmp, out int written))
{
exception = null;
return new ContentInfo(
new Oid(contentType),
- decrypted);
+ decrypted!);
}
private static byte[] GetAsnSequenceWithContentNoValidation(ReadOnlySpan<byte> content)
}
}
- private static byte[] DecryptContent(
+ private static byte[]? DecryptContent(
ReadOnlyMemory<byte> encryptedContent,
byte[] cek,
AlgorithmIdentifierAsn contentEncryptionAlgorithm,
- out Exception exception)
+ out Exception? exception)
{
exception = null;
int encryptedContentLength = encryptedContent.Length;
- byte[] encryptedContentArray = CryptoPool.Rent(encryptedContentLength);
+ byte[]? encryptedContentArray = CryptoPool.Rent(encryptedContentLength);
try
{
{
EncryptedContentInfo =
{
- ContentType = contentInfo.ContentType.Value,
+ ContentType = contentInfo.ContentType.Value!,
ContentEncryptionAlgorithm =
{
public override SubjectIdentifierOrKey OriginatorIdentifierOrKey =>
_asn.Originator.ToSubjectIdentifierOrKey();
- public override CryptographicAttributeObject OtherKeyAttribute
+ public override CryptographicAttributeObject? OtherKeyAttribute
{
get
{
if (rid.RKeyId.Value.Other.Value.KeyAttr != null)
{
- rawData = rid.RKeyId.Value.Other.Value.KeyAttr.Value.ToArray();
+ rawData = rid.RKeyId.Value.Other.Value.KeyAttr!.Value.ToArray();
}
Pkcs9AttributeObject pkcs9AttributeObject = new Pkcs9AttributeObject(oid, rawData);
public override int Version => _asn.Version;
- internal byte[] DecryptCek(X509Certificate2 cert, RSA privateKey, out Exception exception)
+ internal byte[]? DecryptCek(X509Certificate2? cert, RSA? privateKey, out Exception? exception)
{
ReadOnlyMemory<byte>? parameters = _asn.KeyEncryptionAlgorithm.Parameters;
- string keyEncryptionAlgorithm = _asn.KeyEncryptionAlgorithm.Algorithm.Value;
+ string? keyEncryptionAlgorithm = _asn.KeyEncryptionAlgorithm.Algorithm.Value;
switch (keyEncryptionAlgorithm)
{
return DecryptCekCore(cert, privateKey, _asn.EncryptedKey.Span, keyEncryptionAlgorithm, parameters, out exception);
}
- internal static byte[] DecryptCekCore(
- X509Certificate2 cert,
- RSA privateKey,
+ internal static byte[]? DecryptCekCore(
+ X509Certificate2? cert,
+ RSA? privateKey,
ReadOnlySpan<byte> encryptedKey,
- string keyEncryptionAlgorithm,
+ string? keyEncryptionAlgorithm,
ReadOnlyMemory<byte>? algorithmParameters,
- out Exception exception)
+ out Exception? exception)
{
- RSAEncryptionPadding encryptionPadding;
+ RSAEncryptionPadding? encryptionPadding;
switch (keyEncryptionAlgorithm)
{
return ktri;
}
- private static byte[] DecryptKey(
+ private static byte[]? DecryptKey(
RSA privateKey,
RSAEncryptionPadding encryptionPadding,
ReadOnlySpan<byte> encryptedKey,
- out Exception exception)
+ out Exception? exception)
{
if (privateKey == null)
{
}
#if NETCOREAPP || NETSTANDARD2_1
- byte[] cek = null;
+ byte[]? cek = null;
int cekLength = 0;
try
{
internal sealed partial class DecryptorPalWindows : DecryptorPal
{
- public unsafe sealed override ContentInfo TryDecrypt(
+ public unsafe sealed override ContentInfo? TryDecrypt(
RecipientInfo recipientInfo,
- X509Certificate2 cert,
- AsymmetricAlgorithm privateKey,
+ X509Certificate2? cert,
+ AsymmetricAlgorithm? privateKey,
X509Certificate2Collection originatorCerts,
X509Certificate2Collection extraStore,
- out Exception exception)
+ out Exception? exception)
{
Debug.Assert((cert != null) ^ (privateKey != null));
if (privateKey != null)
{
- RSA key = privateKey as RSA;
+ RSA? key = privateKey as RSA;
if (key == null)
{
}
ContentInfo contentInfo = _hCryptMsg.GetContentInfo();
- byte[] cek = AnyOS.ManagedPkcsPal.ManagedKeyTransPal.DecryptCekCore(
+ byte[]? cek = AnyOS.ManagedPkcsPal.ManagedKeyTransPal.DecryptCekCore(
cert,
key,
recipientInfo.EncryptedKey,
}
return AnyOS.ManagedPkcsPal.ManagedDecryptorPal.TryDecryptCore(
- cek,
- contentInfo.ContentType.Value,
+ cek!,
+ contentInfo.ContentType.Value!,
contentInfo.Content,
_contentEncryptionAlgorithm,
out exception);
// because wrapping an NCrypt wrapper over CAPI keys unconditionally causes some legacy features
// (such as RC4 support) to break.
const bool PreferNCrypt = false;
- using (SafeProvOrNCryptKeyHandle hKey = PkcsPalWindows.GetCertificatePrivateKey(cert, Silent, PreferNCrypt, out _, out exception))
+ using (SafeProvOrNCryptKeyHandle? hKey = PkcsPalWindows.GetCertificatePrivateKey(cert, Silent, PreferNCrypt, out _, out exception))
{
if (hKey == null)
return null;
}
}
- private static Exception TryGetKeySpecForCertificate(X509Certificate2 cert, out CryptKeySpec keySpec)
+ private static Exception? TryGetKeySpecForCertificate(X509Certificate2 cert, out CryptKeySpec keySpec)
{
using (SafeCertContextHandle hCertContext = cert.CreateCertContextHandle())
{
}
}
- private Exception TryDecryptTrans(KeyTransRecipientInfo recipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec)
+ private Exception? TryDecryptTrans(KeyTransRecipientInfo recipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec)
{
KeyTransRecipientInfoPalWindows pal = (KeyTransRecipientInfoPalWindows)(recipientInfo.Pal);
return null;
}
- private Exception TryDecryptAgree(KeyAgreeRecipientInfo keyAgreeRecipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore)
+ private Exception? TryDecryptAgree(KeyAgreeRecipientInfo keyAgreeRecipientInfo, SafeProvOrNCryptKeyHandle hKey, CryptKeySpec keySpec, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore)
{
unsafe
{
KeyAgreeRecipientInfoPalWindows pal = (KeyAgreeRecipientInfoPalWindows)(keyAgreeRecipientInfo.Pal);
- return pal.WithCmsgCmsRecipientInfo<Exception>(
+ return pal.WithCmsgCmsRecipientInfo<Exception?>(
delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* pKeyAgreeRecipientInfo)
{
CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara = default(CMSG_CTRL_KEY_AGREE_DECRYPT_PARA);
candidateCerts.AddRange(originatorCerts);
candidateCerts.AddRange(extraStore);
SubjectIdentifier originatorId = pKeyAgreeRecipientInfo->OriginatorCertId.ToSubjectIdentifier();
- X509Certificate2 originatorCert = candidateCerts.TryFindMatchingCertificate(originatorId);
+ X509Certificate2? originatorCert = candidateCerts.TryFindMatchingCertificate(originatorId);
if (originatorCert == null)
return ErrorCode.CRYPT_E_NOT_FOUND.ToCryptographicException();
using (SafeCertContextHandle hCertContext = originatorCert.CreateCertContextHandle())
}
}
- private Exception TryExecuteDecryptAgree(ref CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara)
+ private Exception? TryExecuteDecryptAgree(ref CMSG_CTRL_KEY_AGREE_DECRYPT_PARA decryptPara)
{
if (!Interop.Crypt32.CryptMsgControl(_hCryptMsg, 0, MsgControlType.CMSG_CTRL_KEY_AGREE_DECRYPT, ref decryptPara))
{
if (_hCryptMsg != null && !_hCryptMsg.IsInvalid)
{
_hCryptMsg.Dispose();
- _hCryptMsg = null;
+ _hCryptMsg = null!;
}
}
h.Dispose();
}
}
- _blocks = null;
+ _blocks = null!;
}
private readonly List<object> _mustLive;
public static string ToStringAnsi(this IntPtr psz)
{
- return Marshal.PtrToStringAnsi(psz);
+ return Marshal.PtrToStringAnsi(psz)!;
}
// Used for binary blobs without internal pointers.
switch (subjectIdentifierType)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
- return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.IssuerAndSerialNumber, subjectIdentifier.Value);
+ return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.IssuerAndSerialNumber, subjectIdentifier.Value!);
case SubjectIdentifierType.SubjectKeyIdentifier:
- return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.SubjectKeyIdentifier, subjectIdentifier.Value);
+ return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.SubjectKeyIdentifier, subjectIdentifier.Value!);
default:
Debug.Fail("Only the framework can construct SubjectIdentifier's so if we got a bad value here, that's our fault.");
((CspProviderFlags)keysetType & CspProviderFlags.UseMachineKeyStore) |
CspProviderFlags.UseExistingKey;
- byte[] rented = null;
+ byte[]? rented = null;
Span<byte> asciiStringBuf = stackSpan;
string provName = GetStringProvParam(handle, CryptProvParam.PP_NAME, ref asciiStringBuf, ref rented, 0);
SafeProvOrNCryptKeyHandle handle,
CryptProvParam dwParam,
ref Span<byte> buf,
- ref byte[] rented,
+ ref byte[]? rented,
int clearLen)
{
int len = buf.Length;
}
}
- public sealed override CryptographicAttributeObject OtherKeyAttribute
+ public sealed override CryptographicAttributeObject? OtherKeyAttribute
{
get
{
unsafe
{
- return WithCmsgCmsRecipientInfo<CryptographicAttributeObject>(
+ return WithCmsgCmsRecipientInfo<CryptographicAttributeObject?>(
delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient)
{
CMSG_RECIPIENT_ENCRYPTED_KEY_INFO* pEncryptedKeyInfo = recipient->rgpRecipientEncryptedKeys[SubIndex];
using (SafeCryptMsgHandle hCryptMsg = EncodeHelpers.CreateCryptMsgHandleToEncode(recipients, contentInfo.ContentType, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes))
{
byte[] encodedContent;
- if (contentInfo.ContentType.Value.Equals(Oids.Pkcs7Data, StringComparison.OrdinalIgnoreCase))
+ if (contentInfo.ContentType.Value!.Equals(Oids.Pkcs7Data, StringComparison.OrdinalIgnoreCase))
{
encodedContent = PkcsHelpers.EncodeOctetString(contentInfo.Content);
}
unsafe
{
CMSG_ENVELOPED_ENCODE_INFO* pEnvelopedEncodeInfo = CreateCmsEnvelopedEncodeInfo(recipients, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes, hb);
- SafeCryptMsgHandle hCryptMsg = Interop.Crypt32.CryptMsgOpenToEncode(MsgEncodingType.All, 0, CryptMsgType.CMSG_ENVELOPED, pEnvelopedEncodeInfo, innerContentType.Value, IntPtr.Zero);
+ SafeCryptMsgHandle hCryptMsg = Interop.Crypt32.CryptMsgOpenToEncode(MsgEncodingType.All, 0, CryptMsgType.CMSG_ENVELOPED, pEnvelopedEncodeInfo, innerContentType.Value!, IntPtr.Zero);
if (hCryptMsg == null || hCryptMsg.IsInvalid)
throw Marshal.GetLastWin32Error().ToCryptographicException();
pEnvelopedEncodeInfo->cbSize = sizeof(CMSG_ENVELOPED_ENCODE_INFO);
pEnvelopedEncodeInfo->hCryptProv = IntPtr.Zero;
- string algorithmOidValue = contentEncryptionAlgorithm.Oid.Value;
+ string algorithmOidValue = contentEncryptionAlgorithm.Oid.Value!;
pEnvelopedEncodeInfo->ContentEncryptionAlgorithm.pszObjId = hb.AllocAsciiString(algorithmOidValue);
// .NET Framework compat: Though it seems like we could copy over the contents of contentEncryptionAlgorithm.Parameters, that property is for retrieving information from decoded Cms's only, and it
for (int i = 0; i < numUnprotectedAttributes; i++)
{
CryptographicAttributeObject attribute = unprotectedAttributes[i];
- pCryptAttribute[i].pszObjId = hb.AllocAsciiString(attribute.Oid.Value);
+ pCryptAttribute[i].pszObjId = hb.AllocAsciiString(attribute.Oid.Value!);
AsnEncodedDataCollection values = attribute.Values;
int numValues = values.Count;
pCryptAttribute[i].cValue = numValues;
pEncodeInfo->cbSize = sizeof(CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO);
- RSAEncryptionPadding padding = recipient.RSAEncryptionPadding;
+ RSAEncryptionPadding? padding = recipient.RSAEncryptionPadding;
if (padding is null)
{
pEncodeInfo->pvKeyEncryptionAuxInfo = null;
string oidValue;
- AlgId algId = contentEncryptionAlgorithm.Oid.Value.ToAlgId();
+ AlgId algId = contentEncryptionAlgorithm.Oid.Value!.ToAlgId();
if (algId == AlgId.CALG_RC2)
oidValue = Oids.CmsRc2Wrap;
else
//
private static IntPtr GenerateEncryptionAuxInfoIfNeeded(AlgorithmIdentifier contentEncryptionAlgorithm, HeapBlockRetainer hb)
{
- string algorithmOidValue = contentEncryptionAlgorithm.Oid.Value;
+ string algorithmOidValue = contentEncryptionAlgorithm.Oid.Value!;
AlgId algId = algorithmOidValue.ToAlgId();
if (!(algId == AlgId.CALG_RC2 || algId == AlgId.CALG_RC4))
return IntPtr.Zero;
using Microsoft.Win32.SafeHandles;
using static Interop.Crypt32;
+using System.Diagnostics.CodeAnalysis;
namespace Internal.Cryptography.Pal.Windows
{
}
}
+ [return: MaybeNull]
public override T GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent)
{
return GetPrivateKey<T>(certificate, silent, preferNCrypt: true);
}
+ [return: MaybeNull]
public override T GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent)
{
return GetPrivateKey<T>(certificate, silent, preferNCrypt: false);
}
- private T GetPrivateKey<T>(X509Certificate2 certificate, bool silent, bool preferNCrypt) where T : AsymmetricAlgorithm
+ private T? GetPrivateKey<T>(X509Certificate2 certificate, bool silent, bool preferNCrypt) where T : AsymmetricAlgorithm
{
if (!certificate.HasPrivateKey)
{
return null;
}
- SafeProvOrNCryptKeyHandle handle = GetCertificatePrivateKey(
+ SafeProvOrNCryptKeyHandle? handle = GetCertificatePrivateKey(
certificate,
silent,
preferNCrypt,
out CryptKeySpec keySpec,
- out Exception exception);
+ out Exception? exception);
using (handle)
{
}
}
- internal static SafeProvOrNCryptKeyHandle GetCertificatePrivateKey(
+ internal static SafeProvOrNCryptKeyHandle? GetCertificatePrivateKey(
X509Certificate2 cert,
bool silent,
bool preferNCrypt,
out CryptKeySpec keySpec,
- out Exception exception)
+ out Exception? exception)
{
CryptAcquireCertificatePrivateKeyFlags flags =
CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_USE_PROV_INFO_FLAG
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using X509IssuerSerial = System.Security.Cryptography.Xml.X509IssuerSerial;
+using System.Diagnostics.CodeAnalysis;
namespace Internal.Cryptography
{
return GetDigestAlgorithm(oid.Value);
}
- internal static HashAlgorithmName GetDigestAlgorithm(string oidValue, bool forVerification = false)
+ internal static HashAlgorithmName GetDigestAlgorithm(string? oidValue, bool forVerification = false)
{
switch (oidValue)
{
public static AttributeAsn[] NormalizeAttributeSet(
AttributeAsn[] setItems,
- Action<byte[]> encodedValueProcessor = null)
+ Action<byte[]>? encodedValueProcessor = null)
{
byte[] normalizedValue;
/// <summary>
/// .NET Framework compat: We do not complain about multiple matches. Just take the first one and ignore the rest.
/// </summary>
- public static X509Certificate2 TryFindMatchingCertificate(this X509Certificate2Collection certs, SubjectIdentifier recipientIdentifier)
+ public static X509Certificate2? TryFindMatchingCertificate(this X509Certificate2Collection certs, SubjectIdentifier recipientIdentifier)
{
//
// Note: SubjectIdentifier has no public constructor so the only one that can construct this type is this assembly.
{
case SubjectIdentifierType.IssuerAndSerialNumber:
{
- X509IssuerSerial issuerSerial = (X509IssuerSerial)(recipientIdentifier.Value);
+ X509IssuerSerial issuerSerial = (X509IssuerSerial)(recipientIdentifier.Value!);
byte[] serialNumber = issuerSerial.SerialNumber.ToSerialBytes();
string issuer = issuerSerial.IssuerName;
foreach (X509Certificate2 candidate in certs)
case SubjectIdentifierType.SubjectKeyIdentifier:
{
- string skiString = (string)(recipientIdentifier.Value);
+ string skiString = (string)(recipientIdentifier.Value!);
byte[] ski = skiString.ToSkiBytes();
foreach (X509Certificate2 cert in certs)
{
Span<byte> tmp = stackalloc byte[ArbitraryStackLimit];
// Use stackalloc 0 so data can later hold a slice of tmp.
ReadOnlySpan<byte> data = stackalloc byte[0];
- byte[] poolBytes = null;
+ byte[]? poolBytes = null;
try
{
public static bool TryGetRsaOaepEncryptionPadding(
ReadOnlyMemory<byte>? parameters,
- out RSAEncryptionPadding rsaEncryptionPadding,
- out Exception exception)
+ [NotNullWhen(true)] out RSAEncryptionPadding? rsaEncryptionPadding,
+ [NotNullWhen(false)] out Exception? exception)
{
exception = null;
rsaEncryptionPadding = null;
// See the LICENSE file in the project root for more information.
using System;
+using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
/// <summary>
/// Retrieve a private key object for the certificate to use with signing.
/// </summary>
- public abstract T GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent) where T : AsymmetricAlgorithm;
+ public abstract T? GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent) where T : AsymmetricAlgorithm;
/// <summary>
/// Retrieve a private key object for the certificate to use with decryption.
/// </summary>
- public abstract T GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent) where T : AsymmetricAlgorithm;
+ public abstract T? GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent) where T : AsymmetricAlgorithm;
/// <summary>
/// Get the one instance of PkcsPal.
}
private readonly bool _isNcrypt;
- private SafeHandle _parentHandle;
+ private SafeHandle? _parentHandle;
}
}
<UsePackageTargetRuntimeDefaults Condition="'$(IsPartialFacadeAssembly)' != 'true'">true</UsePackageTargetRuntimeDefaults>
<IncludeDllSafeSearchPathAttribute>true</IncludeDllSafeSearchPathAttribute>
<NoWarn>$(NoWarn);CS1574;CS3016;CA5379;CA5384</NoWarn>
- <Nullable>annotations</Nullable>
+ <Nullable>enable</Nullable>
<TargetFrameworks>$(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent);netstandard2.0;netstandard2.0-Windows_NT;netstandard2.1;netstandard2.1-Windows_NT;netcoreapp3.0-Windows_NT;netcoreapp3.0;net461-Windows_NT;$(NetFrameworkCurrent)-Windows_NT</TargetFrameworks>
<ExcludeCurrentNetCoreAppFromPackage>true</ExcludeCurrentNetCoreAppFromPackage>
<ExcludeCurrentFullFrameworkFromPackage>true</ExcludeCurrentFullFrameworkFromPackage>
{
}
- public CryptographicAttributeObject(Oid oid, AsnEncodedDataCollection values)
+ public CryptographicAttributeObject(Oid oid, AsnEncodedDataCollection? values)
{
_oid = new Oid(oid);
if (values == null)
{
foreach (AsnEncodedData asn in values)
{
- if (!string.Equals(asn.Oid.Value, oid.Value, StringComparison.Ordinal))
+ if (!string.Equals(asn.Oid!.Value, oid.Value, StringComparison.Ordinal))
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_WrongOidInAsnCollection, oid.Value, asn.Oid.Value));
}
Values = values;
if (asnEncodedData == null)
throw new ArgumentNullException(nameof(asnEncodedData));
- return Add(new CryptographicAttributeObject(asnEncodedData.Oid, new AsnEncodedDataCollection(asnEncodedData)));
+ return Add(new CryptographicAttributeObject(asnEncodedData.Oid!, new AsnEncodedDataCollection(asnEncodedData)));
}
public int Add(CryptographicAttributeObject attribute)
//
// Merge with existing attribute, if already existed, else add as new.
//
- string szOid1 = attribute.Oid.Value;
+ string? szOid1 = attribute.Oid.Value;
for (int index = 0; index < _list.Count; index++)
{
CryptographicAttributeObject existing = _list[index];
if (object.ReferenceEquals(existing.Values, attribute.Values))
throw new InvalidOperationException(SR.InvalidOperation_DuplicateItemNotAllowed);
- string szOid2 = existing.Oid.Value;
+ string? szOid2 = existing.Oid.Value;
if (string.Equals(szOid1, szOid2, StringComparison.OrdinalIgnoreCase))
{
//
// 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.Pkcs.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.Pkcs.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.Pkcs.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.Pkcs.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.Pkcs.Asn1
{
[StructLayout(LayoutKind.Sequential)]
internal int Version;
internal System.Security.Cryptography.Pkcs.Asn1.MessageImprint MessageImprint;
- internal Oid ReqPolicy;
+ internal Oid? ReqPolicy;
internal ReadOnlyMemory<byte>? Nonce;
internal bool CertReq;
internal System.Security.Cryptography.Asn1.X509ExtensionAsn[] Extensions;
// 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.Collections.Generic;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
-#nullable enable
namespace System.Security.Cryptography.Pkcs
{
[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.Pkcs.Asn1
{
[StructLayout(LayoutKind.Sequential)]
internal ReadOnlyMemory<byte>? SignedAttributes;
internal System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn SignatureAlgorithm;
internal ReadOnlyMemory<byte> SignatureValue;
- internal System.Security.Cryptography.Asn1.AttributeAsn[] UnsignedAttributes;
+ internal System.Security.Cryptography.Asn1.AttributeAsn[]? UnsignedAttributes;
internal void Encode(AsnWriter writer)
{
#else
public
#endif
- RSAEncryptionPadding RSAEncryptionPadding { get; }
+ RSAEncryptionPadding? RSAEncryptionPadding { get; }
public SubjectIdentifierType RecipientIdentifierType { get; }
public X509Certificate2 Certificate { get; }
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using Internal.Cryptography;
+using System.Diagnostics.CodeAnalysis;
namespace System.Security.Cryptography.Pkcs
{
private class DSACmsSignature : CmsSignature
{
private readonly HashAlgorithmName _expectedDigest;
- private readonly string _signatureAlgorithm;
+ private readonly string? _signatureAlgorithm;
- internal DSACmsSignature(string signatureAlgorithm, HashAlgorithmName expectedDigest)
+ internal DSACmsSignature(string? signatureAlgorithm, HashAlgorithmName expectedDigest)
{
_signatureAlgorithm = signatureAlgorithm;
_expectedDigest = expectedDigest;
byte[] valueHash,
byte[] signature,
#endif
- string digestAlgorithmOid,
+ string? digestAlgorithmOid,
HashAlgorithmName digestAlgorithmName,
ReadOnlyMemory<byte>? signatureParameters,
X509Certificate2 certificate)
#endif
HashAlgorithmName hashAlgorithmName,
X509Certificate2 certificate,
- AsymmetricAlgorithm key,
+ AsymmetricAlgorithm? key,
bool silent,
- out Oid signatureAlgorithm,
- out byte[] signatureValue)
+ [NotNullWhen(true)] out Oid? signatureAlgorithm,
+ [NotNullWhen(true)] out byte[]? signatureValue)
{
// If there's no private key, fall back to the public key for a "no private key" exception.
DSA dsa = key as DSA ??
return false;
}
- string oidValue =
+ string? oidValue =
hashAlgorithmName == HashAlgorithmName.SHA1 ? Oids.DsaWithSha1 :
hashAlgorithmName == HashAlgorithmName.SHA256 ? Oids.DsaWithSha256 :
hashAlgorithmName == HashAlgorithmName.SHA384 ? Oids.DsaWithSha384 :
using System.Buffers;
using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography.X509Certificates;
using Internal.Cryptography;
private partial class ECDsaCmsSignature : CmsSignature
{
private readonly HashAlgorithmName _expectedDigest;
- private readonly string _signatureAlgorithm;
+ private readonly string? _signatureAlgorithm;
- internal ECDsaCmsSignature(string signatureAlgorithm, HashAlgorithmName expectedDigest)
+ internal ECDsaCmsSignature(string? signatureAlgorithm, HashAlgorithmName expectedDigest)
{
_signatureAlgorithm = signatureAlgorithm;
_expectedDigest = expectedDigest;
byte[] valueHash,
byte[] signature,
#endif
- string digestAlgorithmOid,
+ string? digestAlgorithmOid,
HashAlgorithmName digestAlgorithmName,
ReadOnlyMemory<byte>? signatureParameters,
X509Certificate2 certificate)
#endif
HashAlgorithmName hashAlgorithmName,
X509Certificate2 certificate,
- AsymmetricAlgorithm certKey,
+ AsymmetricAlgorithm? certKey,
bool silent,
- out Oid signatureAlgorithm,
- out byte[] signatureValue)
+ [NotNullWhen(true)] out Oid? signatureAlgorithm,
+ [NotNullWhen(true)] out byte[]? signatureValue)
{
// If there's no private key, fall back to the public key for a "no private key" exception.
ECDsa key = certKey as ECDsa ??
return false;
}
- string oidValue =
+ string? oidValue =
hashAlgorithmName == HashAlgorithmName.SHA1 ? Oids.ECDsaWithSha1 :
hashAlgorithmName == HashAlgorithmName.SHA256 ? Oids.ECDsaWithSha256 :
hashAlgorithmName == HashAlgorithmName.SHA384 ? Oids.ECDsaWithSha384 :
using System.Collections.Generic;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs.Asn1;
using System.Security.Cryptography.X509Certificates;
private abstract class RSACmsSignature : CmsSignature
{
- private readonly string _signatureAlgorithm;
+ private readonly string? _signatureAlgorithm;
private readonly HashAlgorithmName? _expectedDigest;
- protected RSACmsSignature(string signatureAlgorithm, HashAlgorithmName? expectedDigest)
+ protected RSACmsSignature(string? signatureAlgorithm, HashAlgorithmName? expectedDigest)
{
_signatureAlgorithm = signatureAlgorithm;
_expectedDigest = expectedDigest;
byte[] valueHash,
byte[] signature,
#endif
- string digestAlgorithmOid,
+ string? digestAlgorithmOid,
HashAlgorithmName digestAlgorithmName,
ReadOnlyMemory<byte>? signatureParameters,
X509Certificate2 certificate)
protected abstract RSASignaturePadding GetSignaturePadding(
ReadOnlyMemory<byte>? signatureParameters,
- string digestAlgorithmOid,
+ string? digestAlgorithmOid,
HashAlgorithmName digestAlgorithmName,
int digestValueLength);
}
private sealed class RSAPkcs1CmsSignature : RSACmsSignature
{
- public RSAPkcs1CmsSignature(string signatureAlgorithm, HashAlgorithmName? expectedDigest)
+ public RSAPkcs1CmsSignature(string? signatureAlgorithm, HashAlgorithmName? expectedDigest)
: base(signatureAlgorithm, expectedDigest)
{
}
protected override RSASignaturePadding GetSignaturePadding(
ReadOnlyMemory<byte>? signatureParameters,
- string digestAlgorithmOid,
+ string? digestAlgorithmOid,
HashAlgorithmName digestAlgorithmName,
int digestValueLength)
{
#endif
HashAlgorithmName hashAlgorithmName,
X509Certificate2 certificate,
- AsymmetricAlgorithm key,
+ AsymmetricAlgorithm? key,
bool silent,
- out Oid signatureAlgorithm,
- out byte[] signatureValue)
+ [NotNullWhen(true)] out Oid? signatureAlgorithm,
+ [NotNullWhen(true)] out byte[]? signatureValue)
{
RSA certPublicKey = certificate.GetRSAPublicKey();
protected override RSASignaturePadding GetSignaturePadding(
ReadOnlyMemory<byte>? signatureParameters,
- string digestAlgorithmOid,
+ string? digestAlgorithmOid,
HashAlgorithmName digestAlgorithmName,
int digestValueLength)
{
#endif
HashAlgorithmName hashAlgorithmName,
X509Certificate2 certificate,
- AsymmetricAlgorithm key,
+ AsymmetricAlgorithm? key,
bool silent,
out Oid signatureAlgorithm,
out byte[] signatureValue)
using System.Collections.Generic;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.X509Certificates;
byte[] valueHash,
byte[] signature,
#endif
- string digestAlgorithmOid,
+ string? digestAlgorithmOid,
HashAlgorithmName digestAlgorithmName,
ReadOnlyMemory<byte>? signatureParameters,
X509Certificate2 certificate);
#endif
HashAlgorithmName hashAlgorithmName,
X509Certificate2 certificate,
- AsymmetricAlgorithm key,
+ AsymmetricAlgorithm? key,
bool silent,
- out Oid signatureAlgorithm,
- out byte[] signatureValue);
+ [NotNullWhen(true)] out Oid? signatureAlgorithm,
+ [NotNullWhen(true)] out byte[]? signatureValue);
- internal static CmsSignature ResolveAndVerifyKeyType(string signatureAlgorithmOid, AsymmetricAlgorithm key)
+ internal static CmsSignature? ResolveAndVerifyKeyType(string signatureAlgorithmOid, AsymmetricAlgorithm? key)
{
- if (s_lookup.TryGetValue(signatureAlgorithmOid, out CmsSignature processor))
+ if (s_lookup.TryGetValue(signatureAlgorithmOid, out CmsSignature? processor))
{
if (key != null && !processor.VerifyKeyType(key))
{
#endif
HashAlgorithmName hashAlgorithmName,
X509Certificate2 certificate,
- AsymmetricAlgorithm key,
+ AsymmetricAlgorithm? key,
bool silent,
- out Oid oid,
+ out Oid? oid,
out ReadOnlyMemory<byte> signatureValue)
{
- CmsSignature processor = ResolveAndVerifyKeyType(certificate.GetKeyAlgorithm(), key);
+ CmsSignature? processor = ResolveAndVerifyKeyType(certificate.GetKeyAlgorithm(), key);
if (processor == null)
{
return false;
}
- byte[] signature;
- bool signed = processor.Sign(dataHash, hashAlgorithmName, certificate, key, silent, out oid, out signature);
+ bool signed = processor.Sign(dataHash, hashAlgorithmName, certificate, key, silent, out oid, out byte[]? signature);
signatureValue = signature;
return signed;
private SubjectIdentifierType _signerIdentifierType;
- public X509Certificate2 Certificate { get; set; }
- public AsymmetricAlgorithm PrivateKey { get; set; }
+ public X509Certificate2? Certificate { get; set; }
+ public AsymmetricAlgorithm? PrivateKey { get; set; }
public X509Certificate2Collection Certificates { get; private set; } = new X509Certificate2Collection();
public Oid DigestAlgorithm { get; set; }
public X509IncludeOption IncludeOption { get; set; }
{
}
- public CmsSigner(X509Certificate2 certificate)
+ public CmsSigner(X509Certificate2? certificate)
: this(SubjectIdentifierType.IssuerAndSerialNumber, certificate)
{
}
// CertCreateSelfSignedCertificate on a split Windows/netstandard implementation.
public CmsSigner(CspParameters parameters) => throw new PlatformNotSupportedException();
- public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2 certificate) : this(signerIdentifierType, certificate, null)
+ public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2? certificate) : this(signerIdentifierType, certificate, null)
{
}
- public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2 certificate, AsymmetricAlgorithm privateKey)
+ public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2? certificate, AsymmetricAlgorithm? privateKey)
{
switch (signerIdentifierType)
{
internal SignerInfoAsn Sign(
ReadOnlyMemory<byte> data,
- string contentTypeOid,
+ string? contentTypeOid,
bool silent,
out X509Certificate2Collection chainCerts)
{
switch (SignerIdentifierType)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
- byte[] serial = Certificate.GetSerialNumber();
+ byte[] serial = Certificate!.GetSerialNumber();
Array.Reverse(serial);
newSignerInfo.Sid.IssuerAndSerialNumber = new IssuerAndSerialNumberAsn
newSignerInfo.Version = 1;
break;
case SubjectIdentifierType.SubjectKeyIdentifier:
- newSignerInfo.Sid.SubjectKeyIdentifier = PkcsPal.Instance.GetSubjectKeyIdentifier(Certificate);
+ newSignerInfo.Sid.SubjectKeyIdentifier = PkcsPal.Instance.GetSubjectKeyIdentifier(Certificate!);
newSignerInfo.Version = 3;
break;
case SubjectIdentifierType.NoSignature:
}
bool signed;
- Oid signatureAlgorithm;
+ Oid? signatureAlgorithm;
ReadOnlyMemory<byte> signatureValue;
if (SignerIdentifierType == SubjectIdentifierType.NoSignature)
signed = CmsSignature.Sign(
dataHash,
hashAlgorithmName,
- Certificate,
+ Certificate!,
PrivateKey,
silent,
out signatureAlgorithm,
}
newSignerInfo.SignatureValue = signatureValue;
- newSignerInfo.SignatureAlgorithm.Algorithm = signatureAlgorithm;
+ newSignerInfo.SignatureAlgorithm.Algorithm = signatureAlgorithm!;
X509Certificate2Collection certs = new X509Certificate2Collection();
certs.AddRange(Certificates);
return newSignerInfo;
}
- internal static List<AttributeAsn> BuildAttributes(CryptographicAttributeObjectCollection attributes)
+ internal static List<AttributeAsn> BuildAttributes(CryptographicAttributeObjectCollection? attributes)
{
List<AttributeAsn> signedAttrs = new List<AttributeAsn>();
case LastCall.Decode:
case LastCall.Decrypt:
+ Debug.Assert(_decryptorPal != null);
return _decryptorPal.RecipientInfos;
default:
DecryptContent(RecipientInfos, extraStore);
}
- public void Decrypt(RecipientInfo recipientInfo, AsymmetricAlgorithm privateKey)
+ public void Decrypt(RecipientInfo recipientInfo, AsymmetricAlgorithm? privateKey)
{
if (recipientInfo == null)
throw new ArgumentNullException(nameof(recipientInfo));
CheckStateForDecryption();
X509Certificate2Collection extraStore = new X509Certificate2Collection();
- ContentInfo contentInfo = _decryptorPal.TryDecrypt(
+ ContentInfo? contentInfo = _decryptorPal!.TryDecrypt(
recipientInfo,
null,
privateKey,
Certificates,
extraStore,
- out Exception exception);
+ out Exception? exception);
if (exception != null)
throw exception;
- SetContentInfo(contentInfo);
+ SetContentInfo(contentInfo!);
}
- private void DecryptContent(RecipientInfoCollection recipientInfos, X509Certificate2Collection extraStore)
+ private void DecryptContent(RecipientInfoCollection recipientInfos, X509Certificate2Collection? extraStore)
{
CheckStateForDecryption();
extraStore = extraStore ?? new X509Certificate2Collection();
X509Certificate2Collection originatorCerts = Certificates;
- ContentInfo newContentInfo = null;
- Exception exception = PkcsPal.Instance.CreateRecipientsNotFoundException();
+ ContentInfo? newContentInfo = null;
+ Exception? exception = PkcsPal.Instance.CreateRecipientsNotFoundException();
foreach (RecipientInfo recipientInfo in recipientInfos)
{
- X509Certificate2 cert = certs.TryFindMatchingCertificate(recipientInfo.RecipientIdentifier);
+ X509Certificate2? cert = certs.TryFindMatchingCertificate(recipientInfo.RecipientIdentifier);
if (cert == null)
{
exception = PkcsPal.Instance.CreateRecipientsNotFoundException();
continue;
}
- newContentInfo = _decryptorPal.TryDecrypt(
+ newContentInfo = _decryptorPal!.TryDecrypt(
recipientInfo,
cert,
null,
if (exception != null)
throw exception;
- SetContentInfo(newContentInfo);
+ SetContentInfo(newContentInfo!);
}
private void CheckStateForDecryption()
// Instance fields
//
- private DecryptorPal _decryptorPal;
- private byte[] _encodedMessage;
+ private DecryptorPal? _decryptorPal;
+ private byte[]? _encodedMessage;
private LastCall _lastCall;
private enum LastCall
}
}
- public CryptographicAttributeObject OtherKeyAttribute
+ public CryptographicAttributeObject? OtherKeyAttribute
{
get
{
}
}
- private volatile SubjectIdentifier _lazyRecipientIdentifier = null;
- private volatile AlgorithmIdentifier _lazyKeyEncryptionAlgorithm = null;
- private volatile byte[] _lazyEncryptedKey = null;
- private volatile SubjectIdentifierOrKey _lazyOriginatorIdentifierKey = null;
+ private volatile SubjectIdentifier? _lazyRecipientIdentifier = null;
+ private volatile AlgorithmIdentifier? _lazyKeyEncryptionAlgorithm = null;
+ private volatile byte[]? _lazyEncryptedKey = null;
+ private volatile SubjectIdentifierOrKey? _lazyOriginatorIdentifierKey = null;
private DateTime? _lazyDate = default(DateTime?);
- private volatile CryptographicAttributeObject _lazyOtherKeyAttribute = null;
+ private volatile CryptographicAttributeObject? _lazyOtherKeyAttribute = null;
}
}
}
}
- private volatile SubjectIdentifier _lazyRecipientIdentifier = null;
- private volatile AlgorithmIdentifier _lazyKeyEncryptionAlgorithm = null;
- private volatile byte[] _lazyEncryptedKey = null;
+ private volatile SubjectIdentifier? _lazyRecipientIdentifier = null;
+ private volatile AlgorithmIdentifier? _lazyKeyEncryptionAlgorithm = null;
+ private volatile byte[]? _lazyEncryptedKey = null;
}
}
public sealed class Pkcs12Builder
{
private ReadOnlyMemory<byte> _sealedData;
- private List<ContentInfoAsn> _contents;
+ private List<ContentInfoAsn>? _contents;
public bool IsSealed => !_sealedData.IsEmpty;
public void AddSafeContentsEncrypted(
Pkcs12SafeContents safeContents,
- byte[] passwordBytes,
+ byte[]? passwordBytes,
PbeParameters pbeParameters)
{
AddSafeContentsEncrypted(
public void AddSafeContentsEncrypted(
Pkcs12SafeContents safeContents,
- string password,
+ string? password,
PbeParameters pbeParameters)
{
AddSafeContentsEncrypted(
}
public void SealWithMac(
- string password,
+ string? password,
HashAlgorithmName hashAlgorithm,
int iterationCount)
{
if (IsSealed)
throw new InvalidOperationException(SR.Cryptography_Pkcs12_PfxIsSealed);
- byte[] rentedAuthSafe = null;
+ byte[]? rentedAuthSafe = null;
Span<byte> authSafeSpan = default;
- byte[] rentedMac = null;
+ byte[]? rentedMac = null;
Span<byte> macSpan = default;
Span<byte> salt = stackalloc byte[0];
{
public sealed class Pkcs12CertBag : Pkcs12SafeBag
{
- private Oid _certTypeOid;
+ private Oid? _certTypeOid;
private readonly CertBagAsn _decoded;
public bool IsX509Certificate { get; }
private PfxAsn _decoded;
private ReadOnlyMemory<byte> _authSafeContents;
- public ReadOnlyCollection<Pkcs12SafeContents> AuthenticatedSafe { get; private set; }
+ public ReadOnlyCollection<Pkcs12SafeContents> AuthenticatedSafe { get; private set; } = null!; // Initialized using object initializer
public Pkcs12IntegrityMode IntegrityMode { get; private set; }
private Pkcs12Info()
{
}
- public bool VerifyMac(string password)
+ public bool VerifyMac(string? password)
{
// This extension-method call allows null.
return VerifyMac(password.AsSpan());
public abstract class Pkcs12SafeBag
{
private readonly string _bagIdValue;
- private Oid _bagOid;
- private CryptographicAttributeObjectCollection _attributes;
+ private Oid? _bagOid;
+ private CryptographicAttributeObjectCollection? _attributes;
public ReadOnlyMemory<byte> EncodedBagValue { get; }
public sealed class Pkcs12SafeContents
{
private ReadOnlyMemory<byte> _encrypted;
- private List<Pkcs12SafeBag> _bags;
+ private List<Pkcs12SafeBag>? _bags;
public Pkcs12ConfidentialityMode ConfidentialityMode { get; private set; }
public bool IsReadOnly { get; }
public Pkcs12ShroudedKeyBag AddShroudedKey(
AsymmetricAlgorithm key,
- byte[] passwordBytes,
+ byte[]? passwordBytes,
PbeParameters pbeParameters)
{
return AddShroudedKey(
public Pkcs12ShroudedKeyBag AddShroudedKey(
AsymmetricAlgorithm key,
- string password,
+ string? password,
PbeParameters pbeParameters)
{
return AddShroudedKey(
return bag;
}
- public void Decrypt(byte[] passwordBytes)
+ public void Decrypt(byte[]? passwordBytes)
{
// Null is permitted
Decrypt(new ReadOnlySpan<byte>(passwordBytes));
Decrypt(ReadOnlySpan<char>.Empty, passwordBytes);
}
- public void Decrypt(string password)
+ public void Decrypt(string? password)
{
// The string.AsSpan extension method allows null.
Decrypt(password.AsSpan());
for (int i = 0; i < serializedBags.Count; i++)
{
ReadOnlyMemory<byte> bagValue = serializedBags[i].BagValue;
- Pkcs12SafeBag bag = null;
+ Pkcs12SafeBag? bag = null;
try
{
Debug.Assert(pbeParameters != null);
Debug.Assert(pbeParameters.IterationCount >= 1);
- AsnWriter writer = null;
+ AsnWriter? writer = null;
using (AsnWriter contentsWriter = Encode())
{
{
public sealed class Pkcs12SafeContentsBag : Pkcs12SafeBag
{
- public Pkcs12SafeContents SafeContents { get; private set; }
+ public Pkcs12SafeContents? SafeContents { get; private set; }
private Pkcs12SafeContentsBag(ReadOnlyMemory<byte> encoded)
: base(Oids.Pkcs12SafeContentsBag, encoded)
{
public sealed class Pkcs12SecretBag : Pkcs12SafeBag
{
- private Oid _secretTypeOid;
+ private Oid? _secretTypeOid;
private readonly SecretBagAsn _decoded;
public ReadOnlyMemory<byte> SecretValue => _decoded.SecretValue;
private static byte[] EncodeBagValue(Oid secretTypeOid, in ReadOnlyMemory<byte> secretValue)
{
- Debug.Assert(secretTypeOid != null);
+ Debug.Assert(secretTypeOid != null && secretTypeOid.Value != null);
SecretBagAsn secretBagAsn = new SecretBagAsn
{
finally
{
CryptographicOperations.ZeroMemory(decryptedMemory.Span);
- CryptoPool.Return(decrypted.Array, clearSize: 0);
+ CryptoPool.Return(decrypted.Array!, clearSize: 0);
}
}
finally
{
CryptographicOperations.ZeroMemory(decryptedMemory.Span);
- CryptoPool.Return(decrypted.Array, clearSize: 0);
+ CryptoPool.Return(decrypted.Array!, clearSize: 0);
}
}
{
if (asnEncodedData.Oid == null)
throw new ArgumentNullException(nameof(asnEncodedData.Oid));
- string szOid = base.Oid.Value;
+ string? szOid = base.Oid!.Value;
if (szOid == null)
throw new ArgumentNullException("oid.Value");
if (szOid.Length == 0)
// Public properties.
//
- public new Oid Oid
+ public new Oid? Oid
{
get
{
using System;
using System.Diagnostics;
-
+using System.Diagnostics.CodeAnalysis;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
// Private methods.
//
- private static Oid Decode(byte[] rawData)
+ [return: NotNullIfNotNull("rawData")]
+ private static Oid? Decode(byte[]? rawData)
{
if (rawData == null)
return null;
return new Oid(contentTypeValue);
}
- private volatile Oid _lazyContentType = null;
+ private volatile Oid? _lazyContentType = null;
}
}
using System;
using System.Diagnostics;
-
+using System.Diagnostics.CodeAnalysis;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
// Private methods.
//
- private static string Decode(byte[] rawData)
+ [return: NotNullIfNotNull("rawData")]
+ private static string? Decode(byte[]? rawData)
{
if (rawData == null)
return null;
return PkcsHelpers.EncodeOctetString(octets);
}
- private volatile string _lazyDocumentDescription = null;
+ private volatile string? _lazyDocumentDescription = null;
}
}
using System;
using System.Diagnostics;
-
+using System.Diagnostics.CodeAnalysis;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
// Private methods.
//
- private static string Decode(byte[] rawData)
+ [return: NotNullIfNotNull("rawData")]
+ private static string? Decode(byte[]? rawData)
{
if (rawData == null)
return null;
return PkcsHelpers.EncodeOctetString(octets);
}
- private volatile string _lazyDocumentName = null;
+ private volatile string? _lazyDocumentName = null;
}
}
// 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.CodeAnalysis;
using System.Security.Cryptography.Asn1;
using Internal.Cryptography;
{
public sealed class Pkcs9LocalKeyId : Pkcs9AttributeObject
{
- private byte[] _lazyKeyId;
+ private byte[]? _lazyKeyId;
public Pkcs9LocalKeyId() :
base(new Oid(Oids.LocalKeyId))
_lazyKeyId = null;
}
- private static byte[] Decode(byte[] rawData)
+ [return: NotNullIfNotNull("rawData")]
+ private static byte[]? Decode(byte[]? rawData)
{
if (rawData == null)
{
using System;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography.Asn1;
using Internal.Cryptography;
// Private methods.
//
- private static byte[] Decode(byte[] rawData)
+ [return: NotNullIfNotNull("rawData")]
+ private static byte[]? Decode(byte[]? rawData)
{
if (rawData == null)
return null;
return PkcsHelpers.DecodeOctetString(rawData);
}
- private volatile byte[] _lazyMessageDigest = null;
+ private volatile byte[]? _lazyMessageDigest = null;
}
}
// Private methods.
//
- private static DateTime Decode(byte[] rawData)
+ private static DateTime Decode(byte[]? rawData)
{
if (rawData == null)
return default(DateTime);
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs.Asn1;
{
public sealed class Rfc3161TimestampRequest
{
- private byte[] _encodedBytes;
+ private byte[] _encodedBytes = null!; // Initided using object initializer
private Rfc3161TimeStampReq _parsedData;
private Rfc3161TimestampRequest()
public int Version => _parsedData.Version;
public ReadOnlyMemory<byte> GetMessageHash() => _parsedData.MessageImprint.HashedMessage;
public Oid HashAlgorithmId => _parsedData.MessageImprint.HashAlgorithm.Algorithm;
- public Oid RequestedPolicyId => _parsedData.ReqPolicy;
+ public Oid? RequestedPolicyId => _parsedData.ReqPolicy;
public bool RequestSignerCertificate => _parsedData.CertReq;
public ReadOnlyMemory<byte>? GetNonce() => _parsedData.Nonce;
public bool HasExtensions => _parsedData.Extensions?.Length > 0;
public Rfc3161TimestampToken ProcessResponse(ReadOnlyMemory<byte> source, out int bytesConsumed)
{
- Rfc3161RequestResponseStatus status;
- Rfc3161TimestampToken token;
-
- if (ProcessResponse(source, out token, out status, out int localBytesRead, shouldThrow: true))
+ if (ProcessResponse(source, out Rfc3161TimestampToken? token, out Rfc3161RequestResponseStatus status, out int localBytesRead, shouldThrow: true))
{
Debug.Assert(status == Rfc3161RequestResponseStatus.Accepted);
bytesConsumed = localBytesRead;
private bool ProcessResponse(
ReadOnlyMemory<byte> source,
- out Rfc3161TimestampToken token,
+ [NotNullWhen(true)] out Rfc3161TimestampToken? token,
out Rfc3161RequestResponseStatus status,
out int bytesConsumed,
bool shouldThrow)
public static Rfc3161TimestampRequest CreateFromSignerInfo(
SignerInfo signerInfo,
HashAlgorithmName hashAlgorithm,
- Oid requestedPolicyId = null,
+ Oid? requestedPolicyId = null,
ReadOnlyMemory<byte>? nonce = null,
bool requestSignerCertificates = false,
- X509ExtensionCollection extensions = null)
+ X509ExtensionCollection? extensions = null)
{
if (signerInfo == null)
{
public static Rfc3161TimestampRequest CreateFromData(
ReadOnlySpan<byte> data,
HashAlgorithmName hashAlgorithm,
- Oid requestedPolicyId = null,
+ Oid? requestedPolicyId = null,
ReadOnlyMemory<byte>? nonce = null,
bool requestSignerCertificates = false,
- X509ExtensionCollection extensions = null)
+ X509ExtensionCollection? extensions = null)
{
using (IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithm))
{
public static Rfc3161TimestampRequest CreateFromHash(
ReadOnlyMemory<byte> hash,
HashAlgorithmName hashAlgorithm,
- Oid requestedPolicyId = null,
+ Oid? requestedPolicyId = null,
ReadOnlyMemory<byte>? nonce = null,
bool requestSignerCertificates = false,
- X509ExtensionCollection extensions = null)
+ X509ExtensionCollection? extensions = null)
{
string oidStr = PkcsHelpers.GetOidFromHashAlgorithm(hashAlgorithm);
public static Rfc3161TimestampRequest CreateFromHash(
ReadOnlyMemory<byte> hash,
Oid hashAlgorithmId,
- Oid requestedPolicyId = null,
+ Oid? requestedPolicyId = null,
ReadOnlyMemory<byte>? nonce = null,
bool requestSignerCertificates = false,
- X509ExtensionCollection extensions = null)
+ X509ExtensionCollection? extensions = null)
{
// Normalize the nonce:
if (nonce.HasValue)
public static bool TryDecode(
ReadOnlyMemory<byte> encodedBytes,
- out Rfc3161TimestampRequest request,
+ [NotNullWhen(true)] out Rfc3161TimestampRequest? request,
out int bytesConsumed)
{
try
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Asn1.Pkcs7;
{
public sealed class Rfc3161TimestampToken
{
- private SignedCms _parsedDocument;
- private SignerInfo _signerInfo;
+ private SignedCms _parsedDocument = null!; // Initialized by object initializer
+ private SignerInfo? _signerInfo;
private EssCertId? _essCertId;
private EssCertIdV2? _essCertIdV2;
- public Rfc3161TimestampTokenInfo TokenInfo { get; private set; }
+ public Rfc3161TimestampTokenInfo TokenInfo { get; private set; } = null!;
private Rfc3161TimestampToken()
{
/// </remarks>
public SignedCms AsSignedCms() => _parsedDocument;
- private X509Certificate2 GetSignerCertificate(X509Certificate2Collection extraCandidates)
+ private X509Certificate2? GetSignerCertificate(X509Certificate2Collection? extraCandidates)
{
Debug.Assert(_signerInfo != null, "_signerInfo != null");
- X509Certificate2 signerCert = _signerInfo.Certificate;
+ X509Certificate2? signerCert = _signerInfo.Certificate;
if (signerCert != null)
{
public bool VerifySignatureForData(
ReadOnlySpan<byte> data,
- out X509Certificate2 signerCertificate,
- X509Certificate2Collection extraCandidates = null)
+ [NotNullWhen(true)] out X509Certificate2? signerCertificate,
+ X509Certificate2Collection? extraCandidates = null)
{
signerCertificate = null;
- X509Certificate2 cert = GetSignerCertificate(extraCandidates);
+ X509Certificate2? cert = GetSignerCertificate(extraCandidates);
if (cert == null)
{
public bool VerifySignatureForHash(
ReadOnlySpan<byte> hash,
HashAlgorithmName hashAlgorithm,
- out X509Certificate2 signerCertificate,
- X509Certificate2Collection extraCandidates = null)
+ [NotNullWhen(true)] out X509Certificate2? signerCertificate,
+ X509Certificate2Collection? extraCandidates = null)
{
signerCertificate = null;
- X509Certificate2 cert = GetSignerCertificate(extraCandidates);
+ X509Certificate2? cert = GetSignerCertificate(extraCandidates);
if (cert == null)
{
public bool VerifySignatureForHash(
ReadOnlySpan<byte> hash,
Oid hashAlgorithmId,
- out X509Certificate2 signerCertificate,
- X509Certificate2Collection extraCandidates = null)
+ [NotNullWhen(true)] out X509Certificate2? signerCertificate,
+ X509Certificate2Collection? extraCandidates = null)
{
if (hashAlgorithmId == null)
{
signerCertificate = null;
- X509Certificate2 cert = GetSignerCertificate(extraCandidates);
+ X509Certificate2? cert = GetSignerCertificate(extraCandidates);
if (cert == null)
{
public bool VerifySignatureForSignerInfo(
SignerInfo signerInfo,
- out X509Certificate2 signerCertificate,
- X509Certificate2Collection extraCandidates = null)
+ [NotNullWhen(true)] out X509Certificate2? signerCertificate,
+ X509Certificate2Collection? extraCandidates = null)
{
if (signerInfo == null)
{
extraCandidates);
}
- internal bool VerifyHash(ReadOnlySpan<byte> hash, string hashAlgorithmId)
+ internal bool VerifyHash(ReadOnlySpan<byte> hash, string? hashAlgorithmId)
{
return
hash.SequenceEqual(TokenInfo.GetMessageHash().Span) &&
}
}
- public static bool TryDecode(ReadOnlyMemory<byte> source, out Rfc3161TimestampToken token, out int bytesConsumed)
+ public static bool TryDecode(ReadOnlyMemory<byte> source, [NotNullWhen(true)] out Rfc3161TimestampToken? token, out int bytesConsumed)
{
bytesConsumed = 0;
token = null;
return false;
}
- X509Certificate2 signerCert = signer.Certificate;
+ X509Certificate2? signerCert = signer.Certificate;
if (signerCert == null &&
signer.SignerIdentifier.Type == SubjectIdentifierType.IssuerAndSerialNumber)
{
// If the cert wasn't provided, but the identifier was IssuerAndSerialNumber,
// and the ESSCertId(V2) has specified an issuerSerial value, ensure it's a match.
- X509IssuerSerial issuerSerial = (X509IssuerSerial)signer.SignerIdentifier.Value;
+ X509IssuerSerial issuerSerial = (X509IssuerSerial)signer.SignerIdentifier.Value!;
if (certId.HasValue && certId.Value.IssuerSerial != null)
{
}
}
- Rfc3161TimestampTokenInfo tokenInfo;
-
- if (Rfc3161TimestampTokenInfo.TryDecode(cms.ContentInfo.Content, out tokenInfo, out _))
+ if (Rfc3161TimestampTokenInfo.TryDecode(cms.ContentInfo.Content, out Rfc3161TimestampTokenInfo? tokenInfo, out _))
{
if (signerCert != null &&
!CheckCertificate(signerCert, signer, in certId, in certId2, tokenInfo))
{
Debug.Assert(signerCert != null);
Debug.Assert(certId.HasValue || certId2.HasValue);
- byte[] serialNumber = null;
+ byte[]? serialNumber = null;
if (certId.HasValue)
{
foreach (CryptographicAttributeObject attrSet in signer.SignedAttributes)
{
- string setOid = attrSet.Oid?.Value;
+ string? setOid = attrSet.Oid?.Value;
if (setOid != null &&
setOid != Oids.SigningCertificate &&
foreach (AsnEncodedData attr in attrSet.Values)
{
- string attrOid = attr.Oid?.Value;
+ string? attrOid = attr.Oid?.Value;
if (attrOid == Oids.SigningCertificate)
{
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs.Asn1;
bool isOrdering = false,
ReadOnlyMemory<byte>? nonce = null,
ReadOnlyMemory<byte>? tsaName = null,
- X509ExtensionCollection extensions = null)
+ X509ExtensionCollection? extensions = null)
{
_encodedBytes = Encode(
policyId,
public static bool TryDecode(
ReadOnlyMemory<byte> source,
- out Rfc3161TimestampTokenInfo timestampTokenInfo,
+ [NotNullWhen(true)] out Rfc3161TimestampTokenInfo? timestampTokenInfo,
out int bytesConsumed)
{
- if (TryDecode(source, false, out Rfc3161TstInfo tstInfo, out bytesConsumed, out byte[] copiedBytes))
+ if (TryDecode(source, false, out Rfc3161TstInfo tstInfo, out bytesConsumed, out byte[]? copiedBytes))
{
- timestampTokenInfo = new Rfc3161TimestampTokenInfo(copiedBytes, tstInfo);
+ timestampTokenInfo = new Rfc3161TimestampTokenInfo(copiedBytes!, tstInfo);
return true;
}
bool ownsMemory,
out Rfc3161TstInfo tstInfo,
out int bytesConsumed,
- out byte[] copiedBytes)
+ out byte[]? copiedBytes)
{
// https://tools.ietf.org/html/rfc3161#section-2.4.2
// The eContent SHALL be the DER-encoded value of TSTInfo.
long? accuracyInMicroseconds,
ReadOnlyMemory<byte>? nonce,
ReadOnlyMemory<byte>? tsaName,
- X509ExtensionCollection extensions)
+ X509ExtensionCollection? extensions)
{
if (policyId == null)
throw new ArgumentNullException(nameof(policyId));
// Similar to _heldContent, the Windows CMS API held this separate internally,
// and thus we need to be reslilient against modification.
- private string _contentType;
+ private string? _contentType;
public int Version { get; private set; }
public ContentInfo ContentInfo { get; private set; }
foreach (CertificateChoiceAsn choice in certChoices)
{
+ Debug.Assert(choice.Certificate.HasValue);
coll.Add(new X509Certificate2(choice.Certificate.Value.ToArray()));
}
// dynamic adapter.
//
// See https://tools.ietf.org/html/rfc5652#section-5.2.1
- byte[] rented = null;
+ byte[]? rented = null;
int bytesWritten = 0;
try
{
internal ReadOnlySpan<byte> GetHashableContentSpan()
{
+ Debug.Assert(_heldContent.HasValue);
ReadOnlyMemory<byte> content = _heldContent.Value;
if (!_hasPkcs7Content)
if (existingLength > 0)
{
- foreach (CertificateChoiceAsn cert in _signedData.CertificateSet)
+ foreach (CertificateChoiceAsn cert in _signedData.CertificateSet!)
{
- if (cert.Certificate.Value.Span.SequenceEqual(rawData))
+ if (cert.Certificate!.Value.Span.SequenceEqual(rawData))
{
throw new CryptographicException(SR.Cryptography_Cms_CertificateAlreadyInCollection);
}
int idx = 0;
byte[] rawData = certificate.RawData;
- foreach (CertificateChoiceAsn cert in _signedData.CertificateSet)
+ foreach (CertificateChoiceAsn cert in _signedData.CertificateSet!)
{
- if (cert.Certificate.Value.Span.SequenceEqual(rawData))
+ if (cert.Certificate!.Value.Span.SequenceEqual(rawData))
{
PkcsHelpers.RemoveAt(ref _signedData.CertificateSet, idx);
Reencode();
public SubjectIdentifier SignerIdentifier { get; }
private readonly Oid _digestAlgorithm;
- private readonly AttributeAsn[] _signedAttributes;
+ private readonly AttributeAsn[]? _signedAttributes;
private readonly ReadOnlyMemory<byte>? _signedAttributesMemory;
private readonly Oid _signatureAlgorithm;
private readonly ReadOnlyMemory<byte>? _signatureAlgorithmParameters;
private readonly ReadOnlyMemory<byte> _signature;
- private readonly AttributeAsn[] _unsignedAttributes;
+ private readonly AttributeAsn[]? _unsignedAttributes;
private readonly SignedCms _document;
- private X509Certificate2 _signerCertificate;
- private SignerInfo _parentSignerInfo;
- private CryptographicAttributeObjectCollection _parsedSignedAttrs;
- private CryptographicAttributeObjectCollection _parsedUnsignedAttrs;
+ private X509Certificate2? _signerCertificate;
+ private SignerInfo? _parentSignerInfo;
+ private CryptographicAttributeObjectCollection? _parsedSignedAttrs;
+ private CryptographicAttributeObjectCollection? _parsedUnsignedAttrs;
internal SignerInfo(ref SignerInfoAsn parsedData, SignedCms ownerDocument)
{
public byte[] GetSignature() => _signature.ToArray();
- public X509Certificate2 Certificate
+ public X509Certificate2? Certificate
{
get
{
throw new CryptographicException(SR.Cryptography_Cms_NoSignerAtIndex);
}
- ref AttributeAsn[] unsignedAttrs = ref parentData.UnsignedAttributes;
+ ref AttributeAsn[] unsignedAttrs = ref parentData.UnsignedAttributes!;
for (int i = 0; i < unsignedAttrs.Length; i++)
{
private static void AddUnsignedAttribute(ref SignerInfoAsn mySigner, AsnEncodedData unsignedAttribute)
{
- int existingAttribute = mySigner.UnsignedAttributes == null ? -1 : FindAttributeIndexByOid(mySigner.UnsignedAttributes, unsignedAttribute.Oid);
+ int existingAttribute = mySigner.UnsignedAttributes == null ? -1 : FindAttributeIndexByOid(mySigner.UnsignedAttributes, unsignedAttribute.Oid!);
if (existingAttribute == -1)
{
else
{
// merge with existing attribute
- ref AttributeAsn modifiedAttr = ref mySigner.UnsignedAttributes[existingAttribute];
+ ref AttributeAsn modifiedAttr = ref mySigner.UnsignedAttributes![existingAttribute];
int newIndex = modifiedAttr.AttrValues.Length;
Array.Resize(ref modifiedAttr.AttrValues, newIndex + 1);
modifiedAttr.AttrValues[newIndex] = unsignedAttribute.RawData;
if (isOnlyValue)
{
- PkcsHelpers.RemoveAt(ref mySigner.UnsignedAttributes, outerIndex);
+ PkcsHelpers.RemoveAt(ref mySigner.UnsignedAttributes!, outerIndex);
}
else
{
- PkcsHelpers.RemoveAt(ref mySigner.UnsignedAttributes[outerIndex].AttrValues, innerIndex);
+ PkcsHelpers.RemoveAt(ref mySigner.UnsignedAttributes![outerIndex].AttrValues, innerIndex);
}
}
if (extraStore == null)
throw new ArgumentNullException(nameof(extraStore));
- X509Certificate2 certificate = Certificate;
+ X509Certificate2? certificate = Certificate;
if (certificate == null)
{
private bool CheckHash(bool compatMode)
{
- using (IncrementalHash hasher = PrepareDigest(compatMode))
+ using (IncrementalHash? hasher = PrepareDigest(compatMode))
{
if (hasher == null)
{
}
}
- private X509Certificate2 FindSignerCertificate()
+ private X509Certificate2? FindSignerCertificate()
{
return FindSignerCertificate(SignerIdentifier, _document.Certificates);
}
- private static X509Certificate2 FindSignerCertificate(
+ private static X509Certificate2? FindSignerCertificate(
SubjectIdentifier signerIdentifier,
- X509Certificate2Collection extraStore)
+ X509Certificate2Collection? extraStore)
{
if (extraStore == null || extraStore.Count == 0)
{
return null;
}
- X509Certificate2Collection filtered = null;
- X509Certificate2 match = null;
+ X509Certificate2Collection? filtered = null;
+ X509Certificate2? match = null;
switch (signerIdentifier.Type)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
{
- X509IssuerSerial issuerSerial = (X509IssuerSerial)signerIdentifier.Value;
+ X509IssuerSerial issuerSerial = (X509IssuerSerial)signerIdentifier.Value!;
filtered = extraStore.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false);
foreach (X509Certificate2 cert in filtered)
return match;
}
- private IncrementalHash PrepareDigest(bool compatMode)
+ private IncrementalHash? PrepareDigest(bool compatMode)
{
HashAlgorithmName hashAlgorithmName = GetDigestAlgorithm();
X509Certificate2 certificate,
bool verifySignatureOnly)
{
- CmsSignature signatureProcessor = CmsSignature.ResolveAndVerifyKeyType(SignatureAlgorithm.Value, key: null);
+ CmsSignature? signatureProcessor = CmsSignature.ResolveAndVerifyKeyType(SignatureAlgorithm.Value!, key: null);
if (signatureProcessor == null)
{
foreach (X509Extension ext in certificate.Extensions)
{
- if (ext.Oid.Value == Oids.KeyUsage)
+ if (ext.Oid!.Value == Oids.KeyUsage)
{
if (!(ext is X509KeyUsageExtension keyUsage))
{
X509Certificate2 certificate,
bool compatMode)
{
- using (IncrementalHash hasher = PrepareDigest(compatMode))
+ using (IncrementalHash? hasher = PrepareDigest(compatMode))
{
if (hasher == null)
{
private HashAlgorithmName GetDigestAlgorithm()
{
- return PkcsHelpers.GetDigestAlgorithm(DigestAlgorithm.Value, forVerification: true);
+ return PkcsHelpers.GetDigestAlgorithm(DigestAlgorithm.Value!, forVerification: true);
}
- internal static CryptographicAttributeObjectCollection MakeAttributeCollection(AttributeAsn[] attributes)
+ internal static CryptographicAttributeObjectCollection MakeAttributeCollection(AttributeAsn[]? attributes)
{
var coll = new CryptographicAttributeObjectCollection();
return -1;
}
- private static (int, int) FindAttributeLocation(AttributeAsn[] attributes, AsnEncodedData attribute, out bool isOnlyValue)
+ private static (int, int) FindAttributeLocation(AttributeAsn[]? attributes, AsnEncodedData attribute, out bool isOnlyValue)
{
if (attributes != null)
{
for (int outerIndex = 0; ; outerIndex++)
{
- outerIndex = FindAttributeIndexByOid(attributes, attribute.Oid, outerIndex);
+ outerIndex = FindAttributeIndexByOid(attributes, attribute.Oid!, outerIndex);
if (outerIndex == -1)
{
private readonly SignerInfoCollection _signerInfos;
private int _position;
- private SignerInfoEnumerator() { }
-
internal SignerInfoEnumerator(SignerInfoCollection signerInfos)
{
Debug.Assert(signerInfos != null);
}
public SubjectIdentifierType Type { get; }
- public object Value { get; }
+ public object? Value { get; }
public bool MatchesCertificate(X509Certificate2 certificate)
{
{
case SubjectIdentifierType.IssuerAndSerialNumber:
{
- X509IssuerSerial issuerSerial = (X509IssuerSerial)Value;
+ X509IssuerSerial issuerSerial = (X509IssuerSerial)Value!;
byte[] serialNumber = issuerSerial.SerialNumber.ToSerialBytes();
string issuer = issuerSerial.IssuerName;
byte[] certSerialNumber = certificate.GetSerialNumber();
case SubjectIdentifierType.SubjectKeyIdentifier:
{
- string skiString = (string)Value;
+ string skiString = (string)Value!;
byte[] ski = skiString.ToSkiBytes();
byte[] candidateSki = PkcsPal.Instance.GetSubjectKeyIdentifier(certificate);
if (Type == SubjectIdentifierType.IssuerAndSerialNumber)
{
- issuerSerial = (X509IssuerSerial)Value;
+ issuerSerial = (X509IssuerSerial)Value!;
}
switch (Type)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
{
- X509IssuerSerial currentIssuerSerial = (X509IssuerSerial)currentId.Value;
+ X509IssuerSerial currentIssuerSerial = (X509IssuerSerial)currentId.Value!;
return currentIssuerSerial.IssuerName == issuerSerial.IssuerName &&
currentIssuerSerial.SerialNumber == issuerSerial.SerialNumber;
}
case SubjectIdentifierType.SubjectKeyIdentifier:
- return (string)Value == (string)currentId.Value;
+ return (string)Value! == (string)currentId.Value!;
case SubjectIdentifierType.NoSignature:
return true;
default: