Skip to content

Instantly share code, notes, and snippets.

@pedro2555
Last active November 28, 2022 14:31
Show Gist options
  • Save pedro2555/85c92ad202cff0f0a096fd1a45d0305e to your computer and use it in GitHub Desktop.
Save pedro2555/85c92ad202cff0f0a096fd1a45d0305e to your computer and use it in GitHub Desktop.
Jon Galloway - Encrypting Passwords in a .NET app.config File
///
/// https://weblogs.asp.net/jongalloway/encrypting-passwords-in-a-net-app-config-file
///
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;
}
@pedro2555
Copy link
Author

Encrypt:

AppSettings.Password = EncryptString(ToSecureString(PasswordTextBox.Password));

Decrypt:

SecureString password = DecryptString(AppSettings.Password);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment