OaepSHA1WithRSA.cs
2.32 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Security.Cryptography;
using System.Text;
namespace NCC.Core.Pay.Security
{
public static class OaepSHA1WithRSA
{
public static string Encrypt(string data, string publicKey)
{
if (string.IsNullOrEmpty(data))
{
throw new ArgumentNullException(nameof(data));
}
if (string.IsNullOrEmpty(publicKey))
{
throw new ArgumentNullException(nameof(publicKey));
}
using (var rsa = RSA.Create())
{
rsa.ImportRSAPublicKey(Convert.FromBase64String(publicKey), out var _);
return Convert.ToBase64String(rsa.Encrypt(Encoding.UTF8.GetBytes(data), RSAEncryptionPadding.OaepSHA1));
}
}
public static string Decrypt(string data, string privateKey)
{
if (string.IsNullOrEmpty(data))
{
throw new ArgumentNullException(nameof(data));
}
if (string.IsNullOrEmpty(privateKey))
{
throw new ArgumentNullException(nameof(privateKey));
}
using (var rsa = RSA.Create())
{
rsa.ImportRSAPrivateKey(Convert.FromBase64String(privateKey), out var _);
return Encoding.UTF8.GetString(rsa.Decrypt(Convert.FromBase64String(data), RSAEncryptionPadding.OaepSHA1));
}
}
public static string Encrypt(RSA rsa, string data)
{
if (rsa == null)
{
throw new ArgumentNullException(nameof(rsa));
}
if (string.IsNullOrEmpty(data))
{
throw new ArgumentNullException(nameof(data));
}
return Convert.ToBase64String(rsa.Encrypt(Encoding.UTF8.GetBytes(data), RSAEncryptionPadding.OaepSHA1));
}
public static string Decrypt(RSA rsa, string data)
{
if (rsa == null)
{
throw new ArgumentNullException(nameof(rsa));
}
if (string.IsNullOrEmpty(data))
{
throw new ArgumentNullException(nameof(data));
}
return Encoding.UTF8.GetString(rsa.Decrypt(Convert.FromBase64String(data), RSAEncryptionPadding.OaepSHA1));
}
}
}