update rsa implementation
[GitHub/Stricted/SpeedportHybridControl.git] / SpeedportHybridControl.Implementations / Cryptography.cs
1 using System;
2 using System.Security.Cryptography;
3 using System.Text;
4
5 namespace SpeedportHybridControl.Implementations
6 {
7 public static class Cryptography
8 {
9 private static string GetKeyFromContainer()
10 {
11 // store key in keycontainer, this generates a new key if none exist
12 CspParameters cp = new CspParameters();
13 cp.KeyContainerName = "SpeedportHybridControl";
14 RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, cp);
15 string result = rsa.ToXmlString(true);
16 rsa.Dispose();
17
18 return result;
19 }
20
21 public static string Encrypt(string clearText)
22 {
23 RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
24 byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
25 rsa.FromXmlString(GetKeyFromContainer());
26 string result = Convert.ToBase64String(rsa.Encrypt(clearBytes, true));
27 rsa.Dispose();
28
29 return result;
30 }
31
32 public static string Decrypt(string cipherText)
33 {
34 RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
35 byte[] cipherBytes = Convert.FromBase64String(cipherText);
36 rsa.FromXmlString(GetKeyFromContainer());
37 string result = Encoding.Unicode.GetString(rsa.Decrypt(cipherBytes, true));
38 rsa.Dispose();
39
40 return result;
41 }
42 }
43 }