您的位置:首页 > 其它

AES与RSA加密

2017-02-07 16:05 169 查看
AES

using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace winfAESEncryptDecrypt
{
public class AES
{
/// <summary>
/// AES加密
/// </summary>
/// <param name="data">待加密的字符数据</param>
/// <param name="key">密匙,长度可以为:128位(byte[16]),192位(byte[24]),256位(byte[32])</param>
/// <param name="iv">iv向量,长度必须为128位(byte[16])</param>
/// <returns>加密后的字符</returns>
public string EnAES(string data, string key, string iv)
{
if (string.IsNullOrEmpty(data)) return data;
Aes aes = Aes.Create();
byte[] tmp = null;

ICryptoTransform encryptor = aes.CreateEncryptor(Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(iv));
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
StreamWriter writer = new StreamWriter(cs);
writer.Write(data);
writer.Flush();
writer.Close();
}
tmp = ms.ToArray();
}
return Convert.ToBase64String(tmp);
}

/// <summary>
/// AES解密
/// </summary>
/// <param name="data">待加密的字符数据</param>
/// <param name="key">密匙,长度可以为:128位(byte[16]),192位(byte[24]),256位(byte[32])</param>
/// <param name="iv">iv向量,长度必须为128位(byte[16])</param>
/// <returns>加密后的字符</returns>
public string DeAES(string data, string key, string iv)
{
if (string.IsNullOrEmpty(data)) return data;
string result = string.Empty;
Aes aes = Aes.Create();

ICryptoTransform edcryptor = aes.CreateDecryptor(Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(iv));
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(data)))
{
using (CryptoStream cs = new CryptoStream(ms, edcryptor, CryptoStreamMode.Read))
{
StreamReader reader = new StreamReader(cs);
result = reader.ReadLine();
reader.Close();
}
}
aes.Clear();
return result;
}
}

}
RSA
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string privateKey = rsa.ToXmlString(true);
string publicKey = rsa.ToXmlString(false);

using System;
using System.Security.Cryptography;
using System.Text;

namespace winfAESEncryptDecrypt
{
public class RSA
{
/// <summary>
/// RSA加密
/// </summary>
/// <param name="sdata"></param>
/// <param name="sPublicKey"></param>
/// <returns></returns>
public string EnRSA(string sdata, string sPublicKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(sPublicKey);
byte[] mybyte = Encoding.UTF8.GetBytes(sdata);
string sEnRSA = Convert.ToBase64String(rsa.Encrypt(mybyte, false));
return sEnRSA;
}

/// <summary>
/// RSA解密
/// </summary>
/// <param name="sdata"></param>
/// <param name="sPrivateKey"></param>
/// <returns></returns>
public string DeRAS(string sdata, string sPrivateKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(sPrivateKey);
byte[] mybyte = Convert.FromBase64String(sdata);
string sDeRAS = Encoding.UTF8.GetString(rsa.Decrypt(mybyte, false));
return sDeRAS;
}

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