【问题标题】:SHA512 encoding in pythonpython中的SHA512编码
【发布时间】:2021-09-26 20:43:58
【问题描述】:

我需要有关 python 中 sha512 编码的帮助。我正在尝试编写一段应该与c#代码一致的python代码。

这是C#中的方法

public string GenerateSHA512Hash(string data, sting salt) {
  data = data.Replace(" ", string.Empty).Replace("\n", string.Empty).Replace("\t", string.Empty).Replace("\r", string.Empty).Trim();

  data = data + salt;

  byte[] HashedBytes = Encoding.UTF8.GetBytes(data);

  using(SHA512Managed hash = new SHA512Managed()) {
    for (int j = 0; j < 2; j++) {
      HashedBytes = hash.ComputeHash(HashedBytes);
      var text = HashedBytes.ToBase16();
    }
  }

  return HashedBytes.ToBase16();
}

我在 python 中得到了以下内容

import hashlib

def HashPAN(pan: str, salt: str):
    data: str = pan + salt
    data = data.replace(" ", "").replace("\n", "").replace("\t", "").replace("\r", "")
    data_bytes = data.encode("utf-8")

    hasher = hashlib.sha512()

    # First Iteration
    hasher.update(data_bytes)
    hashed = hasher.digest()
    h = hasher.hexdigest().upper()

    # Second Iteration
    hasher.update(hashed)
    hashed = hasher.digest()
    h = hasher.hexdigest().upper()

    return hashed

在 python 中,标记为#First Iteration 的部分的结果与 C# 代码中循环中第一次的结果相匹配(h = 文本)。

但是,python 中的第二次与 c# 中的第二次不匹配。有人可以帮忙吗

【问题讨论】:

  • 您不应该只拥有hexdigest 而不是digesthexdigest 吗?
  • @ChatterOne 我正在做十六进制只是为了获取和查看字符串值。

标签: python sha512


【解决方案1】:

我想出了如何在 python 中做到这一点

def HashPAN(pan: str, salt: str):
    data: str = pan + salt
    data = data.replace(" ", "").replace("\n", "").replace("\t", "").replace("\r", "")
    data_bytes = data.encode("utf-8")
    hashed_text: str

    for i in range(2):
        hasher = hashlib.sha512()
        hasher.update(data_bytes)
        data_bytes = hasher.digest()
        hashed_text = hasher.hexdigest()

    return hashed_text.upper()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 2015-01-29
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2016-02-21
    相关资源
    最近更新 更多