public class PwdEncode
{
/// <summary>
/// 加密字符串
/// </summary>
/// <param name="pToDecrypt">待加密字符串</param>
/// <returns></returns> public string Encrypt(string pToEncrypt)
{ byte[] desKey = new  byte[]{0x16, 0x09, 0x14, 0x15, 0x07, 0x01, 0x05, 0x08};
byte[] desIV = new  byte[]{0x16, 0x09, 0x14, 0x15, 0x07, 0x01, 0x05, 0x08}; DESCryptoServiceProvider des = new DESCryptoServiceProvider();
try
{
//把字符串放到byte数组中
//原来使用的UTF8编码,我改成Unicode编码了,不行
byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
//byte[] inputByteArray=Encoding.Unicode.GetBytes(pToEncrypt); //建立加密对象的密钥和偏移量
//原文使用ASCIIEncoding.ASCII方法的GetBytes方法
//使得输入密码必须输入英文文本
des.Key = desKey; // ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = desIV; //ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(),
CryptoStreamMode.Write);
//Write the byte array into the crypto stream
//(It will end up in the memory stream)
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock(); //Get the data back from the memory stream, and into a string
StringBuilder ret = new StringBuilder();
foreach(byte b in ms.ToArray())
{
//Format as hex
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
catch
{
return pToEncrypt;
}
finally
{
des = null;
}
} /// <summary>
/// 解密字符串
/// </summary>
/// <param name="pToDecrypt">待解密字符串</param>
/// <returns></returns>
public string Decrypt(string pToDecrypt)
{
byte[] desKey = new  byte[]{0x16, 0x09, 0x14, 0x15, 0x07, 0x01, 0x05, 0x08};
byte[] desIV = new  byte[]{0x16, 0x09, 0x14, 0x15, 0x07, 0x01, 0x05, 0x08}; DESCryptoServiceProvider des = new DESCryptoServiceProvider();
try
{
//Put the input string into the byte array
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for(int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
} //建立加密对象的密钥和偏移量,此值重要,不能修改
des.Key = desKey; //ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = desIV; //ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(),CryptoStreamMode.Write);
//Flush the data through the crypto stream into the memory stream
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock(); //Get the decrypted data back from the memory stream
//建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象
StringBuilder ret = new StringBuilder();

return System.Text.Encoding.Default.GetString(ms.ToArray());
}
catch
{
return pToDecrypt;
}
finally
{
des = null;
}
}
}

解决方案 »

