一个可逆的DES和TripleDES方式加密类(downmoon原创)
一个可逆的DES和TripleDES方式加密类(downmoon原创)
using System;
using System.Security;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace EncryptDownmoon

...{

/**//// <summary>
/// EncryptSqlConn 的摘要说明。
/// </summary>
public class EncryptSqlConn

...{
public EncryptSqlConn()

...{
if(mCSP ==null)

...{
mCSP = SetEnc();
}
}

/**//// <summary>
/// 设置加密方式,0为DES,1为TripleDES
/// </summary>
/// <returns></returns>
public EncryptSqlConn(int EnMethod)

...{
if(EnMethod==0)

...{
lngEnMethod=0;
}
else

...{
lngEnMethod=1;
}
if(mCSP ==null)

...{
mCSP = SetEnc();
}
}

方法#region 方法

private SymmetricAlgorithm mCSP;
private int m_lngEnMethod=0;

/**//// <summary>
/// 加密方式,0为DES,1为TripleDES
/// </summary>
public int lngEnMethod

...{
get

...{
return m_lngEnMethod;
}
set

...{
m_lngEnMethod=value;
}
}
private SymmetricAlgorithm SetEnc()

...{
if(lngEnMethod==0)

...{
return new DESCryptoServiceProvider();
}
else
return new TripleDESCryptoServiceProvider();
}
//测试键值
private string genKeyValue

...{
get

...{
mCSP.GenerateKey();
return Convert.ToBase64String(mCSP.Key);
}
}
//测试IV值
private string genIVValue

...{
get

...{
mCSP.GenerateIV();
return Convert.ToBase64String(mCSP.IV);
}
}

/**//// <summary>
/// 加密字串
/// </summary>
/// <param name="Value"></param>
/// <returns></returns>
public string EncryptString(string Value)

...{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
//ct = mCSP.CreateEncryptor(genKeyValue,genIVValue);
byt = Encoding.UTF8.GetBytes(Value);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}


/**//// <summary>
/// 解密字串
/// </summary>
/// <param name="Value"></param>
/// <returns></returns>
public string DecryptString(string Value)

...{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
//ct = mCSP.CreateDecryptor(genKeyValue, genIVValue);
byt = Convert.FromBase64String(Value);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
#endregion
}
}
查看本文来源