如何公开字符串返回编辑文本



我想更改公共类中的返回值。

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

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

看起来您可能有圆形参考。您可能需要使用第二个属性,一个属性将密码设置为纯文本,而将密码设置为加密。

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

如果为了安全性,以防您不想存储原始密码,则可以使用设置器。请注意,该属性使用私有字段存储和访问加密值,因此未存储原始的未加密密码。

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

让我知道这是否有帮助。

最新更新