编译器错误消息:CS0103:当前上下文中不存在名称"ProtectedData"

use*_*830 4 c# cryptography

我在尝试使用System.Security的加密代码时遇到运行时错误.我添加了对System.Security的引用,一切看起来不错,但我收到此错误:"编译器错误消息:CS0103:名称'ProtectedData'在当前上下文中不存在"

这是抛出错误的代码.

public static string EncryptString(SecureString input, string entropy)
    {
        byte[] salt = Encoding.Unicode.GetBytes(entropy);
        byte[] encryptedData = ProtectedData.Protect(
            Encoding.Unicode.GetBytes(ToInsecureString(input)),
            salt,
            DataProtectionScope.CurrentUser);
        return Convert.ToBase64String(encryptedData);
    }
Run Code Online (Sandbox Code Playgroud)

谢谢,山姆

pst*_*jds 10

您需要为其添加using语句,System.Security.Cryptography并且需要引用System.Security.dll.从您的问题看来,您刚刚添加了引用而不是using语句.

您也可以完全限定引用,而不是using语句,如下所示:

byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect(
            Encoding.Unicode.GetBytes(ToInsecureString(input)), salt,
            System.Security.Cryptography.DataProtectionScope.CurrentUser);
Run Code Online (Sandbox Code Playgroud)