C# Rijndael Encrypt加密/Decrypt解密算法
C# Rijndael Encrypt加密/Decrypt解密算法
C# Code:
C# 全选
/// <summary>
/// Rijndael加密
/// </summary>
/// <param name="clearText">明文</param>
/// <param name="key">key:8位</param>
/// <param name="iv">iv:8位</param>
/// <returns></returns>
public static string RijndaelEncrypt(string clearText, string key, string iv)
{
try
{
if (String.IsNullOrWhiteSpace(clearText)) return "";
RijndaelManaged Rijndael = new RijndaelManaged();
byte[] bytIn = UTF8Encoding.UTF8.GetBytes(clearText);
MemoryStream ms = new MemoryStream();
Rijndael.Key = GetLegalKey(Rijndael, key);
Rijndael.IV = GetLegalIV(Rijndael, iv);
ICryptoTransform encrypto = Rijndael.CreateEncryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
cs.Write(bytIn, 0, bytIn.Length);
cs.FlushFinalBlock();
ms.Close();
byte[] bytOut = ms.ToArray();
return Convert.ToBase64String(bytOut);
}
catch
{
return string.Empty;
}
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
C# Code:
C# 全选
/// <summary>
/// Rijndael解密
/// </summary>
/// <param name="encryptedText">加密的文本</param>
/// <param name="key">key:8位</param>
/// <param name="iv">iv:8位</param>
/// <returns></returns>
public static string RijndaelDecrypt(string encryptedText, string key, string iv)
{
try
{
if (String.IsNullOrWhiteSpace(encryptedText)) return "";
RijndaelManaged Rijndael = new RijndaelManaged();
byte[] bytIn = Convert.FromBase64String(encryptedText);
MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
Rijndael.Key = GetLegalKey(Rijndael, key);
Rijndael.IV = GetLegalIV(Rijndael, iv);
ICryptoTransform encrypto = Rijndael.CreateDecryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);
return sr.ReadToEnd();
}
catch
{
return string.Empty;
}
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
C# Code:
C# 全选
/// <summary>
/// 获得密钥
/// </summary>
/// <returns>密钥</returns>
private static byte[] GetLegalKey(RijndaelManaged Rijndael, string key)
{
string KeyTemp = key;
Rijndael.GenerateKey();
byte[] bytTemp = Rijndael.Key;
int KeyLength = bytTemp.Length;
if (KeyTemp.Length > KeyLength)
KeyTemp = KeyTemp.Substring(0, KeyLength);
else if (KeyTemp.Length < KeyLength)
KeyTemp = KeyTemp.PadRight(KeyLength, ' ');
return ASCIIEncoding.ASCII.GetBytes(KeyTemp);
}
/// <summary>
/// 获得初始向量IV
/// </summary>
/// <returns>初试向量IV</returns>
private static byte[] GetLegalIV(RijndaelManaged Rijndael, string iv)
{
string IVTemp = iv;
Rijndael.GenerateIV();
byte[] bytTemp = Rijndael.IV;
int IVLength = bytTemp.Length;
if (IVTemp.Length > IVLength)
IVTemp = IVTemp.Substring(0, IVLength);
else if (IVTemp.Length < IVLength)
IVTemp = IVTemp.PadRight(IVLength, ' ');
return ASCIIEncoding.ASCII.GetBytes(IVTemp);
}
//来源:C/S框架网 | www.csframework.com | QQ:23404761
扫一扫加微信
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网