-
Notifications
You must be signed in to change notification settings - Fork 0
/
SignatureRSA.cs
58 lines (51 loc) · 1.69 KB
/
SignatureRSA.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System.Security.Cryptography;
using System.Text;
public class SignatureRSA
{
public static string SignData(string data, RSAParameters privateKey)
{
byte[] signedBytes;
var toEncrypt = Encoding.Unicode.GetBytes(data);
var rsa = new RSACryptoServiceProvider(2048);
try
{
//// Import the private key used for signing the message
rsa.ImportParameters(privateKey);
//// Sign the data, using SHA512 as the hashing algorithm
signedBytes = rsa.SignData(toEncrypt, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return "error";
}
finally
{
//// Set the keycontainer to be cleared when rsa is garbage collected.
rsa.PersistKeyInCsp = false;
}
//// Convert the a base64 string before returning
return Convert.ToBase64String(signedBytes);
}
public static bool VerifyData(string data, string signedData, RSAParameters publicKey)
{
var success = false;
var bytesToVerify = Encoding.Unicode.GetBytes(data);
var signedBytes = Encoding.Unicode.GetBytes(signedData);
var rsa = new RSACryptoServiceProvider(2048);
try
{
rsa.ImportParameters(publicKey);
success = rsa.VerifyData(bytesToVerify, CryptoConfig.MapNameToOID("SHA512")!, signedBytes);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
finally
{
rsa.PersistKeyInCsp = false;
}
return success;
}
}