简体   繁体   中英

SHA512 encoding in python

I need help with regards to sha512 encoding in python. I am trying to write a piece of python code that should be in line with c# code.

Here is the method in 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();
}

I got the following in 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

In python, the results from section labeled #First Iteration matches the result from the first time in the loop in C# code (h = text).

However, the second time in python does not match the second time in c#. can someone please assist

I figured out how to do this in 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM