@@ -7,27 +7,34 @@ namespace Org.Security.Cryptography
7
7
{
8
8
public static class X509SignatureExtensions
9
9
{
10
- public static byte [ ] CreateSignature ( this X509Certificate2 x509Cert , byte [ ] hash )
10
+ /// <summary>
11
+ /// Signs given messageDigest (hash-value) using X509 PrivateKey and returns the RSA PKCS #1 signature.
12
+ /// </summary>
13
+ public static byte [ ] CreateSignature ( this X509Certificate2 x509Cert , byte [ ] messageDigest )
11
14
{
12
15
if ( null == x509Cert ) throw new ArgumentNullException ( nameof ( x509Cert ) ) ;
13
- if ( null == hash ) throw new ArgumentNullException ( nameof ( hash ) ) ;
16
+ if ( null == messageDigest ) throw new ArgumentNullException ( nameof ( messageDigest ) ) ;
14
17
15
- var asymmetricAlgorithm = x509Cert . GetRsaPrivateKeyAsymmetricAlgorithm ( ) ;
16
- var hashAlgorithmName = InferHashAlgorithm ( hash ) ;
18
+ var asymmetricAlgorithm = x509Cert . GetPrivateKeyAsymmetricAlgorithm ( ) ;
19
+ var hashAlgorithmName = InferHashAlgorithm ( messageDigest ) ;
17
20
18
21
var formatter = new RSAPKCS1SignatureFormatter ( asymmetricAlgorithm ) ;
19
22
formatter . SetHashAlgorithm ( hashAlgorithmName ) ;
20
23
21
- return formatter . CreateSignature ( hash ) ;
24
+ return formatter . CreateSignature ( messageDigest ) ;
22
25
}
23
26
27
+ /// <summary>
28
+ /// Verifies RSA PKCS #1 signature for give messageDigest (hash-value), using X509 PublicKey.
29
+ /// Returns true|false indicating if the signature is valid.
30
+ /// </summary>
24
31
public static bool VerifySignature ( this X509Certificate2 x509Cert , byte [ ] hash , byte [ ] signature )
25
32
{
26
33
if ( null == x509Cert ) throw new ArgumentNullException ( nameof ( x509Cert ) ) ;
27
34
if ( null == hash ) throw new ArgumentNullException ( nameof ( hash ) ) ;
28
35
if ( null == signature ) throw new ArgumentNullException ( nameof ( signature ) ) ;
29
36
30
- var asymmetricAlgorithm = x509Cert . GetRsaPublicKeyAsymmetricAlgorithm ( ) ;
37
+ var asymmetricAlgorithm = x509Cert . GetPublicKeyAsymmetricAlgorithm ( ) ;
31
38
var hashAlgorithmName = InferHashAlgorithm ( hash ) ;
32
39
33
40
var formatter = new RSAPKCS1SignatureDeformatter ( asymmetricAlgorithm ) ;
@@ -55,7 +62,7 @@ static string InferHashAlgorithm(byte[] hash)
55
62
case 48 : return HashAlgorithmName . SHA384 . Name ;
56
63
case 64 : return HashAlgorithmName . SHA512 . Name ;
57
64
default :
58
- throw new Exception ( $ "Can't infer Hash algorithm. Unexpected hash length { hash . Length : #,0} bytes. Expecting 16|20|32|48|64 bytes.") ;
65
+ throw new Exception ( $ "Can't infer HashAlgorithm. Unknown hash length { hash . Length : #,0} bytes. Expecting 16|20|32|48|64 bytes.") ;
59
66
}
60
67
}
61
68
}
0 commit comments