-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRSAWithXMLKey.cs
80 lines (61 loc) · 2.24 KB
/
RSAWithXMLKey.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
67
68
69
70
using System;
using System.IO;
using System.Security.Cryptography;
namespace Crypto
{
class RSAWithXMLKey
{
private RSAParameters _publicKey;
private RSAParameters _privateKey;
public void AssignKey(string publicKeyPath, string privateKeypath)
{
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp = false;
if (File.Exists(privateKeypath))
{
File.Delete(privateKeypath);
}
if (File.Exists(publicKeyPath))
{
File.Delete(publicKeyPath);
}
var publicKeyFolder = Path.GetDirectoryName(publicKeyPath);
var privateKeyFolder = Path.GetDirectoryName(privateKeypath);
if (!Directory.Exists(publicKeyFolder))
{
Directory.CreateDirectory(publicKeyFolder);
}
if(!Directory.Exists(privateKeyFolder)){
Directory.CreateDirectory(privateKeyFolder);
}
File.WriteAllText(publicKeyFolder,rsa.ToXmlString(false));
File.WriteAllText(privateKeypath,rsa.ToXmlString(true));
this._publicKey = rsa.ExportParameters(false);
this._privateKey = rsa.ExportParameters(true);
}
}
public byte[] EncryptData(string publicKeyPath,byte[] dataToEncrypt)
{
byte[] cipherBytes;
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp = false;
rsa.FromXmlString(File.ReadAllText(publicKeyPath));
cipherBytes = rsa.Encrypt(dataToEncrypt, true);
}
return cipherBytes;
}
public byte[] DecryptData(string privateKeyPath,byte[] dataToDecrypt)
{
byte[] plain;
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp = false;
rsa.FromXmlString(File.ReadAllText(privateKeyPath));
plain = rsa.Decrypt(dataToDecrypt, true);
}
return plain;
}
}
}