Skip to content

Instantly share code, notes, and snippets.

@otac0n
Created July 22, 2015 21:08
Show Gist options
  • Save otac0n/fd597bcc7030842b0a79 to your computer and use it in GitHub Desktop.
Save otac0n/fd597bcc7030842b0a79 to your computer and use it in GitHub Desktop.
Quick, secure secret storage for C# scripts.
public class SecretStore
{
private readonly string SecretsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), typeof(SecretStore).FullName);
public bool Exists(Guid key)
{
return File.Exists(GetPath(key));
}
public string Get(Guid key)
{
try
{
var bytes = File.ReadAllBytes(GetPath(key));
bytes = ProtectedData.Unprotect(bytes, null, DataProtectionScope.CurrentUser);
return Encoding.UTF8.GetString(bytes);
}
catch (DirectoryNotFoundException)
{
return null;
}
catch (FileNotFoundException)
{
return null;
}
}
public void Set(Guid key, string secret)
{
var bytes = Encoding.UTF8.GetBytes(secret);
bytes = ProtectedData.Protect(bytes, null, DataProtectionScope.CurrentUser);
Directory.CreateDirectory(SecretsPath);
File.WriteAllBytes(GetPath(key), bytes);
}
private string GetPath(Guid key)
{
return Path.Combine(this.SecretsPath, key.ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment