/// <summary>
/// 使用DES加密
/// </summary>
/// <param name= "originalValue "> 待加密的字符串 </param>
/// <param name= "key "> 密钥(最大长度8) </param>
/// <param name= "IV "> 初始化向量(最大长度8) </param>
/// <returns> 加密后的字符串 </returns>
public string DESEncrypt(string originalValue,string key,string IV)
{
//将key和IV处理成8个字符
key += "12345678 ";
IV += "12345678 ";
key = key.Substring(0,8);
IV = IV.Substring(0,8);
SymmetricAlgorithm sa;
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
sa = new DESCryptoServiceProvider();
sa.Key = Encoding.UTF8.GetBytes(key);
sa.IV = Encoding.UTF8.GetBytes(IV);
ct = sa.CreateEncryptor();
byt = Encoding.UTF8.GetBytes(originalValue);
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>
/// 使用DES加密
/// </summary>
/// <param name= "originalValue "> 待加密的字符串 </param>
/// <param name= "key "> 密钥(最大长度8) </param>
/// <returns> 加密后的字符串 </returns>
public string DESEncrypt(string originalValue,string key)
{
return DESEncrypt(originalValue,key,key);
}
/// <summary>
/// 使用DES解密
/// </summary>
/// <param name= "encryptedValue "> 待解密的字符串 </param>
/// <param name= "key "> 密钥(最大长度8) </param>
/// <returns> 解密后的字符串 </returns>
public string DESDecrypt(string encryptedValue,string key)
{
return DESDecrypt(encryptedValue,key,key);
}
/// <summary>
/// 将二进制数组转为字符串
/// </summary>
/// <param name= "Byte "> 二进制数组 </param>
/// <returns> </returns>
private string GetStringValue(byte[] Byte)
{
string tmpString = " ";
if (this.isReturnNum == false)
{
ASCIIEncoding Asc = new ASCIIEncoding();
tmpString = Asc.GetString(Byte);
}
else
{
int iCounter;
for(iCounter=0;iCounter <Byte.Length;iCounter++)
{
tmpString = tmpString + Byte[iCounter].ToString();
}
}
return tmpString;
}
/// <summary>
/// 返回字符串的二进制数组
/// </summary>
/// <param name= "strKey "> 字符串 </param>
/// <returns> </returns>
private byte[] GetKeyByteArray(string strKey)
{
ASCIIEncoding Asc = new ASCIIEncoding();
int tmpStrLen = strKey.Length;
byte[] tmpByte = new byte[tmpStrLen-1];
tmpByte = Asc.GetBytes(strKey);
return tmpByte;
}
}
}
程序中这样调用:
public static readonly string ConnectionStringLocalTransaction =new HashEncrypt(true,false).DESDecrypt( ConfigurationManager.ConnectionStrings[ "SQLConnString "].ConnectionString, "web ", "web ");