返回多个哈希字符串

时间:2013-02-07 12:25:36

标签: c# asp.net md5

我有以下功能:

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

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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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'
}