1

Currently I have this code written in nodejs.

const sha256 = require('js-sha256').sha256;
var stringl = "8d12a197cb00d4747a1fe03395095ce2a5cc68198f3470a7388c05ee4e7af3d01d8c722b0ff5237400000000000000000000000000000000000000000000000000000000000000b40000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003600000000000000000000000000000000000000000000000000000000004c4b40000000000000000000000000000000000000000000000000000000000001e240"
console.log(sha256(new Buffer(stringl, 'hex')));

it returns

2c0a99a5727be633e440dd8ce2090a0ab7d5a84ccafc9385ea9812db4d715df1

I want to convert the code from nodejs to python (3.5) .

I thought I could just do it with this code.

import hashlib
string21 = "8d12a197cb00d4747a1fe03395095ce2a5cc68198f3470a7388c05ee4e7af3d01d8c722b0ff5237400000000000000000000000000000000000000000000000000000000000000b40000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003600000000000000000000000000000000000000000000000000000000004c4b40000000000000000000000000000000000000000000000000000000000001e240"
print(hashlib.sha256(str(int(string21,16)).encode('utf-8')).hexdigest())

but that returns

346c61765546d4ff12fdbea997f40bdb5216b8df2b5402a6b45893df723132f6

any ideas?

1
  • Hint: Look at what str(int(string21,16)) returns. Commented Oct 22, 2017 at 20:03

1 Answer 1

2

Buffer returns an array of bytes (integers in range(0, 256)), so you need to do the same thing in Python:

print(hashlib.sha256(bytearray.fromhex(string21)).hexdigest())

bytearray.fromhex does exactly what it says: creates a bytearray from a hexadecimal representation.

EDIT: there's no need to encode anything here as bytearrays already represent bytes.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent ! Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.