我试图加密字符串以将其保存在sql server数据库中,但是"名称' ASCIIEncoding'在当前背景下不存在"出现。如何在ASP.Net Web Pages Framework中加密字符串?以下是我的代码:
@using System.Security.Cryptography;
@{
String s = "hello";
String s2 = "hello";
s = Encrypt(s,_key);
s2 = Encrypt(s2, _key);
}
@functions{
private static readonly byte[] _key = "myVeryStrongPsw";
public static string Encrypt(string strToEncrypt, string strKey)
{
try
{
TripleDESCryptoServiceProvider objDESCrypto =
new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
byte[] byteHash, byteBuff;
string strTempKey = strKey;
byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
objHashMD5 = null;
objDESCrypto.Key = byteHash;
objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
return Convert.ToBase64String(objDESCrypto.CreateEncryptor().
TransformFinalBlock(byteBuff, 0, byteBuff.Length));
}
catch (Exception ex)
{
return "Wrong Input. " + ex.Message;
}
}
}
答案 0 :(得分:2)
使用System.Text
语句
using
using System.Text ;
或完全符合参考资格:
System.Text.ASCIIEncoding
但你应该意识到System.Text.ASCIIEncoding.ASCII
是多余的。只是说
`System.Text.Encoding.ASCII`
答案 1 :(得分:0)
ASCIIEncoding
类包含在System.Text
命名空间中。您需要做以下两件事之一:
using
语句(如using System.Text
)byteBuff = System.Text.ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
)查看here了解更多信息。