将字节转换为基本字符串

时间:2018-11-16 11:25:23

标签: c# string

Payload=ABCDEFGHIJKLMNOPQR; basetoConvert = hexa

public static string SHA256HashToBaseMessage(string payload, eBase baseToConvert)
{                        
    StringBuilder sb;
    using (SHA256 sHA256 = SHA256.Create("SHA256"))
    {
        byte[] hash = sHA256.ComputeHash(Encoding.UTF8.GetBytes(payload));
        sb = new StringBuilder();
        for (int i = 0; i < hash.Length; i++)
        {                    
            sb.Append(Convert.ToString((hash[i] & 0xff) + 0x100, (int)baseToConvert).Substring(1));
        }
    }
    return sb.ToString();
}

public enum eBase
{
    BINARY=2,
    OCTAL=8,
    DECA=10,
    HEXA=16
}

上面是我的代码,用于生成字节的相应基本字符串。我使用了文档中给出的代码。 我的问题是我何时使用这部分代码,例如

sb.Append(Convert.ToString(hash[i], (int)baseToConvert));

输出为:

38d3bed3499804995bda3123885d4f3eab0c19efc2dd03df5be147b359ceed

但是当我使用代码作为文档时,

sb.Append(Convert.ToString((hash[i] & 0xff) + 0x100, (int)baseToConvert).Substring(1));

对于相同的有效负载,输出为(上方的原始版本在下面,以进行比较-差异为空间)

38d3bed34909804995bda3123885d4f3eab0c19efc2dd03df5be0147b359ceed
38d3bed349 9804995bda3123885d4f3eab0c19efc2dd03df5be 147b359ceed -- original

有人可以解释为什么输出有所不同吗? (hash [i]&0xff)+ 0x100)实际上在做什么?

1 个答案:

答案 0 :(得分:0)

我认为通过位操作应用 format (添加前导零)不是一个好主意。让我们用PadLeft明确地做到这一点:

public static string SHA256HashToBaseMessage(string payload, eBase baseToConvert) {
  //DONE: public method values' validation 
  if (null == payload)
    throw new ArgumentNullException(nameof(payload));

  int padLength =
    (baseToConvert == eBase.BINARY) ? 8 : // 8 for binary
    (baseToConvert == eBase.HEXA) ? 2 :   // 2 for hexadecimal
    3;                                    // 3 for decimal and octal

  StringBuilder sb = new StringBuilder();

  using (SHA256 sHA256 = SHA256.Create("SHA256")) {
    byte[] hash = sHA256.ComputeHash(Encoding.UTF8.GetBytes(payload));

    for (int i = 0; i < hash.Length; i++) 
      sb.Append(Convert.ToString(hash[i], (int)baseToConvert).PadLeft(padLength, '0'));
  }
  return sb.ToString();
}

如果运行此代码,您将得到

38d3bed34909804995bda3123885d4f3eab0c19efc2dd03df5be0147b359ceed
          ^                                         ^
          padding: 9 -> "09"                        padding: 1 -> "01"

如果您删除填充,则.PadLeft(padLength, '0')0都不会出现

38d3bed3499804995bda3123885d4f3eab0c19efc2dd03df5be147b359ceed
         ^                                         ^
         no padding: 9 -> "9"                      no padding: 1 -> "1"