I have a small app of little value and concern but the user has to identify themselves (imagine a budget book for personal use).
To make life easier on the twelve colonies the user can choose to auto-login and for that I want to store the username/password in the %appdata% folder with the built-in settings file in C#.
That folder is visible to any PC admin and that's why I don't want it to store in plaintext (especially since users are prone to re-use passwords).
Is there an easy library where I can encrypt/decrypt a string with a master password that doesn't require me to code hundreds of lines?
Yes I am aware that if someone would be able to decompile the exe and get their hold on the master password that security would be breached. I know it's a bit of security-by-obscurity but I think for my use case it would fall in the category of "good enough".
One solution would be using System.Security.Cryptography.
In this example I use a 32 byte key to encrypt and decrypt.
public static string EncryptString(string text, string key)
{
var aes = Aes.Create();
var encryptor = aes.CreateEncryptor(Encoding.UTF8.GetBytes(key), aes.IV);
using var memoryStream = new MemoryStream();
using var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
using (var streamWriter = new StreamWriter(cryptoStream))
{
streamWriter.Write(text);
}
var iv = aes.IV;
var encrypted = memoryStream.ToArray();
return Convert.ToBase64String(iv.Concat(encrypted).ToArray());
}
public static string DecryptString(string cipherText, string key)
{
var fullCipher = Convert.FromBase64String(cipherText);
var iv = fullCipher.Take(16).ToArray();
var cipher = fullCipher.Skip(16).ToArray();
var aes = Aes.Create();
var decryptor = aes.CreateDecryptor(Encoding.UTF8.GetBytes(key), iv);
using var memoryStream = new MemoryStream(cipher);
using var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
using var streamReader = new StreamReader(cryptoStream);
return streamReader.ReadToEnd();
}