-
Notifications
You must be signed in to change notification settings - Fork 15
/
RSAHelper.cs
66 lines (55 loc) · 2.48 KB
/
RSAHelper.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
59
60
61
62
63
64
65
66
using System;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace RSA_Angular_with_.net.Helper
{
public class RsaHelper
{
private readonly RSACryptoServiceProvider _privateKey;
private readonly RSACryptoServiceProvider _publicKey;
public RsaHelper()
{
string public_pem = @"C:\OpenSSL\bin\posvendor.pub.pem";
string private_pem = @"C:\OpenSSL\bin\posvendor.key.pem";
_publicKey = GetPublicKeyFromPemFile(public_pem);
_privateKey = GetPrivateKeyFromPemFile(private_pem);
}
public string Encrypt(string text)
{
var encryptedBytes =_publicKey.Encrypt(Encoding.UTF8.GetBytes(text), false);
return Convert.ToBase64String(encryptedBytes);
}
public string Decrypt(string encrypted)
{
var decryptedBytes = _privateKey.Decrypt(Convert.FromBase64String(encrypted), false);
return Encoding.UTF8.GetString(decryptedBytes, 0, decryptedBytes.Length);
}
private RSACryptoServiceProvider GetPrivateKeyFromPemFile(string filePath)
{
using (TextReader privateKeyTextReader = new StringReader(File.ReadAllText(filePath)))
{
AsymmetricCipherKeyPair readKeyPair = (AsymmetricCipherKeyPair)new PemReader(privateKeyTextReader).ReadObject();
RSAParameters rsaParams = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)readKeyPair.Private);
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
csp.ImportParameters(rsaParams);
return csp;
}
}
private RSACryptoServiceProvider GetPublicKeyFromPemFile(String filePath)
{
using (TextReader publicKeyTextReader = new StringReader(File.ReadAllText(filePath)))
{
RsaKeyParameters publicKeyParam = (RsaKeyParameters)new PemReader(publicKeyTextReader).ReadObject();
RSAParameters rsaParams = DotNetUtilities.ToRSAParameters((RsaKeyParameters)publicKeyParam);
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
csp.ImportParameters(rsaParams);
return csp;
}
}
}
}