62,073
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using System.Text;
using System.IO;
/// <summary>
/// 密码安全类
/// </summary>
public class SafeUtil
{
private string iv = "1234****"; //种子
private string key = "1234****"; //加密密钥
private Encoding encoding = new UnicodeEncoding();
private DES des = null;
/// <summary>
/// 构造函数
/// </summary>
public SafeUtil()
{
des = new DESCryptoServiceProvider();
}
/// <summary>
/// 设置或获取加密密钥
/// </summary>
public string EncryptKey
{
set { this.key = value; }
}
/// <summary>
/// 要加密字符的编码格式
/// </summary>
public Encoding EncodingMode
{
get { return this.encoding; }
set { this.encoding = value; }
}
/// <summary>
/// 加密字符串并返回加密后的结果
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string EncryptString(string str)
{
byte[] ivb = Encoding.ASCII.GetBytes(this.iv);
byte[] keyb = Encoding.ASCII.GetBytes(this.key);
byte[] toEncrypt = this.EncodingMode.GetBytes(str);
byte[] encrypted;
ICryptoTransform encrypyor = des.CreateEncryptor(keyb,ivb);
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encrypyor, CryptoStreamMode.Write);
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();
encrypted = msEncrypt.ToArray();
csEncrypt.Close();
msEncrypt.Close();
return Convert.ToBase64String(encrypted);
}
/// <summary>
/// 解密给定的字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string DecryptString(string str)
{
byte[] ivb = Encoding.ASCII.GetBytes(this.iv);
byte[] keyb = Encoding.ASCII.GetBytes(this.key);
byte[] toDecrypt = Convert.FromBase64String(str);
byte[] deCrypted = new byte[toDecrypt.Length];
ICryptoTransform encrypyor = des.CreateEncryptor(keyb, ivb);
MemoryStream msDecrypt = new MemoryStream(toDecrypt);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, encrypyor, CryptoStreamMode.Read);
try
{
csDecrypt.Read(deCrypted, 0, deCrypted.Length);
}
catch (Exception err)
{
throw new ApplicationException(err.Message);
}
finally
{
try
{
msDecrypt.Close();
csDecrypt.Close();
}
catch { ;}
}
return this.EncodingMode.GetString(deCrypted);
}
}
private static string connString = ConfigurationManager.ConnectionStrings["CardShopConnectionString"].ToString();
//解密
//实例化这个类
System.Configuration.ConnectionStringSettings
//用它可以编辑web.config中的 connection节点;
System.Configuration.ConnectionStringSettings css = new ConnectionStringSettings();
css.Name = "connstr";
css.ConnectionString = 加密("连结字符串");
css.ProviderName = "……";
//这个类可以操作web.config文件
System.Configuration.ConfigXmlDocument cxd;