返回多个哈希字符串

本文关键字:字符串 哈希 返回 | 更新日期: 2023-09-27 17:58:22

我有以下功能:

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

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

返回多个哈希字符串

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

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;
}
    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 u作为IEnumerable<String>

的典型用法

var values = GetRaumImageName();
foreach(value in values)
{
    // use the 'value'
}