|
|
|
using System.Security.Cryptography;
|
|
|
|
using System.Text;
|
|
|
|
using System.IO;
|
|
|
|
using System;
|
|
|
|
|
|
|
|
class PrivateData
|
|
|
|
{
|
|
|
|
private RSACryptoServiceProvider RSA;
|
|
|
|
private string keyFile = "KeyInfo.xml";
|
|
|
|
|
|
|
|
public PrivateData()
|
|
|
|
{
|
|
|
|
if (File.Exists(keyFile)) {
|
|
|
|
RSA = new RSACryptoServiceProvider();
|
|
|
|
RSA.FromXmlString(File.ReadAllText(keyFile));
|
|
|
|
} else {
|
|
|
|
RSA = new RSACryptoServiceProvider(4096);
|
|
|
|
string KeyInfo = RSA.ToXmlString(true);
|
|
|
|
File.WriteAllText(keyFile, KeyInfo);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public string EncryptString(string input)
|
|
|
|
{
|
|
|
|
return Encryption(Encoding.UTF8.GetBytes(input), RSA.ExportParameters(false), false);
|
|
|
|
}
|
|
|
|
public string DecryptString(string input)
|
|
|
|
{
|
|
|
|
return Decryption(Convert.FromBase64String(input), RSA.ExportParameters(false), false);
|
|
|
|
}
|
|
|
|
private string Encryption(byte[] Data, RSAParameters RSAKey, bool DoOAEPPadding)
|
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
Console.WriteLine(RSAKey.ToString());
|
|
|
|
byte[] encryptedData;
|
|
|
|
encryptedData = RSA.Encrypt(Data, DoOAEPPadding);
|
|
|
|
|
|
|
|
return Convert.ToBase64String(encryptedData);
|
|
|
|
}
|
|
|
|
catch (CryptographicException e)
|
|
|
|
{
|
|
|
|
Console.WriteLine(e.Message);
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public string Decryption(byte[] Data, RSAParameters RSAKey, bool DoOAEPPadding)
|
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
byte[] decryptedData;
|
|
|
|
decryptedData = RSA.Decrypt(Data, DoOAEPPadding);
|
|
|
|
|
|
|
|
return Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length); ;
|
|
|
|
}
|
|
|
|
catch (CryptographicException e)
|
|
|
|
{
|
|
|
|
Console.WriteLine(e.ToString());
|
|
|
|
return "";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|