【问题标题】:Return Multiple strings of hash返回多个哈希字符串
【发布时间】:2013-02-07 12:25:35
【问题描述】:

我有以下功能:

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

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

【问题讨论】:

  • 你能返回一个IEnumerable&lt;String&gt; 而不是一个String吗?

标签: c# asp.net md5


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
        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();
            }          
        }
    

    这将返回您需要的所有ValuesIEnumerable&lt;String&gt;

    典型用法

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

    【讨论】:

      猜你喜欢
      • 2021-10-01
      • 2016-07-24
      • 1970-01-01
      • 2021-11-19
      • 2020-04-05
      • 2013-11-21
      • 2014-04-08
      • 2016-07-24
      • 2015-11-28
      相关资源
      最近更新 更多