c# - 如何加密密码?(csharp/dotnet - 天蓝色 sql 数据库)
问题描述
我正在 csharp 中处理我的第一个 Azure SQL 数据库项目,其中代码看起来基本上像他们文档中的示例代码:
https://docs.microsoft.com/en-us/azure/mysql/connect-csharp
我目前将我的用户名和密码以纯文本形式存储在 JSON 配置文件中。我希望能够加密这些,但不确定如何设计/实现它。
理想情况下,用户将能够进行一次性配置(example.exe --config -username {username} -password {password}),程序将对密码进行哈希处理并将其存储在我的 config.json 中,然后当用户想要使用程序与他们的数据库交互时,能够解密它。
从设计的角度来看,这有意义/安全吗?推荐用于此用途的加密/解密框架?谢谢!
解决方案
为此,您可以使用System.Security.CryptoGraphy.ProtectedData类,即加密,然后存储加密的用户凭据并在需要时解密。你可以在这里阅读它:
https://docs.microsoft.com/en-us/dotnet/standard/security/how-to-use-data-protection
这是一个例子:
using System;
using System.Text;
// Reference assembly 'System.Security'
using System.Security.Cryptography;
namespace TestProtectedData
{
class Program
{
// Encrypt plainText and return a base-64 encoded cipher text
static string Encrypt(string plainText)
{
byte[] plainBytes = UnicodeEncoding.UTF8.GetBytes(plainText);
byte[] cipherBytes = ProtectedData.Protect(plainBytes, null, DataProtectionScope.CurrentUser);
return Convert.ToBase64String(cipherBytes);
}
// Decrypt a base-64 encoded cipher text and return plain text
static string Decrypt(string cipherBase64)
{
var cipherBytes = Convert.FromBase64String(cipherBase64);
var plainBytes = ProtectedData.Unprotect(cipherBytes, null, DataProtectionScope.CurrentUser);
return Encoding.UTF8.GetString(plainBytes, 0, plainBytes.Length);
}
static void Main(string[] args)
{
// plainTextToEncrypt can be a connection string, user credentials or similar
var plainTextToEncrypt = "Hello, secret!";
Console.WriteLine("Plain text: " + plainTextToEncrypt);
// Getting a base64 encoded string as the encryption result for easy storage
var cipherBase64 = Encrypt(plainTextToEncrypt);
// Save the cipherBase64 string into a configuration file or similar
Console.WriteLine("Encrypted text (base64): " + cipherBase64);
// When needed, read the cipherBase64 string and decrypt the text
var plainTextDecrypted = Decrypt(cipherBase64);
Console.WriteLine("Decrypted text: " + plainTextDecrypted);
Console.ReadKey();
}
}
}
推荐阅读
- r - 根据过滤值为数据表创建一个新列
- .htaccess - 在我的 htaccess RewriteRule 中不起作用
- java - 在他进行过滤后过滤器显示不正确的列表
- python - 如何在熊猫中从一种日期时间格式转换为另一种日期时间格式?
- ios - 相机插件导致 Flutter iOS 构建失败
- c# - Automapper 在自定义成员映射中引用现有的子类型映射
- google-api - 使用应用程序专用密码访问 Google Calendar API
- php - 在下拉菜单中分离 Powershell 输出
- c# - 声明身份 .NET CORE 3.0 API JWT
- javascript - 找不到变量:计数器,在博览会中