在C#中本地存储和加密密码

时间:2013-12-08 09:09:20

标签: c# web-services password-protection

我需要在C#中开发一个与SOAP Web服务交互的工具。此Web服务的第一个操作使用用户名和密码登录到应用程序。但是,在提供用户凭据时,该工具应在没有用户交互的情况下运行。

这意味着该工具知道用户名和密码。在程序代码或外部文件中存储加密的用户名和密码的方式或多或少是合适的?

3 个答案:

答案 0 :(得分:4)

我会考虑使用DPAPI应该有一个特定于机器的算法。这应该确保数据只能在加密数据的机器上解密。

在链接帖子中也是一个很好的article链接

来自MSDN

// Encrypt the data using DataProtectionScope.CurrentUser. The result can be decrypted 

//  only by the same current user. 

return ProtectedData.Protect( data, s_aditionalEntropy, DataProtectionScope.CurrentUser );

答案 1 :(得分:1)

不太合适的方法是将您的密码以明文形式存储在文本文件或注册表中,以便让作为管理员获取访问权限的所有人都可以访问您的敏感信息 混淆密码的最佳方法之一是使用此ProtectedData Class
 这里是MSDN的一个例子:

using System;
using System.Security.Cryptography;

public class DataProtectionSample
{
// Create byte array for additional entropy when using Protect method. 
    static byte [] s_aditionalEntropy = { 9, 8, 7, 6, 5 };

    public static void Main()
    {
// Create a simple byte array containing data to be encrypted. 

byte [] secret = { 0, 1, 2, 3, 4, 1, 2, 3, 4 };

//Encrypt the data. 
        byte [] encryptedSecret = Protect( secret );
        Console.WriteLine("The encrypted byte array is:");
        PrintValues(encryptedSecret);

// Decrypt the data and store in a byte array. 
        byte [] originalData = Unprotect( encryptedSecret );
        Console.WriteLine("{0}The original data is:", Environment.NewLine);
        PrintValues(originalData);

    }

    public static byte [] Protect( byte [] data )
    {
        try
        {
            // Encrypt the data using DataProtectionScope.CurrentUser. The result can be decrypted 
            //  only by the same current user. 
            return ProtectedData.Protect( data, s_aditionalEntropy, DataProtectionScope.CurrentUser );
        } 
        catch (CryptographicException e)
        {
            Console.WriteLine("Data was not encrypted. An error occurred.");
            Console.WriteLine(e.ToString());
            return null;
        }
    }

    public static byte [] Unprotect( byte [] data )
    {
        try
        {
            //Decrypt the data using DataProtectionScope.CurrentUser. 
            return ProtectedData.Unprotect( data, s_aditionalEntropy, DataProtectionScope.CurrentUser );
        } 
        catch (CryptographicException e)
        {
            Console.WriteLine("Data was not decrypted. An error occurred.");
            Console.WriteLine(e.ToString());
            return null;
        }
    }

    public static void PrintValues( Byte[] myArr )  
    {
          foreach ( Byte i in myArr )  
            {
                 Console.Write( "\t{0}", i );
             }
      Console.WriteLine();
     }

}

答案 2 :(得分:1)

如果您确实需要以某种形式存储密码,请使用AES更好地对其进行加密。 AES是一种经过验证的算法,至少要到下一个十年才能阻止它。请参阅此SO链接以查找C#中的AES加密示例:

Using AES encryption in C#

相关问题