Это почти так же просто, как предполагается, если вы действительно хотите иметь возможность зашифровать / расшифровать строку и сохранить ее на диске.Обратите внимание, что это не использует пароль, он использует контекст безопасности вошедшего в систему пользователя System.Security.Cryptography.DataProtectionScope.CurrentUser для защиты данных.
public class SecureIt
{
static byte[] entropy = System.Text.Encoding.Unicode.GetBytes("Salt Is Not A Password");
public static string EncryptString(System.Security.SecureString input)
{
byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect(
System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)),
entropy,
System.Security.Cryptography.DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encryptedData);
}
public static SecureString DecryptString(string encryptedData)
{
try
{
byte[] decryptedData = System.Security.Cryptography.ProtectedData.Unprotect(
Convert.FromBase64String(encryptedData),
entropy,
System.Security.Cryptography.DataProtectionScope.CurrentUser);
return ToSecureString(System.Text.Encoding.Unicode.GetString(decryptedData));
}
catch
{
return new SecureString();
}
}
public static SecureString ToSecureString(string input)
{
SecureString secure = new SecureString();
foreach (char c in input)
{
secure.AppendChar(c);
}
secure.MakeReadOnly();
return secure;
}
public static string ToInsecureString(SecureString input)
{
string returnValue = string.Empty;
IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
try
{
returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
}
finally
{
System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
}
return returnValue;
}
}
Затем длязашифровать строку:
var clearText = "Some string to encrypt";
var cypherText = SecureIt.EncryptString( SecureIt.ToSecureString( clearText));
и впоследствии расшифровать:
var clearText = SecureIt.ToInsecureString( SecureIt.DecryptString(cypherText));