1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4 
5 using Internal.Cryptography;
6 
7 namespace System.Security.Cryptography
8 {
9     public class RSAPKCS1SignatureDeformatter : AsymmetricSignatureDeformatter
10     {
11         private RSA _rsaKey;
12         private string _algName;
13 
RSAPKCS1SignatureDeformatter()14         public RSAPKCS1SignatureDeformatter() { }
RSAPKCS1SignatureDeformatter(AsymmetricAlgorithm key)15         public RSAPKCS1SignatureDeformatter(AsymmetricAlgorithm key)
16         {
17             if (key == null)
18                 throw new ArgumentNullException(nameof(key));
19 
20             _rsaKey = (RSA)key;
21         }
22 
SetKey(AsymmetricAlgorithm key)23         public override void SetKey(AsymmetricAlgorithm key)
24         {
25             if (key == null)
26                 throw new ArgumentNullException(nameof(key));
27 
28             _rsaKey = (RSA)key;
29         }
30 
SetHashAlgorithm(string strName)31         public override void SetHashAlgorithm(string strName)
32         {
33             try
34             {
35                 // Verify the name
36                 Oid.FromFriendlyName(strName, OidGroup.HashAlgorithm);
37 
38                 // Uppercase known names as required for BCrypt
39                 _algName = HashAlgorithmNames.ToUpper(strName);
40             }
41             catch (CryptographicException)
42             {
43                 // For desktop compat, exception is deferred until VerifySignature
44                 _algName = null;
45             }
46         }
47 
VerifySignature(byte[] rgbHash, byte[] rgbSignature)48         public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature)
49         {
50             if (rgbHash == null)
51                 throw new ArgumentNullException(nameof(rgbHash));
52             if (rgbSignature == null)
53                 throw new ArgumentNullException(nameof(rgbSignature));
54             if (_algName == null)
55                 throw new CryptographicUnexpectedOperationException(SR.Cryptography_MissingOID);
56             if (_rsaKey == null)
57                 throw new CryptographicUnexpectedOperationException(SR.Cryptography_MissingKey);
58 
59             return _rsaKey.VerifyHash(rgbHash, rgbSignature, new HashAlgorithmName(_algName), RSASignaturePadding.Pkcs1);
60         }
61     }
62 }
63