Created
July 22, 2015 21:08
-
-
Save otac0n/fd597bcc7030842b0a79 to your computer and use it in GitHub Desktop.
Quick, secure secret storage for C# scripts.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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