  1.   

    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Web;
    using System.Web.Security;
    using BidData;namespace eBid.bizclass
    {
    /// <summary>
    /// BidSecurity 的摘要说明。
    /// </summary>
    public class BidSecurity:ILogin
    {
    private const String HASH_METHOD = "MD5";  //密码加密方式 SqlConnection conn; String strUserName;
    String strPassword;
    DateTime dtPasswordChangeDate;
    Boolean bNeedToChangePassword;
    String strGUID;
    Boolean bUserLocked;
    DateTime dtUserLockedTime;
    String strUserType;
    Decimal intProviderID;
    Decimal intStockerID; public BidSecurity()
    {
    conn = new Conn().GetConn();
    } private void GetUser(String UserName)
    {
    LoginData login = new LoginData();
    login.SelectLogin(-1,UserName);
    if (login.Tables[LoginData.LOGIN_TABLE_NAME].Rows.Count > 0)
    {
    DataRow dr = login.Tables[LoginData.LOGIN_TABLE_NAME].Rows[0];
    strUserName = dr[LoginData.LOGIN_USERNAME].ToString();
    strPassword = dr[LoginData.LOGIN_PASSWORD].ToString();
    dtPasswordChangeDate = (DateTime)dr[LoginData.LOGIN_PASSWORD_CHANGED_DATE];
    bNeedToChangePassword = (Boolean)dr[LoginData.LOGIN_NEED_TO_CHANGE_PASSWORD];
    strGUID = dr[LoginData.LOGIN_GUID].ToString();
    bUserLocked = (Boolean)dr[LoginData.LOGIN_USER_LOCKED];
    strUserType = dr[LoginData.LOGIN_USER_TYPE].ToString();
    intProviderID = Decimal.Parse(dr[LoginData.PROVIDER_ID].ToString());
    intStockerID = Decimal.Parse(dr[LoginData.STOCKER_ID].ToString());
    if (dr[LoginData.LOGIN_USER_LOCKED_TIME] != System.DBNull.Value)
    dtUserLockedTime = DateTime.Parse(dr[LoginData.LOGIN_USER_LOCKED_TIME].ToString());
    else
    dtUserLockedTime = DateTime.MaxValue;
    }
    else
    {
    strUserName = "";
    strPassword = "";
    dtPasswordChangeDate = DateTime.Now;
    bNeedToChangePassword = true;
    strGUID = "";
    bUserLocked = true;
    strUserType = "";
    dtUserLockedTime = DateTime.Now;
    }
    } private String HashPassword(String ClearPassword)
    {
    return FormsAuthentication.HashPasswordForStoringInConfigFile(ClearPassword,HASH_METHOD);
    } public bool IfUserLocked()
    {
    if (this.bUserLocked || this.dtUserLockedTime > DateTime.Now)
    return true;
    else
    return false;
    } public bool IfUserNeedToChangePassword()
    {
    if (this.bNeedToChangePassword || this.dtPasswordChangeDate < DateTime.Now)
    return true;
    else
    return false;
    } public int ChangePassword(String UserName,String NewPassword,Boolean ResetPassword)
    {
    String strGuidGet = HttpContext.Current.Request.QueryString[0];
    int intResult = -1;
    GetUser(UserName);
    if (strUserName.Length > 0)
    {
    if (ResetPassword)
    {
    if (strGuidGet == strGUID)
    {
    int UpdateResult = this.WriteNewPasswordToDataBase(UserName,HashPassword(NewPassword));
    if (UpdateResult == 1)
    return 1;
    else
    return 0;
    }
    else
    {
    intResult = 2;
    }
    }
    }
    else //
    {
    intResult = -1; //找不到该用户
    }
    return intResult;
    } private int WriteNewPasswordToDataBase(String UserName,String NewPassword)
    {
    SqlCommand cmd = new SqlCommand(LoginData.CHANGE_PASSWORD_PROC_NAME,conn);
                SqlParameterCollection param = cmd.Parameters;
    param.Add("@username",SqlDbType.VarChar,20);
    param["@username"].Value = UserName;
    param.Add("@password",SqlDbType.VarChar,50);
    param["@password"].Value = NewPassword;
    return cmd.ExecuteNonQuery();
    } public String GetRealName(String UserName)
    {
    GetUser(UserName);
    if (this.strUserType == "1")
    {
    return GetProviderName(intProviderID);
    }
    else if (this.strUserType == "2")
    {
    return GetStocherName(intStockerID);
    }
    else
    {
    return "来宾";
    }
    } public String GetStocherName(decimal StockerID)
    {
    String strResult = "";
    FileStockorData stocker = new FileStockorData();
    stocker.SelectStockor(StockerID,"","",-1,-1,-1,-1,-1,-1,"1");
    strResult = stocker.StockorTable.Rows[0][FileStockorData.CHINESE_NAME].ToString();
    return strResult;
    } public String GetProviderName(decimal ProviderID)
    {
    String strResult = "";
    FileProviderData provider = new FileProviderData();
    provider.SelectProvider(ProviderID,"","","","","","","","",-1,-1,-1);
    strResult = provider.ProviderTable.Rows[0][FileProviderData.C_NAME].ToString();
    return strResult;
    } public String WriteResetPassword(String UserName)
    {
    String guid = new Guid().ToString();
    Random random = new Random((Int32)DateTime.Now.Ticks);
    String randomPassword = HashPassword(random.ToString());
    SqlCommand cmd = new SqlCommand(LoginData.CHANGE_PASSWORD_PROC_NAME,conn);
    SqlParameterCollection param = cmd.Parameters;
    param.Add("@username",SqlDbType.VarChar,20);
    param["@username"].Value = UserName;
    param.Add("@password",SqlDbType.VarChar,50);
    param["@password"].Value = "";
    param.Add("@guid",SqlDbType.VarChar,50);
    param["@guid"].Value = guid;
    try
    {
    cmd.ExecuteNonQuery();
    }
    catch
    {
    throw new Exception("重置密码存储过程执行错误");
    }
    return guid;
    }
    #region ILogin 成员 public bool Authenticate(String UserName, String Password)
    {
    bool bResult = false;
    GetUser(UserName);
    if (UserName.Length > 0)
    {
    if (HashPassword(Password) == strPassword)
    {
    bResult = true;
    }
    else
    {
    bResult = false;
    }
    }
    else
    {
    bResult = false;
    }
    return bResult;
    } #endregion
    }}
      

  2.   

    使用列取法取秘密算法也不错
    例如
    列如下.密码是 username
      1 2 3 4 5
      U S E R N
      A M E
    那么密文是UASMEER N  没有的为空格.这种加密算法也可以考虑,
    当然你可以考虑其它更好的算法..最好没有其它人专门使用..一般都足够你加密
      

  3.   

