“ASCIIEncoding”这个名称在当前上下文中不存在

时间:2014-07-01 19:59:33

标签: c# sql webmatrix

我试图加密字符串以将其保存在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;
    }
}
}

2 个答案:

答案 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了解更多信息。