首页 > 解决方案 > 如何加密密码?(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 中,然后当用户想要使用程序与他们的数据库交互时,能够解密它。

从设计的角度来看,这有意义/安全吗?推荐用于此用途的加密/解密框架?谢谢!

标签: c#sql.netazureencryption

解决方案


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

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

https://docs.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();
        }
    }
}

推荐阅读