Python SHA1 Integer -


i did 2 sha1 in c code, 1 string, , integer, , different result.

sha_init(&ctx); sha_update(&ctx, "1234", 4); sha = sha_final(&ctx);  unsigned n = 1234; sha_init(&ctx); sha_update(&ctx, &n, sizeof(n)); sha = sha_final(&ctx);  string  result:  7110eda4d09e62aa5e4a390b0a572acd2c220 integer result:  c7f07b846cc46631c2079cdd7179afdd783d643 

in python, it's easy string sha1

sha1 = hashlib.sha1() sha1.update('1234') sha1.hexdigest()  '7110eda4d09e062aa5e4a390b0a572ac0d2c0220' 

we can see string result same c code. how integer sha1 in python? because python sha1 doesn't support integer.

i tried following code, can't same result c code.

aint = unpack('>4b', pack('>i', 1234))    sha1 = hashlib.sha1() sha1.update(bytearray(aint)) sha1.hexdigest() 

'ac9928e78cf6ea117451ecd6654fea2adae73e21'

how integer sha1 in python?

i can't reproduce results in c, sha library using? openssl recommends sha1_* functions says sha_* included compatibility. these 2 give different results me, if you're comparing pythons sha1, should using sha1_*

#include <openssl/sha.h> #include <stdio.h>  int main(void) {     unsigned n = 1234;     unsigned char md[50];     sha_ctx c;      (int i=0; i<sizeof(n); i++) {         printf("%02x ", ((unsigned char*)&n)[i]);     }     printf("\n");      sha1_init(&c);     sha1_update(&c, &n, 4);     sha1_final(md, &c);      (int i=0; i<20; i++) {         printf("%02x", md[i]);     }     printf("\n");     return 0; } 

gives:

 d2 04 00 00  7b08e025e311c3dfcf5179b67c0fdc08e73de261 

which suggests you're packing bytes in wrong order in python implementation. should be:

>>> import hashlib >>> hashlib.sha1(b'\xd2\x04\x00\x00').hexdigest() '7b08e025e311c3dfcf5179b67c0fdc08e73de261' >>> hashlib.sha1(bytearray(unpack('>4b', pack('i', 1234)))).hexdigest() '7b08e025e311c3dfcf5179b67c0fdc08e73de261' 

(note no > in front of i) matches shasum above.

for reference, if use sha_* functions get

int main(void) {     unsigned n = 1234;     unsigned char md[50];     sha_ctx c;      sha_init(&c);     sha_update(&c, &n, 4);     sha_final(md, &c);      (int i=0; i<20; i++) {         printf("%02x", md[i]);     }     printf("\n");     return 0; }  3e491ac1d065d6d666e5e216e0cddf60fcb5be86 

which seems agree sha ("sha-0") value in python:

>>> hashlib.new('sha', b'\xd2\x04\x00\x00').hexdigest() '3e491ac1d065d6d666e5e216e0cddf60fcb5be86' 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -