public static byte[] ProtectData(byte[] data, byte[] optionalEntropy = null, DataProtectionScope scope = DataProtectionScope.LocalMachine)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
try
{
byte[] protectedData = ProtectedData.Protect(data, optionalEntropy, scope);
return protectedData;
}
catch (CryptographicException e)
{
Console.WriteLine($"Data protection failed.{e}");
return null;
}
}
public static byte[] UnprotectData(byte[] data, byte[] optionalEntropy = null, DataProtectionScope scope = DataProtectionScope.LocalMachine)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
try
{
byte[] unprotectedData = ProtectedData.Unprotect(data, optionalEntropy, scope);
return unprotectedData;
}
catch (CryptographicException e)
{
Console.WriteLine($"Data unprotection failed.{e}");
return null;
}
}
以上代码将使用LocalMachine数据保护范围(可以更改为CurrentUser)来加密和解密数据。在应用程序中使用它们将确保数据正确保存和解密。