2012-02-12 10:46:16|?次阅读|上传:wustguangh【已有?条评论】发表评论
C#程序经常需要对文件、字符串进行加密、解密处理,以保护数据的安全,C#对加密、解密提供了方便的API支持,本文总结了常用的加密、解密方法,通过实际的代码,让读者能够快速掌握C#的各种加密/解密方法,以便在实际工作中应用适合项目的加密、解密方式。
1、方法一 (不可逆加密),使用HashPasswordForStoringInConfigFile函数
public string EncryptPassword(string PasswordString, string PasswordFormat)
{
string encryptPassword = null;
if (PasswordFormat = "SHA1")
encryptPassword = FormsAuthentication
.HashPasswordForStoringInConfigFile(PasswordString, "SHA1");
else if (PasswordFormat = "MD5")
encryptPassword = FormsAuthentication
.HashPasswordForStoringInConfigFile(PasswordString, "MD5");
return encryptPassword;
}
备注:FormsAuthentication.HashPasswordForStoringInConfigFile 方法
根据指定的密码和哈希算法生成一个适合于存储在配置文件中的哈希密码。
命名空间: System.Web.Security
程序集: System.Web(在 System.Web.dll 中)
public static string HashPasswordForStoringInConfigFile(
string password,
string passwordFormat
)
password
类型:System.String
要进行哈希运算的密码。
passwordFormat
类型:System.String
要使用的哈希算法。 passwordFormat 是一个 String,表示 FormsAuthPasswordFormat 枚举值之一。
类型:System.String
经过哈希运算的密码。
2、方法二 (可逆加密) ,自定义加密算法
public interface IBindesh
{
string encode(string str);
string decode(string str);
}
public class EncryptionDecryption : IBindesh
{
public string encode(string str)
{
string htext = "";
for (int i = 0; i < str.Length; i++)
{
htext = htext + (char)(str[i] + 10 - 1 * 2);
}
return htext;
}
public string decode(string str)
{
string dtext = "";
for (int i = 0; i < str.Length; i++)
{
dtext = dtext + (char)(str[i] - 10 + 1 * 2);
}
return dtext;
}
}