private void Save(FileInfo file) { byte[] usernameBytes = Encoding.Unicode.GetBytes(Username); byte[] passwordBytes = new byte[SecureStringHelper.GetSecureStringByteCount(Password, Encoding.Unicode)]; SecureStringHelper.SecureStringToBytes(Password, passwordBytes, 0, Encoding.Unicode); try { byte[] entropy = GenerateEntropy(); byte[] protectedUsernameBytes = ProtectedData.Protect(usernameBytes, entropy, DataProtectionScope.CurrentUser); byte[] protectedPasswordBytes = ProtectedData.Protect(passwordBytes, entropy, DataProtectionScope.CurrentUser); var template = new CredentialsExportTemplate() { Entropy = Convert.ToBase64String(entropy), ProtectedUsername = Convert.ToBase64String(protectedUsernameBytes), ProtectedPassword = Convert.ToBase64String(protectedPasswordBytes), }; JsonHelper.Serialize(template, file); } finally { SecureStringHelper.DestroySecureByteArray(passwordBytes); } }
private void Load(FileInfo file) { CredentialsExportTemplate template = JsonHelper.Deserialize <CredentialsExportTemplate>(file); byte[] entropy = Convert.FromBase64String(template.Entropy); byte[] protectedUsernameBytes = Convert.FromBase64String(template.ProtectedUsername); byte[] protectedPasswordBytes = Convert.FromBase64String(template.ProtectedPassword); byte[] usernameBytes = ProtectedData.Unprotect(protectedUsernameBytes, entropy, DataProtectionScope.CurrentUser); byte[] passwordBytes = ProtectedData.Unprotect(protectedPasswordBytes, entropy, DataProtectionScope.CurrentUser); try { username = Encoding.Unicode.GetString(usernameBytes); password = SecureStringHelper.SecureStringFromBytes(passwordBytes, Encoding.Unicode); } finally { SecureStringHelper.DestroySecureByteArray(passwordBytes); } }