您的位置:首页 > 其它

RSA 非对称加密与解密

2008-12-01 15:23 344 查看
private static string Encrypt(string msg, string publickey)
{
ASCIIEncoding enc = new ASCIIEncoding();
byte[] bytes = enc.GetBytes(msg);
int blockSize = 0;
RSACryptoServiceProvider crypt = new RSACryptoServiceProvider();
crypt.FromXmlString(publickey);
if (crypt.KeySize == 1024)
blockSize = 16;
else
blockSize = 8;

MemoryStream ms = new MemoryStream();

byte[] rawblock, encryblock;
for (int i = 0; i < bytes.Length; i += blockSize)
{
if ((bytes.Length - i) > blockSize)
rawblock = new byte[blockSize];
else
rawblock = new byte[bytes.Length - i];
Buffer.BlockCopy(bytes, i, rawblock, 0, rawblock.Length);
encryblock = crypt.Encrypt(rawblock, false);
ms.Write(encryblock, 0, encryblock.Length);
}

ms.Position = 0;
byte[] decode = new byte[ms.Length];
ms.Read(decode, 0, (int)ms.Length);

string decodeinfo = Convert.ToBase64String(decode);
ms.Close();
return decodeinfo;

}
private static string Decrypt(string msg, string privatekey)
{
RSACryptoServiceProvider crypt = new RSACryptoServiceProvider();
crypt.FromXmlString(privatekey);

ASCIIEncoding enc = new ASCIIEncoding();
byte[] bytes = Convert.FromBase64String(msg);

MemoryStream ms = new MemoryStream();
int keySize = crypt.KeySize / 8;
byte[] rawblock, decryptblock;
for (int i = 0; i < bytes.Length; i += keySize)
{
if ((bytes.Length - i) > keySize)
{
rawblock = new byte[keySize];
}
else
{ rawblock = new byte[bytes.Length - i]; }

Buffer.BlockCopy(bytes, i, rawblock, 0, rawblock.Length);
decryptblock = crypt.Decrypt(rawblock, false);
ms.Write(decryptblock, 0, decryptblock.Length);
}
ms.Position = 0;
byte[] decode = new byte[ms.Length];
ms.Read(decode, 0, (int)ms.Length);

string text = enc.GetString(decode);
ms.Close();
return text;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: