在客户端保护数据



am从纯文本文件中[写-读]用户名和密码,但这是一种保护数据的糟糕方法,有没有其他方法可以做到这一点,很可能是使用IV的加密-解密算法。

您需要决定是否需要再次解密文本。我建议,至少对于密码,你可以使用单向哈希。如果你使用salt,你可以很难对哈希进行暴力攻击。理想情况下,每个密码都应该使用一个单独的随机salt:password+salt=hash。您需要存储salt和hash,但它可以以纯文本形式存储,因为它不是加密机密。示例实现(使用SHA256):

 public class SHA256
{
    public static string GetHash(string password, string salt)
    {
        UTF8Encoding encoder = new UTF8Encoding();
        SHA256Managed sha256 = new SHA256Managed();
        byte[] hashedDataBytes = sha256.ComputeHash(encoder.GetBytes(salt + password));
        return ByteArrayToString(hashedDataBytes);
    }

    /// <summary>
    /// Generates a random 16 character alpha-numeric salt
    /// </summary>
    /// <returns></returns>
    public static string GenerateRandomSalt()
    {
        const string allowedChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";
        char[] chars = new char[16];
        var rd = new Random((int)DateTime.Now.Ticks);
        for (int i = 0; i < 16; i++)
        {
            chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
        }
        return new string(chars);
    }
    /// <summary>
    /// Converts supplied byte array to hex format string.
    /// </summary>
    /// <param name="inputArray"></param>
    /// <returns></returns>
    private static string ByteArrayToString(byte[] inputArray)
    {
        StringBuilder output = new StringBuilder("");
        for (int i = 0; i < inputArray.Length; i++)
        {
            output.Append(inputArray[i].ToString("X2")); //Return in hex format
        }
        return output.ToString();
    }
}

GenerateRandomSalt方法可用于为您的密码生成salt。在SO上还有很多其他问题涉及这类事情。

您可以使用类似SHA1的HASHES对密码进行编码。

Function getSHA1Hash(ByVal strToHash As String) As String
  Dim sha1Obj As New Security.Cryptography.SHA1CryptoServiceProvider
  Dim bytesToHash() As Byte = System.Text.Encoding.ASCII.GetBytes(strToHash)
  bytesToHash = sha1Obj.ComputeHash(bytesToHash)
  Dim strResult As String = ""
  For Each b As Byte In bytesToHash
      strResult += b.ToString("x2")
  Next
  Return strResult
End Function

使用它很简单!

Console.Write(getSHA1Hash("password"))

因此,每当你需要对用户进行身份验证时,你可以获取他的输入密码,使用上面的函数计算它的哈希,并确保它与简单的IF子句相同:

if getSHA1Hash(input_password) = HASHED_OLD_PASSWORD then Authenticate()

SHA1哈希是不可解密的,如果没有完全的暴力手段,它是一个非常安全的解决方案。

最新更新