gpt4 book ai didi

c# - 如何对密码进行加密? (csharp/dotnet - azure sql 数据库)

转载 作者:行者123 更新时间:2023-12-03 01:39:50 24 4
gpt4 key购买 nike

我正在 csharp 中开发我的第一个 Azure SQL 数据库项目,其中的代码基本上类似于其文档中的示例代码:

https://learn.microsoft.com/en-us/azure/mysql/connect-csharp

我目前将我的用户名和密码以纯文本形式存储在 JSON 配置文件中。我希望能够加密这些,但不确定如何设计/实现。

理想情况下,用户能够执行一次性配置(example.exe --config -username {username} -password {password}),程序会对密码进行哈希处理并将其存储在我的 config.json 中,并且当用户想要使用该程序与数据库交互时能够解密它。

从设计角度来看,这有意义/安全吗?建议使用什么加密/解密框架?谢谢!

最佳答案

您可以使用 System.Security.CryptoGraphy.ProtectedData 类来实现此目的,即加密,然后存储加密的用户凭据并在需要时解密。您可以在这里阅读:

https://learn.microsoft.com/en-us/dotnet/standard/security/how-to-use-data-protection

https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.protecteddata?view=netframework-4.7.2

这是一个例子:

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();
}
}
}

关于c# - 如何对密码进行加密? (csharp/dotnet - azure sql 数据库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54876857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com