2016-12-01 34 views
-3

我想改变公共类中的返回值。如何公共字符串返回编辑文本?

我想使MD5加密。 我该怎么做。 我在msdn.microsoft.com上搜索,但我没有。 :(

 public string Password { 
     get { return SystemProccess.MD5Encrypt(Password); } 
    } 
+0

'我搜索了msdn',你搜索了什么?如何写一个属性?如何使用'System.Security.Cryptography.MD5'?看到'C#MD5'的谷歌的第一个结果:) –

+0

只使用哈希函数是不够的,只是添加盐没有什么提高安全性。取而代之的是用随机盐对HMAC进行大约100毫秒的持续时间并用散列表保存盐。使用诸如“PBKDF2”,“password_hash”,“Bcrypt”等功能。关键是要让攻击者花费大量时间通过强力查找密码。保护您的用户非常重要,请使用安全的密码方法。 – zaph

回答

1

它看起来像你可能有一个循环引用。您可能需要使用第二个属性,一到设定密码为明文,而另一个得到加密的一个。

public string Password { get; set; } 

public string EncryptedPassword { 
    get { return GetMd5Hash(Password); } 
} 

我发现下面的代码方法从MSDN生成散列。https://msdn.microsoft.com/en-us/library/system.security.cryptography.md5(v=vs.110).aspx,要确保你有适当的命名空间。

using System; 
using System.Security.Cryptography; 
using System.Text; 

然后将以下添加到您的类。

static string GetMd5Hash(MD5 md5Hash, string input) 
{ 

    // Convert the input string to a byte array and compute the hash. 
    byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); 

    // Create a new Stringbuilder to collect the bytes 
    // and create a string. 
    StringBuilder sBuilder = new StringBuilder(); 

    // Loop through each byte of the hashed data 
    // and format each one as a hexadecimal string. 
    for (int i = 0; i < data.Length; i++) 
    { 
     sBuilder.Append(data[i].ToString("x2")); 
    } 

    // Return the hexadecimal string. 
    return sBuilder.ToString(); 
} 

如果为了安全起见,如果您不想存储原始密码,可以使用setter。请注意,该属性使用专用字段来存储和访问加密值,因此未存储原始未加密的密码。

private string _EncryptedPassword = null; 
public string EncryptedPassword 
{ 
    get { return _EncryptedPassword ; } 
    set { _EncryptedPassword = GetMd5Hash(value); } 
} 

让我知道这是否有帮助。

+0

'Convert.ToBase64String(data)'? 'BitConverter.ToString(data)'?你不觉得他们更简单吗? –

+0

你说得对。 OP提到了MSDN,所以我想把它作为教程加入,但我一定会偶然发现有点过时的。 –

+0

他还提到了MD5加密。这与Base64相同吗?我对密码学不太熟悉。 –

相关问题