简体   繁体   中英

Converting uint_32t integers to byte array

This is the python code to get byte array and calculate SHA1 after performing concatenation of previous(n-1) hash with ibytes.

***for i in range(50000):
    ibytes = pack("<I", i)
    h = sha1(ibytes + h).digest()***

What could be the best possible way in C++ to implement above code,where I have C++ sha1 code already in place and accepts parameter of void* type.

I tried below code. But SHA value being generated is wrong starting from iterator == 0

 BYTE pBuffer[24];
                
 char fbuf[4];
 sprintf(fbuf, "%02X%02X%02X%02X", (unsigned)val & 0xFF,
                     (unsigned)(val >> 8) & 0xFF,
                     (unsigned)(val >> 16) & 0xFF,
                     (unsigned)(val >> 24) & 0xFF);

 pBuffer[0] = fbuf[0];
 pBuffer[1] = fbuf[1];
 pBuffer[2] = fbuf[2];
 pBuffer[3] = fbuf[3];
memcpy(pBuffer + 4, hn, SHA_DIGEST_LENGTH);

Following the suggestions from @wohlstad and @john, I modified the code as

fbuf[0] = (unsigned)(val>>0) & 0xFF;
fbuf[1] = (unsigned)(val >> 8) & 0xFF;
fbuf[2] = (unsigned)(val >> 16) & 0xFF;
fbuf[3] = (unsigned)(val >> 24) & 0xFF;

This worked.

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