    /// <summary>
    /// 通过DES算法加密一个字符串.
    /// </summary>
    /// <param name="ValueToEnCrypt">需要被加密的值</param>
    public static String DESEnCrypt(String ValueToEnCrypt)
    {
    DESCryptoServiceProvider DesProv = new DESCryptoServiceProvider();
    return EnCrypt(DesProv, ValueToEnCrypt);
    } /// <summary>
    /// 通过DES算法解密一个字符串
    /// </summary>
    /// <param name="ValueToDeCrypt">需要被解密的值</param>
    public static String DESDeCrypt(String ValueToDeCrypt)
    {
    DESCryptoServiceProvider DesProv = new DESCryptoServiceProvider();
    return DeCrypt(DesProv, ValueToDeCrypt);
    } /// <summary>
    /// 通过Rijandel算法加密一个字符串.
    /// </summary>
    /// <param name="ValueToEnCrypt">需要被解密的值</param>
    public static String RijndaelEnCrypt(String ValueToEnCrypt)
    {
    Rijndael Rijndael = Rijndael.Create();
    return EnCrypt(Rijndael, ValueToEnCrypt);
    } /// <summary>
    /// 通过Rijandel算法解密一个字符串.
    /// </summary>
    /// <param name="ValueToDeCrypt">需要被解密的值.</param>
    public static String RijndaelDeCrypt(String ValueToDeCrypt)
    {
    Rijndael Rijndael = Rijndael.Create();
    return DeCrypt(Rijndael, ValueToDeCrypt);
    } /// <summary>
    /// 通过制定的算法模式来加密一个字符串
    /// </summary>
    /// <param name="Algorithm">加密的算法</param>
    /// <param name="ValueToEnCrypt">将要被加密的值</param>
    private static String EnCrypt(SymmetricAlgorithm Algorithm, String ValueToEnCrypt)
    {
    // 将字符串保存到字节数组中
    Byte [] InputByteArray = Encoding.UTF8.GetBytes(ValueToEnCrypt); // 获得需要的密钥
    String EncryptionKey = CommonFunction.EncryptionKey;

    // 创建一个key.
    Byte [] Key = ASCIIEncoding.ASCII.GetBytes(EncryptionKey);
    Algorithm.Key = (Byte [])ArrayFunctions.ReDim(Key, Algorithm.Key.Length);
    Algorithm.IV = (Byte [])ArrayFunctions.ReDim(Key, Algorithm.IV.Length); MemoryStream MemStream = new MemoryStream();
    CryptoStream CrypStream = new CryptoStream(MemStream, Algorithm.CreateEncryptor(), CryptoStreamMode.Write);

    // Write the byte array into the crypto stream( It will end up in the memory stream).
    CrypStream.Write(InputByteArray, 0, InputByteArray.Length);
    CrypStream.FlushFinalBlock(); // Get the data back from the memory stream, and into a string.
    StringBuilder StringBuilder = new StringBuilder();
    for (Int32 i = 0; i < MemStream.ToArray().Length; i++)
    {
    Byte ActualByte = MemStream.ToArray()[i];

    // Format the actual byte as HEX.
    StringBuilder.AppendFormat("{0:X2}", ActualByte);
    }

    return StringBuilder.ToString();
    } /// <summary>
    /// 通过制定的算法模式来加密一个字符串
    /// </summary>
    /// <param name="Algorithm">解密的算法</param>
    /// <param name="ValueToDeCrypt">将要被解密的值</param>
    private static String DeCrypt(SymmetricAlgorithm Algorithm, String ValueToDeCrypt)
    {
    // Put the input string into the byte array.
    Byte [] InputByteArray = new Byte[ValueToDeCrypt.Length / 2]; for (Int32 i = 0; i < ValueToDeCrypt.Length / 2; i++)
    {
    Int32 Value = (Convert.ToInt32(ValueToDeCrypt.Substring(i * 2, 2), 16));
    InputByteArray[i] = (Byte)Value;
    } // Create the crypto objects.
    String EncryptionKey = CommonFunction.EncryptionKey;
    // Create the key.
    Byte [] Key = ASCIIEncoding.ASCII.GetBytes(EncryptionKey);
    Algorithm.Key = (Byte [])ArrayFunctions.ReDim(Key, Algorithm.Key.Length);
    Algorithm.IV = (Byte [])ArrayFunctions.ReDim(Key, Algorithm.IV.Length);

    MemoryStream MemStream = new MemoryStream();
    CryptoStream CrypStream = new CryptoStream(MemStream, Algorithm.CreateDecryptor(), CryptoStreamMode.Write);

    // Flush the data through the crypto stream into the memory stream.
    CrypStream.Write(InputByteArray, 0, InputByteArray.Length);
    CrypStream.FlushFinalBlock(); // Get the decrypted data back from the memory stream.
    StringBuilder StringBuilder = new StringBuilder();

    for (Int32 i = 0; i < MemStream.ToArray().Length; i++)
    {
    StringBuilder.Append((Char)MemStream.ToArray()[i]);
    } return StringBuilder.ToString();
    }