From 309e03665e125494cf8d81390934c8050e4abeb9 Mon Sep 17 00:00:00 2001 From: BrentSchmaltz Date: Tue, 3 Dec 2024 11:21:37 -0800 Subject: [PATCH] Stack parameters to improve reading of code. (#3031) Fix some spelling. Co-authored-by: id4s --- .../AsymmetricAdapter.cs | 51 +++- .../AsymmetricSignatureProvider.cs | 92 +++++-- .../CryptoProviderFactory.cs | 225 +++++++++++++----- .../SignatureProvider.cs | 4 +- .../SymmetricSignatureProvider.cs | 71 ++++-- 5 files changed, 337 insertions(+), 106 deletions(-) diff --git a/src/Microsoft.IdentityModel.Tokens/AsymmetricAdapter.cs b/src/Microsoft.IdentityModel.Tokens/AsymmetricAdapter.cs index 5bca1e9317..7b09c89324 100644 --- a/src/Microsoft.IdentityModel.Tokens/AsymmetricAdapter.cs +++ b/src/Microsoft.IdentityModel.Tokens/AsymmetricAdapter.cs @@ -47,14 +47,23 @@ internal AsymmetricAdapter(SecurityKey key, string algorithm, bool requirePrivat { } - internal AsymmetricAdapter(SecurityKey key, string algorithm, HashAlgorithm hashAlgorithm, HashAlgorithmName hashAlgorithmName, bool requirePrivateKey) + internal AsymmetricAdapter( + SecurityKey key, + string algorithm, + HashAlgorithm hashAlgorithm, + HashAlgorithmName hashAlgorithmName, + bool requirePrivateKey) : this(key, algorithm, hashAlgorithm, requirePrivateKey) { HashAlgorithmName = hashAlgorithmName; } - internal AsymmetricAdapter(SecurityKey key, string algorithm, HashAlgorithm hashAlgorithm, bool requirePrivateKey) + internal AsymmetricAdapter( + SecurityKey key, + string algorithm, + HashAlgorithm hashAlgorithm, + bool requirePrivateKey) { HashAlgorithm = hashAlgorithm; @@ -79,7 +88,11 @@ internal AsymmetricAdapter(SecurityKey key, string algorithm, HashAlgorithm hash else if (securityKey is ECDsaSecurityKey edcsaSecurityKeyFromJsonWebKey) InitializeUsingEcdsaSecurityKey(edcsaSecurityKeyFromJsonWebKey); else - throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10684, LogHelper.MarkAsNonPII(algorithm), key))); + throw LogHelper.LogExceptionMessage( + new NotSupportedException( + LogHelper.FormatInvariant( + LogMessages.IDX10684, + LogHelper.MarkAsNonPII(algorithm), key))); } } else if (key is ECDsaSecurityKey ecdsaKey) @@ -87,7 +100,11 @@ internal AsymmetricAdapter(SecurityKey key, string algorithm, HashAlgorithm hash InitializeUsingEcdsaSecurityKey(ecdsaKey); } else - throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10684, LogHelper.MarkAsNonPII(algorithm), key))); + throw LogHelper.LogExceptionMessage( + new NotSupportedException( + LogHelper.FormatInvariant( + LogMessages.IDX10684, + LogHelper.MarkAsNonPII(algorithm), key))); } internal byte[] Decrypt(byte[] data) @@ -233,7 +250,10 @@ private void InitializeUsingRsaSecurityKey(RsaSecurityKey rsaSecurityKey, string } } - private void InitializeUsingX509SecurityKey(X509SecurityKey x509SecurityKey, string algorithm, bool requirePrivateKey) + private void InitializeUsingX509SecurityKey( + X509SecurityKey x509SecurityKey, + string algorithm, + bool requirePrivateKey) { if (requirePrivateKey) InitializeUsingRsa(x509SecurityKey.PrivateKey as RSA, algorithm); @@ -249,7 +269,10 @@ internal byte[] Sign(byte[] bytes) } #if NET6_0_OR_GREATER - internal bool SignUsingSpan(ReadOnlySpan data, Span destination, out int bytesWritten) + internal bool SignUsingSpan( + ReadOnlySpan data, + Span destination, + out int bytesWritten) { return _signUsingSpanFunction(data, destination, out bytesWritten); } @@ -274,7 +297,10 @@ private static byte[] SignUsingOffsetNotFound(byte[] b, int c, int d) #if NET6_0_OR_GREATER #pragma warning disable CA1801 // Review unused parameters - private static bool SignUsingSpanNotFound(ReadOnlySpan data, Span destination, out int bytesWritten) + private static bool SignUsingSpanNotFound( + ReadOnlySpan data, + Span destination, + out int bytesWritten) #pragma warning restore CA1801 // Review unused parameters { // we should never get here, its a bug if we do. @@ -288,7 +314,10 @@ private byte[] SignECDsa(byte[] bytes) } #if NET6_0_OR_GREATER - internal bool SignUsingSpanECDsa(ReadOnlySpan data, Span destination, out int bytesWritten) + internal bool SignUsingSpanECDsa( + ReadOnlySpan data, + Span destination, + out int bytesWritten) { // ECDSA.TrySignData will return true and set bytesWritten = 64, if destination is null. if (destination.Length == 0) @@ -397,7 +426,11 @@ private bool VerifyUsingOffsetRsa(byte[] bytes, int offset, int count, byte[] si #if NET6_0_OR_GREATER return VerifyUsingSpan(isRSA: true, bytes.AsSpan(offset, count), signature); #else - return RSA.VerifyHash(HashAlgorithm.ComputeHash(bytes, offset, count), signature, HashAlgorithmName, RSASignaturePadding); + return RSA.VerifyHash( + HashAlgorithm.ComputeHash(bytes, offset, count), + signature, + HashAlgorithmName, + RSASignaturePadding); #endif } diff --git a/src/Microsoft.IdentityModel.Tokens/AsymmetricSignatureProvider.cs b/src/Microsoft.IdentityModel.Tokens/AsymmetricSignatureProvider.cs index b767713bb1..0117c21b5e 100644 --- a/src/Microsoft.IdentityModel.Tokens/AsymmetricSignatureProvider.cs +++ b/src/Microsoft.IdentityModel.Tokens/AsymmetricSignatureProvider.cs @@ -22,7 +22,7 @@ public class AsymmetricSignatureProvider : SignatureProvider /// /// Mapping from algorithm to minimum .KeySize when creating signatures. /// - public static readonly Dictionary DefaultMinimumAsymmetricKeySizeInBitsForSigningMap = new Dictionary() + public static readonly Dictionary DefaultMinimumAsymmetricKeySizeInBitsForSigningMap = new() { { SecurityAlgorithms.EcdsaSha256, 256 }, { SecurityAlgorithms.EcdsaSha384, 256 }, @@ -47,7 +47,7 @@ public class AsymmetricSignatureProvider : SignatureProvider /// /// Mapping from algorithm to minimum .KeySize when verifying signatures. /// - public static readonly Dictionary DefaultMinimumAsymmetricKeySizeInBitsForVerifyingMap = new Dictionary() + public static readonly Dictionary DefaultMinimumAsymmetricKeySizeInBitsForVerifyingMap = new() { { SecurityAlgorithms.EcdsaSha256, 256 }, { SecurityAlgorithms.EcdsaSha384, 256 }, @@ -69,13 +69,20 @@ public class AsymmetricSignatureProvider : SignatureProvider { SecurityAlgorithms.RsaSsaPssSha512Signature, 1040 } }; - internal AsymmetricSignatureProvider(SecurityKey key, string algorithm, CryptoProviderFactory cryptoProviderFactory) + internal AsymmetricSignatureProvider( + SecurityKey key, + string algorithm, + CryptoProviderFactory cryptoProviderFactory) : this(key, algorithm) { _cryptoProviderFactory = cryptoProviderFactory; } - internal AsymmetricSignatureProvider(SecurityKey key, string algorithm, bool willCreateSignatures, CryptoProviderFactory cryptoProviderFactory) + internal AsymmetricSignatureProvider( + SecurityKey key, + string algorithm, + bool willCreateSignatures, + CryptoProviderFactory cryptoProviderFactory) : this(key, algorithm, willCreateSignatures) { _cryptoProviderFactory = cryptoProviderFactory; @@ -104,7 +111,10 @@ public AsymmetricSignatureProvider(SecurityKey key, string algorithm) /// Thrown if is true and is less than the required size for signing. /// Thrown if is less than the required size for verifying signatures. /// Thrown if the runtime is unable to create a suitable cryptographic provider. - public AsymmetricSignatureProvider(SecurityKey key, string algorithm, bool willCreateSignatures) + public AsymmetricSignatureProvider( + SecurityKey key, + string algorithm, + bool willCreateSignatures) : base(key, algorithm) { _cryptoProviderFactory = key.CryptoProviderFactory; @@ -116,13 +126,21 @@ public AsymmetricSignatureProvider(SecurityKey key, string algorithm, bool willC JsonWebKeyConverter.TryConvertToSecurityKey(jsonWebKey, out SecurityKey _); if (willCreateSignatures && FoundPrivateKey(key) == PrivateKeyStatus.DoesNotExist) - throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(LogMessages.IDX10638, key))); + throw LogHelper.LogExceptionMessage( + new InvalidOperationException( + LogHelper.FormatInvariant(LogMessages.IDX10638, key))); if (!_cryptoProviderFactory.IsSupportedAlgorithm(algorithm, key)) - throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10634, LogHelper.MarkAsNonPII((algorithm)), key))); + throw LogHelper.LogExceptionMessage( + new NotSupportedException( + LogHelper.FormatInvariant( + LogMessages.IDX10634, + LogHelper.MarkAsNonPII((algorithm)), key))); WillCreateSignatures = willCreateSignatures; - _asymmetricAdapterObjectPool = new DisposableObjectPool(CreateAsymmetricAdapter, _cryptoProviderFactory.SignatureProviderObjectPoolCacheSize); + _asymmetricAdapterObjectPool = new DisposableObjectPool( + CreateAsymmetricAdapter, + _cryptoProviderFactory.SignatureProviderObjectPoolCacheSize); } /// @@ -171,8 +189,13 @@ protected virtual HashAlgorithmName GetHashAlgorithmName(string algorithm) private AsymmetricAdapter CreateAsymmetricAdapter() { - var hashAlgoritmName = GetHashAlgorithmName(Algorithm); - return new AsymmetricAdapter(Key, Algorithm, _cryptoProviderFactory.CreateHashAlgorithm(hashAlgoritmName), hashAlgoritmName, WillCreateSignatures); + HashAlgorithmName hashAlgorithmName = GetHashAlgorithmName(Algorithm); + return new AsymmetricAdapter( + Key, + Algorithm, + _cryptoProviderFactory.CreateHashAlgorithm(hashAlgorithmName), + hashAlgorithmName, + WillCreateSignatures); } internal bool ValidKeySize() @@ -188,7 +211,10 @@ internal bool ValidKeySize() #if NET6_0_OR_GREATER /// - public override bool Sign(ReadOnlySpan input, Span signature, out int bytesWritten) + public override bool Sign( + ReadOnlySpan input, + Span signature, + out int bytesWritten) { if (input.Length == 0) throw LogHelper.LogArgumentNullException(nameof(input)); @@ -219,12 +245,14 @@ public override bool Sign(ReadOnlySpan input, Span signature, out in #endif /// - /// Produces a signature over the 'input' using the and algorithm passed to . + /// Produces a signature over the 'input' using the and algorithm passed + /// to . /// /// The bytes to be signed. /// A signature over the input. /// Thrown if is null or has length of 0. - /// Thrown If has been called. + /// Thrown if + /// has been called. /// Sign is thread safe. public override byte[] Sign(byte[] input) { @@ -317,23 +345,41 @@ public virtual void ValidateAsymmetricSecurityKeySize(SecurityKey key, string al if (convertedSecurityKey is AsymmetricSecurityKey convertedAsymmetricKey) keySize = convertedAsymmetricKey.KeySize; else if (convertedSecurityKey is SymmetricSecurityKey) - throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10704, key))); + throw LogHelper.LogExceptionMessage( + new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10704, key))); } else { - throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10704, key))); + throw LogHelper.LogExceptionMessage( + new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10704, key))); } if (willCreateSignatures) { if (MinimumAsymmetricKeySizeInBitsForSigningMap.ContainsKey(algorithm) && keySize < MinimumAsymmetricKeySizeInBitsForSigningMap[algorithm]) - throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(key), LogHelper.FormatInvariant(LogMessages.IDX10630, key, LogHelper.MarkAsNonPII(MinimumAsymmetricKeySizeInBitsForSigningMap[algorithm]), LogHelper.MarkAsNonPII(keySize)))); + throw LogHelper.LogExceptionMessage( + new ArgumentOutOfRangeException( + nameof(key), + LogHelper.FormatInvariant( + LogMessages.IDX10630, + key, + LogHelper.MarkAsNonPII( + MinimumAsymmetricKeySizeInBitsForSigningMap[algorithm]), + LogHelper.MarkAsNonPII(keySize)))); } else if (MinimumAsymmetricKeySizeInBitsForVerifyingMap.ContainsKey(algorithm) && keySize < MinimumAsymmetricKeySizeInBitsForVerifyingMap[algorithm]) { - throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(key), LogHelper.FormatInvariant(LogMessages.IDX10631, key, LogHelper.MarkAsNonPII(MinimumAsymmetricKeySizeInBitsForVerifyingMap[algorithm]), LogHelper.MarkAsNonPII(keySize)))); + throw LogHelper.LogExceptionMessage( + new ArgumentOutOfRangeException( + nameof(key), + LogHelper.FormatInvariant( + LogMessages.IDX10631, + key, + LogHelper.MarkAsNonPII( + MinimumAsymmetricKeySizeInBitsForVerifyingMap[algorithm]), + LogHelper.MarkAsNonPII(keySize)))); } } @@ -386,7 +432,13 @@ public override bool Verify(byte[] input, byte[] signature) } /// - public override bool Verify(byte[] input, int inputOffset, int inputLength, byte[] signature, int signatureOffset, int signatureLength) + public override bool Verify( + byte[] input, + int inputOffset, + int inputLength, + byte[] signature, + int signatureOffset, + int signatureLength) { if (input == null || input.Length == 0) throw LogHelper.LogArgumentNullException(nameof(input)); @@ -460,7 +512,7 @@ public override bool Verify(byte[] input, int inputOffset, int inputLength, byte } else { - // AsymetricAdapter.Verify could do this. + // AsymmetricAdapter.Verify could do this. // Having the logic here, handles EC and RSA. We can revisit when we start using spans in 3.1+. byte[] signatureBytes = new byte[signatureLength]; Array.Copy(signature, 0, signatureBytes, 0, signatureLength); @@ -490,7 +542,7 @@ protected override void Dispose(bool disposing) _disposed = true; if (disposing) { - foreach (var item in _asymmetricAdapterObjectPool.Items) + foreach (DisposableObjectPool.Element item in _asymmetricAdapterObjectPool.Items) item.Value?.Dispose(); CryptoProviderCache?.TryRemove(this); diff --git a/src/Microsoft.IdentityModel.Tokens/CryptoProviderFactory.cs b/src/Microsoft.IdentityModel.Tokens/CryptoProviderFactory.cs index bdbe960b47..850f2d5657 100644 --- a/src/Microsoft.IdentityModel.Tokens/CryptoProviderFactory.cs +++ b/src/Microsoft.IdentityModel.Tokens/CryptoProviderFactory.cs @@ -45,7 +45,14 @@ public static CryptoProviderFactory Default public static int DefaultSignatureProviderObjectPoolCacheSize { get => _defaultSignatureProviderObjectPoolCacheSize; - set => _defaultSignatureProviderObjectPoolCacheSize = value > 0 ? value : throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(value), LogHelper.FormatInvariant(LogMessages.IDX10698, LogHelper.MarkAsNonPII(value)))); + set => _defaultSignatureProviderObjectPoolCacheSize = value > 0 + ? value + : throw LogHelper.LogExceptionMessage( + new ArgumentOutOfRangeException( + nameof(value), + LogHelper.FormatInvariant( + LogMessages.IDX10698, + LogHelper.MarkAsNonPII(value)))); } /// @@ -96,8 +103,9 @@ public CryptoProviderFactory(CryptoProviderFactory other) /// /// Extensibility point for creating custom cryptographic operators. /// - /// By default, if set, will be called before creating cryptographic operators. - /// If true is returned, then will be called. The will throw if the + /// By default, if set, will be called before + /// creating cryptographic operators. If true is returned, then will be called. + /// The will throw if the /// Cryptographic operator returned is not of the correct type. public ICryptoProvider CustomCryptoProvider { get; set; } @@ -114,23 +122,33 @@ public int SignatureProviderObjectPoolCacheSize { get => _signatureProviderObjectPoolCacheSize; - set => _signatureProviderObjectPoolCacheSize = value > 0 ? value : throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(value), LogHelper.FormatInvariant(LogMessages.IDX10698, LogHelper.MarkAsNonPII(value)))); + set => _signatureProviderObjectPoolCacheSize = value > 0 + ? value + : throw LogHelper.LogExceptionMessage( + new ArgumentOutOfRangeException( + nameof(value), + LogHelper.FormatInvariant( + LogMessages.IDX10698, + LogHelper.MarkAsNonPII(value)))); } /// - /// Creates an instance of for a specific and . + /// Creates an instance of for a specific + /// and . /// /// The to use. /// The algorithm to use. /// Thrown if is null. /// Thrown if is null or empty. - /// Thrown if the combination of and is not supported. - /// Thrown if the type returned by is not assignable to . + /// Thrown if the combination of and + /// is not supported. + /// Thrown if the type returned by + /// is not assignable to . /// - /// If is set and returns true, - /// is called to obtain the . + /// If is set and + /// returns true, is called to obtain the . /// - /// Once done with the , call . + /// When you are finished with the , call . /// /// An instance of . public virtual AuthenticatedEncryptionProvider CreateAuthenticatedEncryptionProvider(SecurityKey key, string algorithm) @@ -145,7 +163,13 @@ public virtual AuthenticatedEncryptionProvider CreateAuthenticatedEncryptionProv { var cryptoProvider = CustomCryptoProvider.Create(algorithm, key) as AuthenticatedEncryptionProvider; if (cryptoProvider == null) - throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(LogMessages.IDX10646, LogHelper.MarkAsNonPII(algorithm), key, LogHelper.MarkAsNonPII(typeof(AuthenticatedEncryptionProvider))))); + throw LogHelper.LogExceptionMessage( + new InvalidOperationException( + LogHelper.FormatInvariant( + LogMessages.IDX10646, + LogHelper.MarkAsNonPII(algorithm), + key, + LogHelper.MarkAsNonPII(typeof(AuthenticatedEncryptionProvider))))); return cryptoProvider; } @@ -153,7 +177,12 @@ public virtual AuthenticatedEncryptionProvider CreateAuthenticatedEncryptionProv if (SupportedAlgorithms.IsSupportedEncryptionAlgorithm(algorithm, key)) return new AuthenticatedEncryptionProvider(key, algorithm); - throw LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(LogMessages.IDX10652, LogHelper.MarkAsNonPII(algorithm)), nameof(algorithm))); + throw LogHelper.LogExceptionMessage( + new ArgumentException( + LogHelper.FormatInvariant( + LogMessages.IDX10652, + LogHelper.MarkAsNonPII(algorithm)), + nameof(algorithm))); } /// @@ -163,13 +192,15 @@ public virtual AuthenticatedEncryptionProvider CreateAuthenticatedEncryptionProv /// The algorithm to use. /// Thrown if is null. /// Thrown if is null or empty. - /// Thrown if the combination of and is not supported. - /// Thrown if the type returned by is not assignable to . + /// Thrown if the combination of and + /// is not supported. + /// Thrown if the type returned by + /// is not assignable to . /// - /// If is set and returns true, - /// is called to obtain the . + /// If is set and + /// returns true, is called to obtain the . /// - /// Once done with the , call . + /// When you are finished with the , call . /// /// An instance of . public virtual KeyWrapProvider CreateKeyWrapProvider(SecurityKey key, string algorithm) @@ -184,13 +215,15 @@ public virtual KeyWrapProvider CreateKeyWrapProvider(SecurityKey key, string alg /// The algorithm to use. /// Thrown if is null. /// Thrown if is null or empty. - /// Thrown if the combination of and is not supported. - /// Thrown if the type returned by is not assignable to . + /// Thrown if the combination of and + /// is not supported. + /// Thrown if the type returned by + /// is not assignable to . /// - /// If is set and returns true, - /// is called to obtain the . + /// If is set and + /// returns true, is called to obtain the . /// - /// Once done with the , call . + /// When you are finished with the , call . /// /// An instance of . public virtual KeyWrapProvider CreateKeyWrapProviderForUnwrap(SecurityKey key, string algorithm) @@ -209,7 +242,13 @@ private KeyWrapProvider CreateKeyWrapProvider(SecurityKey key, string algorithm, if (CustomCryptoProvider != null && CustomCryptoProvider.IsSupportedAlgorithm(algorithm, key, willUnwrap)) { if (!(CustomCryptoProvider.Create(algorithm, key, willUnwrap) is KeyWrapProvider keyWrapProvider)) - throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(LogMessages.IDX10646, LogHelper.MarkAsNonPII(algorithm), key, LogHelper.MarkAsNonPII(typeof(SignatureProvider))))); + throw LogHelper.LogExceptionMessage( + new InvalidOperationException( + LogHelper.FormatInvariant( + LogMessages.IDX10646, + LogHelper.MarkAsNonPII(algorithm), + key, + LogHelper.MarkAsNonPII(typeof(SignatureProvider))))); return keyWrapProvider; } @@ -220,7 +259,12 @@ private KeyWrapProvider CreateKeyWrapProvider(SecurityKey key, string algorithm, if (SupportedAlgorithms.IsSupportedSymmetricKeyWrap(algorithm, key)) return new SymmetricKeyWrapProvider(key, algorithm); - throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10661, LogHelper.MarkAsNonPII(algorithm), key))); + throw LogHelper.LogExceptionMessage( + new NotSupportedException( + LogHelper.FormatInvariant( + LogMessages.IDX10661, + LogHelper.MarkAsNonPII(algorithm), + key))); } /// @@ -231,14 +275,16 @@ private KeyWrapProvider CreateKeyWrapProvider(SecurityKey key, string algorithm, /// Thrown if is null. /// Thrown if is null or empty. /// Thrown if is too small. - /// Thrown if is not assignable from or . + /// Thrown if is not assignable from + /// or . /// Thrown if the key or algorithm combination is not supported. - /// Thrown if the type returned by is not assignable to . + /// Thrown if the type returned by + /// is not assignable to . /// /// AsymmetricSignatureProviders require access to a PrivateKey for signing. - /// Once done with the , call . - /// If is set and returns true, - /// is called to obtain the . + /// When you are finished with the , call . + /// If is set and + /// returns true, is called to obtain the . /// /// /// A instance that can be used to create a signature. @@ -256,12 +302,15 @@ public virtual SignatureProvider CreateForSigning(SecurityKey key, string algori /// Thrown if is null. /// Thrown if is null or empty. /// Thrown if is too small. - /// Thrown if is not assignable from or . - /// Thrown if the combination of and is not supported. - /// Thrown if the type returned by is not assignable to . + /// Thrown if is not assignable from + /// or . + /// Thrown if the combination of and + /// is not supported. + /// Thrown if the type returned by + /// is not assignable to . /// /// AsymmetricSignatureProviders require access to a PrivateKey for signing. - /// Once done with the , call . + /// When you are finished with the , call . /// If is set and returns true, /// is called to obtain the . /// @@ -280,16 +329,19 @@ public virtual SignatureProvider CreateForSigning(SecurityKey key, string algori /// Thrown if is null. /// Thrown if is null or empty. /// Thrown if is too small. - /// Thrown if is not assignable from or . + /// Thrown if is not assignable from + /// or . /// Thrown if the combination of and is not supported. - /// Thrown if the type returned by is not assignable to . + /// Thrown if the type returned by + /// is not assignable to . /// - /// Once done with the , call . + /// When you are finished with the , call . /// If is set and returns true, /// is called to obtain the . /// /// - /// A instance that can be used to validate signatures using the and algorithm. + /// A instance that can be used to validate signatures using the + /// and algorithm. public virtual SignatureProvider CreateForVerifying(SecurityKey key, string algorithm) { return CreateForVerifying(key, algorithm, CacheSignatureProviders); @@ -304,11 +356,13 @@ public virtual SignatureProvider CreateForVerifying(SecurityKey key, string algo /// Thrown if is null. /// Thrown if is null or empty. /// Thrown if is too small. - /// Thrown if is not assignable from or . + /// Thrown if is not assignable from + /// or . /// Thrown if the combination of and is not supported. - /// Thrown if the type returned by is not assignable to . + /// Thrown if the type returned by + /// is not assignable to . /// - /// Once done with the , call . + /// When you are finished with the , call . /// If is set and returns true, /// is called to obtain the . /// @@ -324,10 +378,11 @@ public virtual SignatureProvider CreateForVerifying(SecurityKey key, string algo /// /// The name of the hash algorithm to create. /// Thrown if is null or empty. - /// Thrown if returns a type that is not assignable to . + /// Thrown if + /// returns a type that is not assignable to . /// Thrown if is not supported. /// - /// Once done with the , call . + /// When you are finished with the , call . /// If is set and returns true, /// is called to obtain the . /// @@ -338,7 +393,12 @@ public virtual HashAlgorithm CreateHashAlgorithm(HashAlgorithmName algorithm) if (CustomCryptoProvider != null && CustomCryptoProvider.IsSupportedAlgorithm(algorithm.Name)) { if (!(CustomCryptoProvider.Create(algorithm.Name) is HashAlgorithm hashAlgorithm)) - throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(LogMessages.IDX10647, LogHelper.MarkAsNonPII(algorithm), LogHelper.MarkAsNonPII(typeof(HashAlgorithm))))); + throw LogHelper.LogExceptionMessage( + new InvalidOperationException( + LogHelper.FormatInvariant( + LogMessages.IDX10647, + LogHelper.MarkAsNonPII(algorithm), + LogHelper.MarkAsNonPII(typeof(HashAlgorithm))))); _typeToAlgorithmMap[hashAlgorithm.GetType().ToString()] = algorithm.Name; return hashAlgorithm; @@ -353,7 +413,11 @@ public virtual HashAlgorithm CreateHashAlgorithm(HashAlgorithmName algorithm) if (algorithm == HashAlgorithmName.SHA512) return SHA512.Create(); - throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10640, LogHelper.MarkAsNonPII(algorithm)))); + throw LogHelper.LogExceptionMessage( + new NotSupportedException( + LogHelper.FormatInvariant( + LogMessages.IDX10640, + LogHelper.MarkAsNonPII(algorithm)))); } /// @@ -361,10 +425,11 @@ public virtual HashAlgorithm CreateHashAlgorithm(HashAlgorithmName algorithm) /// /// The name of the hash algorithm to create. /// Thrown if is null or empty. - /// Thrown if returns a type that is not assignable to . + /// Thrown if returns a type that + /// is not assignable to . /// Thrown if is not supported. /// - /// Once done with the , call . + /// When you are finished with the , call . /// If is set and returns true, /// is called to obtain the . /// @@ -378,7 +443,12 @@ public virtual HashAlgorithm CreateHashAlgorithm(string algorithm) if (CustomCryptoProvider != null && CustomCryptoProvider.IsSupportedAlgorithm(algorithm)) { if (!(CustomCryptoProvider.Create(algorithm) is HashAlgorithm hashAlgorithm)) - throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(LogMessages.IDX10647, LogHelper.MarkAsNonPII(algorithm), LogHelper.MarkAsNonPII(typeof(HashAlgorithm))))); + throw LogHelper.LogExceptionMessage( + new InvalidOperationException( + LogHelper.FormatInvariant( + LogMessages.IDX10647, + LogHelper.MarkAsNonPII(algorithm), + LogHelper.MarkAsNonPII(typeof(HashAlgorithm))))); _typeToAlgorithmMap[hashAlgorithm.GetType().ToString()] = algorithm; @@ -400,7 +470,11 @@ public virtual HashAlgorithm CreateHashAlgorithm(string algorithm) return SHA512.Create(); } - throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10640, LogHelper.MarkAsNonPII(algorithm)))); + throw LogHelper.LogExceptionMessage( + new NotSupportedException( + LogHelper.FormatInvariant( + LogMessages.IDX10640, + LogHelper.MarkAsNonPII(algorithm)))); } /// @@ -410,10 +484,11 @@ public virtual HashAlgorithm CreateHashAlgorithm(string algorithm) /// The name of the keyed hash algorithm to create. /// Thrown if is null. /// Thrown if is null or empty. - /// Thrown if returns a type that is not assignable to . + /// Thrown if returns a type that + /// is not assignable to . /// Thrown if is not supported. /// - /// Once done with the , call . + /// When you are finished with the , call . /// If is set and returns true, /// is called to obtain the . /// @@ -485,11 +560,18 @@ public virtual KeyedHashAlgorithm CreateKeyedHashAlgorithm(byte[] keyBytes, stri } default: - throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10666, LogHelper.MarkAsNonPII(algorithm)))); + throw LogHelper.LogExceptionMessage( + new NotSupportedException( + LogHelper.FormatInvariant( + LogMessages.IDX10666, + LogHelper.MarkAsNonPII(algorithm)))); } } - private static void ValidateKeySize(byte[] keyBytes, string algorithm, int expectedNumberOfBytes) + private static void ValidateKeySize( + byte[] keyBytes, + string algorithm, + int expectedNumberOfBytes) { if (keyBytes.Length < expectedNumberOfBytes) throw LogHelper.LogExceptionMessage( @@ -501,7 +583,11 @@ private static void ValidateKeySize(byte[] keyBytes, string algorithm, int expec LogHelper.MarkAsNonPII(keyBytes.Length * 8)))); } - private SignatureProvider CreateSignatureProvider(SecurityKey key, string algorithm, bool willCreateSignatures, bool cacheProvider) + private SignatureProvider CreateSignatureProvider( + SecurityKey key, + string algorithm, + bool willCreateSignatures, + bool cacheProvider) { if (key == null) throw LogHelper.LogArgumentNullException(nameof(key)); @@ -562,7 +648,13 @@ private SignatureProvider CreateSignatureProvider(SecurityKey key, string algori } catch (Exception ex) { - throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(LogMessages.IDX10694, key, ex), ex)); + throw LogHelper.LogExceptionMessage( + new InvalidOperationException( + LogHelper.FormatInvariant( + LogMessages.IDX10694, + key, + ex), + ex)); } } else if (key is SymmetricSecurityKey) @@ -584,14 +676,24 @@ private SignatureProvider CreateSignatureProvider(SecurityKey key, string algori if (CacheSignatureProviders && cacheProvider) { - if (CryptoProviderCache.TryGetSignatureProvider(key, algorithm, typeofSignatureProvider, willCreateSignatures, out signatureProvider)) + if (CryptoProviderCache.TryGetSignatureProvider( + key, + algorithm, + typeofSignatureProvider, + willCreateSignatures, + out signatureProvider)) { signatureProvider.AddRef(); return signatureProvider; } if (!IsSupportedAlgorithm(algorithm, key)) - throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10634, LogHelper.MarkAsNonPII(algorithm), key))); + throw LogHelper.LogExceptionMessage( + new NotSupportedException( + LogHelper.FormatInvariant( + LogMessages.IDX10634, + LogHelper.MarkAsNonPII(algorithm), + key))); if (createAsymmetric) signatureProvider = new AsymmetricSignatureProvider(key, algorithm, willCreateSignatures, this); @@ -611,7 +713,12 @@ private SignatureProvider CreateSignatureProvider(SecurityKey key, string algori else { if (!IsSupportedAlgorithm(algorithm, key)) - throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10634, LogHelper.MarkAsNonPII(algorithm), key))); + throw LogHelper.LogExceptionMessage( + new NotSupportedException( + LogHelper.FormatInvariant( + LogMessages.IDX10634, + LogHelper.MarkAsNonPII(algorithm), + key))); if (createAsymmetric) { @@ -701,7 +808,9 @@ public virtual void ReleaseHashAlgorithm(HashAlgorithm hashAlgorithm) { if (hashAlgorithm == null) throw LogHelper.LogArgumentNullException(nameof(hashAlgorithm)); - else if (CustomCryptoProvider != null && _typeToAlgorithmMap.TryGetValue(hashAlgorithm.GetType().ToString(), out var algorithm) && CustomCryptoProvider.IsSupportedAlgorithm(algorithm)) + else if (CustomCryptoProvider != null + && _typeToAlgorithmMap.TryGetValue(hashAlgorithm.GetType().ToString(), out string algorithm) + && CustomCryptoProvider.IsSupportedAlgorithm(algorithm)) CustomCryptoProvider.Release(hashAlgorithm); else hashAlgorithm.Dispose(); diff --git a/src/Microsoft.IdentityModel.Tokens/SignatureProvider.cs b/src/Microsoft.IdentityModel.Tokens/SignatureProvider.cs index 4f011c9c97..f6423c4870 100644 --- a/src/Microsoft.IdentityModel.Tokens/SignatureProvider.cs +++ b/src/Microsoft.IdentityModel.Tokens/SignatureProvider.cs @@ -147,11 +147,11 @@ public virtual bool Sign(ReadOnlySpan data, Span destination, out in /// Verifies that a signature created over the 'input' matches the signature. Using and 'algorithm' passed to . /// /// The bytes to verify. - /// offset in to input bytes to caculate hash. + /// offset in to input bytes to calculate hash. /// number of bytes of signature to use. /// signature to compare against. /// offset into signature array. - /// how many bytes to verfiy. + /// how many bytes to verify. /// true if computed signature matches the signature parameter, false otherwise. /// 'input' is null. /// 'signature' is null. diff --git a/src/Microsoft.IdentityModel.Tokens/SymmetricSignatureProvider.cs b/src/Microsoft.IdentityModel.Tokens/SymmetricSignatureProvider.cs index bcc4f4a198..72f12a05a8 100644 --- a/src/Microsoft.IdentityModel.Tokens/SymmetricSignatureProvider.cs +++ b/src/Microsoft.IdentityModel.Tokens/SymmetricSignatureProvider.cs @@ -73,13 +73,29 @@ public SymmetricSignatureProvider(SecurityKey key, string algorithm, bool willCr : base(key, algorithm) { if (!key.CryptoProviderFactory.IsSupportedAlgorithm(algorithm, key)) - throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10634, LogHelper.MarkAsNonPII((algorithm)), key))); + throw LogHelper.LogExceptionMessage( + new NotSupportedException( + LogHelper.FormatInvariant( + LogMessages.IDX10634, + LogHelper.MarkAsNonPII((algorithm)), key))); if (key.KeySize < MinimumSymmetricKeySizeInBits) - throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(key), LogHelper.FormatInvariant(LogMessages.IDX10653, LogHelper.MarkAsNonPII((algorithm)), LogHelper.MarkAsNonPII(MinimumSymmetricKeySizeInBits), key, LogHelper.MarkAsNonPII(key.KeySize)))); + throw LogHelper.LogExceptionMessage( + new ArgumentOutOfRangeException( + nameof(key), + LogHelper.FormatInvariant( + LogMessages.IDX10653, + LogHelper.MarkAsNonPII( + (algorithm)), + LogHelper.MarkAsNonPII( + MinimumSymmetricKeySizeInBits), + key, + LogHelper.MarkAsNonPII(key.KeySize)))); WillCreateSignatures = willCreateSignatures; - _keyedHashObjectPool = new DisposableObjectPool(CreateKeyedHashAlgorithm, key.CryptoProviderFactory.SignatureProviderObjectPoolCacheSize); + _keyedHashObjectPool = new DisposableObjectPool( + CreateKeyedHashAlgorithm, + key.CryptoProviderFactory.SignatureProviderObjectPoolCacheSize); } /// @@ -95,7 +111,12 @@ public int MinimumSymmetricKeySizeInBits set { if (value < DefaultMinimumSymmetricKeySizeInBits) - throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(value), LogHelper.FormatInvariant(LogMessages.IDX10628, LogHelper.MarkAsNonPII(DefaultMinimumSymmetricKeySizeInBits)))); + throw LogHelper.LogExceptionMessage( + new ArgumentOutOfRangeException( + nameof(value), + LogHelper.FormatInvariant( + LogMessages.IDX10628, + LogHelper.MarkAsNonPII(DefaultMinimumSymmetricKeySizeInBits)))); _minimumSymmetricKeySizeInBits = value; } @@ -130,7 +151,7 @@ protected virtual byte[] GetKeyBytes(SecurityKey key) /// Returns a . /// This method is called just before a cryptographic operation. /// This provides the opportunity to obtain the from an object pool. - /// If this method is overridden, it is importont to override + /// If this method is overridden, it is important to override /// if custom releasing of the is desired. /// /// The hash algorithm to use to create the hash value. @@ -164,14 +185,16 @@ protected virtual void ReleaseKeyedHashAlgorithm(KeyedHashAlgorithm keyedHashAlg } /// - /// Produces a signature over the 'input' using the and 'algorithm' passed to . + /// Produces a signature over the 'input' using the and 'algorithm' + /// passed to . /// /// The bytes to sign. /// Signed bytes /// 'input' is null. /// 'input.Length' == 0. /// has been called. - /// is null. This can occur if a derived type deletes it or does not create it. + /// is null. + /// This can occur if a derived type deletes it or does not create it. /// Sign is thread safe. public override byte[] Sign(byte[] input) { @@ -268,7 +291,8 @@ public override byte[] Sign(byte[] input, int offset, int count) } /// - /// Verifies that a signature created over the 'input' matches the signature. Using and 'algorithm' passed to . + /// Verifies that a signature created over the 'input' matches the signature. Using and 'algorithm' + /// passed to . /// /// The bytes to verify. /// signature to compare against. @@ -278,7 +302,8 @@ public override byte[] Sign(byte[] input, int offset, int count) /// 'input.Length' == 0. /// 'signature.Length' == 0. /// has been called. - /// If the internal is null. This can occur if a derived type deletes it or does not create it. + /// If the internal is null. + /// This can occur if a derived type deletes it or does not create it. /// Verify is thread safe. public override bool Verify(byte[] input, byte[] signature) { @@ -315,7 +340,8 @@ public override bool Verify(byte[] input, byte[] signature) } /// - /// Verifies that a signature created over the 'input' matches the signature. Using and 'algorithm' passed to . + /// Verifies that a signature created over the 'input' matches the signature. Using and 'algorithm' + /// passed to . /// /// The bytes to verify. /// signature to compare against. @@ -327,7 +353,8 @@ public override bool Verify(byte[] input, byte[] signature) /// 'signature.Length' == 0. /// 'length < 1' /// has been called. - /// If the internal is null. This can occur if a derived type deletes it or does not create it. + /// If the internal is null. + /// This can occur if a derived type deletes it or does not create it. public bool Verify(byte[] input, byte[] signature, int length) { if (input == null) @@ -343,22 +370,31 @@ public override bool Verify(byte[] input, int inputOffset, int inputLength, byte } /// - /// This internal method is called from the AuthenticatedEncryptionProvider which passes in the algorithm that defines the size expected for the signature. + /// This internal method is called from the AuthenticatedEncryptionProvider which passes in the algorithm that defines + /// the size expected for the signature. /// The reason is the way the AuthenticationTag is validated. - /// For example when "A128CBC-HS256" is specified, SHA256 will used to create the HMAC and 32 bytes will be generated, but only the first 16 will be validated. + /// For example when "A128CBC-HS256" is specified, SHA256 will used to create the HMAC and 32 bytes will be generated, + /// but only the first 16 will be validated. /// /// The bytes to verify. - /// offset in to input bytes to caculate hash. + /// offset into the input bytes to calculate the hash. /// number of bytes of signature to use. /// signature to compare against. /// offset into signature array. - /// how many bytes to verfiy. + /// how many bytes to verify. /// algorithm passed by AuthenticatedEncryptionProvider. /// true if computed signature matches the signature parameter, false otherwise. #if NET6_0_OR_GREATER [SkipLocalsInit] #endif - internal bool Verify(byte[] input, int inputOffset, int inputLength, byte[] signature, int signatureOffset, int signatureLength, string algorithm) + internal bool Verify( + byte[] input, + int inputOffset, + int inputLength, + byte[] signature, + int signatureOffset, + int signatureLength, + string algorithm) { if (input == null || input.Length == 0) throw LogHelper.LogArgumentNullException(nameof(input)); @@ -448,7 +484,8 @@ internal bool Verify(byte[] input, int inputOffset, int inputLength, byte[] sign scoped Span hash; #if NET6_0_OR_GREATER - hash = stackalloc byte[keyedHashAlgorithm.HashSize / 8]; // only known algorithms are used, all of which have a small enough hash size to stackalloc + // only known algorithms are used, all of which have a small enough hash size to stackalloc + hash = stackalloc byte[keyedHashAlgorithm.HashSize / 8]; keyedHashAlgorithm.TryComputeHash(input.AsSpan(inputOffset, inputLength), hash, out int bytesWritten); Debug.Assert(bytesWritten == hash.Length); #else