对称
/// <summary>
/// 實現對稱加密的方法,提高系統安全性。
/// </summary>
public class ProSecurity
{
private SymmetricAlgorithm mobjCryptoService;
/// <summary>
/// 初始化加密類別的新執行個體。
/// </summary>
public ProSecurity()
{
mobjCryptoService = new RijndaelManaged();
}
private byte[] GetLegalKey(string Key)
{
string sTemp = Key;
mobjCryptoService.GenerateKey();
byte[] bytTemp = mobjCryptoService.Key;
int KeyLength = bytTemp.Length;
if (sTemp.Length > KeyLength)
sTemp = sTemp.Substring(0, KeyLength);
else if (sTemp.Length < KeyLength)
sTemp = sTemp.PadRight(KeyLength, ' ');
return ASCIIEncoding.ASCII.GetBytes(sTemp);
}
private byte[] GetLegalIV(string Key)
{
string sTemp = Key;
mobjCryptoService.GenerateIV();
byte[] bytTemp = mobjCryptoService.IV;
int IVLength = bytTemp.Length;
if (sTemp.Length > IVLength)
sTemp = sTemp.Substring(0, IVLength);
else if (sTemp.Length < IVLength)
sTemp = sTemp.PadRight(IVLength, ' ');
return ASCIIEncoding.ASCII.GetBytes(sTemp);
}
/// <summary>
/// 對稱加密方法。
/// <para></para>
/// <para>例外狀況:</para>
/// 沒有指定加密的字符以及偏移量。
/// </summary>
/// <param></param>
/// <returns></returns>
public string Encrypto(string Source, string vKey)
{
byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
MemoryStream ms = new MemoryStream();
mobjCryptoService.Key = GetLegalKey(vKey);
mobjCryptoService.IV = GetLegalIV(vKey);
ICryptoTransform encrypto = mobjCryptoService.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);
}
/// <summary>
/// 對稱解密方法。
/// <para></para>
/// <para>例外狀況:</para>
/// 要解密的字符不滿足8位元不帶正負號的整數陣列。
/// </summary>
/// <param></param>
/// <returns></returns>
public string Decrypto(string Source, string vKey)
{
byte[] bytIn = Convert.FromBase64String(Source);
MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
mobjCryptoService.Key = GetLegalKey(vKey);
mobjCryptoService.IV = GetLegalIV(vKey);
ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);
return sr.ReadToEnd();
}
}