0

我有以下功能:

public string GetRaumImageName()
    {
         var md5 = System.Security.Cryptography.MD5.Create();
        byte[] hash = md5.ComputeHash(Encoding.ASCII.GetBytes("Michael"));
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hash.Length; i++)
        {
            sb.Append(hash[i].ToString("X2"));
        }
        return sb.ToString();
    }

这仅适用于一个值。

现在我想加密多个值。我尝试了一些东西:

public string GetRaumImageName()
    {
        var md5 = System.Security.Cryptography.MD5.Create();
        StringBuilder sb = new StringBuilder();
        byte[] hash = new byte[0];

        foreach (PanelView panelView in pv)
        {
            hash = md5.ComputeHash(Encoding.ASCII.GetBytes(panelView.Title));

        }

        for (int i = 0; i < hash.Length; i++)
        {
            sb.Append(hash[i].ToString("X2"));

        }

        return sb.ToString();
    }

但只有列表中的最后一个值才能加密。如何加密列表中的多个值并返回它们?

4

2 回答 2

2

将每个哈希添加到列表中,然后返回该列表:

public List<string> GetRaumImageName()
{
    var md5 = System.Security.Cryptography.MD5.Create();
    List<string> hashes = new List<string>();
    StringBuilder sb = new StringBuilder();
    byte[] hash = new byte[0];

    foreach (PanelView panelView in pv)
    {
        hash = md5.ComputeHash(Encoding.ASCII.GetBytes(panelView.Title));

        //clear sb
        sb.Remove(0, sb.Length);

        for (int i = 0; i < hash.Length; i++)
        {
            sb.Append(hash[i].ToString("X2"));
        }
        hashes.Add(sb.ToString());
    }
    return hashes;
}
于 2013-02-07T12:34:21.007 回答
1
    public IEnumerable<String> GetRaumImageName()
    {
        var md5 = System.Security.Cryptography.MD5.Create();

        byte[] hash = new byte[0];

        foreach (PanelView panelView in pv)
        {
            hash = md5.ComputeHash(Encoding.ASCII.GetBytes(panelView.Title));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));

            }
            yield return sb.ToString();
        }          
    }

这将返回Values您需要的所有内容IEnumerable<String>

典型用法

var values = GetRaumImageName();
foreach(value in values)
{
    // use the 'value'
}
于 2013-02-07T12:29:44.383 回答