using System;
using System.Collections;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace Web
{
public class RSA
{
int keySize;
string publicKey;
string privateKey;
string publicKeyFileName;
string privateKeyFileName;
public RSA()
{
keySize = 1024;
publicKeyFileName = "public.pk";
privateKeyFileName = "private.pk";
publicKey = ReadFile(publicKeyFileName);
privateKey = ReadFile(privateKeyFileName);
if (String.IsNullOrEmpty(publicKey) || String.IsNullOrEmpty(privateKey))
{
GenerateKey();
}
}
private void GenerateKey()
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(keySize);
publicKey = RSA.ToXmlString(true);
privateKey = RSA.ToXmlString(false);
if (SaveFile(privateKeyFileName, publicKey))
{
SaveFile(publicKeyFileName, privateKey);
}
}
public string EncryptString(string text)
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(keySize);
RSA.FromXmlString(publicKey);
byte[] bytes = Encoding.UTF32.GetBytes(text);
int maxLength = (keySize / 8) - 42;
int dataLength = bytes.Length;
int iterations = dataLength / maxLength;
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i <= iterations; i++)
{
byte[] tempBytes = new byte[(dataLength - maxLength * i > maxLength) ? maxLength : dataLength - maxLength * i];
Buffer.BlockCopy(bytes, maxLength * i, tempBytes, 0, tempBytes.Length);
byte[] encryptedBytes = RSA.Encrypt(tempBytes, true);
Array.Reverse(encryptedBytes);
stringBuilder.Append(Convert.ToBase64String(encryptedBytes));
}
return stringBuilder.ToString();
}
public string DecryptString(string text)
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(keySize);
RSA.FromXmlString(privateKey);
int base64BlockSize = ((keySize / 8) % 3 != 0) ? (((keySize / 8) / 3) * 4) + 4 : ((keySize / 8) / 3) * 4;
int iterations = text.Length / base64BlockSize;
ArrayList arrayList = new ArrayList();
for (int i = 0; i < iterations; i++)
{
byte[] encryptedBytes = Convert.FromBase64String(text.Substring(base64BlockSize * i, base64BlockSize));
Array.Reverse(encryptedBytes);
arrayList.AddRange(RSA.Decrypt(encryptedBytes, true));
}
return Encoding.UTF32.GetString(arrayList.ToArray(Type.GetType("System.Byte")) as byte[]);
}
private bool SaveFile(string fileName, string text)
{
try
{
string path = HttpContext.Current.Server.MapPath("/" + fileName);
StreamWriter streamWriter = new StreamWriter(path, false);
if (text != null) streamWriter.Write(text);
streamWriter.Close();
return true;
}
catch (Exception ex)
{
throw ex;
}
}
private string ReadFile(string fileName)
{
string text = null;
string path = HttpContext.Current.Server.MapPath("/" + fileName);
if (File.Exists(path))
{
StreamReader streamReader = new StreamReader(path, true);
text = streamReader.ReadToEnd();
streamReader.Close();
}
return text;
}
}
}
(责任编辑:admin)