How to convert a raw 64-byte binary to Hex or ASCII in C

北战南征 提交于 2021-02-10 16:17:49

问题


I´m using SHA512 in C to get an Hash-Value. I did it like this:

#include <stdlib.h>
#include <stdio.h>
#include <openssl/sha.h>

int main(int argc, char *argv[]){

    unsigned char hash[SHA512_DIGEST_LENGTH];

    char data[] = "data to hash";          //Test Data
    SHA512(data, sizeof(data) - 1, hash);  //Kill termination character
    //Now there is the 64byte binary in hash

I tried to convert it to hex by:

long int binaryval, hexadecimalval = 0, i = 1, remainder;

binaryval=(long int)hash;
        while (binaryval != 0)
        {
            remainder = binaryval % 10;
            hexadecimalval = hexadecimalval + remainder * i;
            i = i * 2;
            binaryval = binaryval / 10;
        }
        printf("Outpunt in Hex is: %lX \n", hexadecimalval);


        printf("%d\n",(long int) awhash );
        return 0;
    }

But this is not wat i wantet.

How can i convert the binary which is in a unsigned char into a human readable format? Best case in a char[] for printing.

The Hash for "data to hash" should be:

d98f945fee6c9055592fa8f398953b3b7cf33a47cfc505667cbca1adb344ff18a4f442758810186fb480da89bc9dfa3328093db34bd9e4e4c394aec083e1773a


回答1:


Just print each char using %x in a printf(). Don't convert, just use the raw data:

int main(int argc, char *argv[]){

  unsigned char hash[SHA512_DIGEST_LENGTH];

  char data[] = "data to hash";          //Test Data
  SHA512(data, sizeof(data) - 1, hash);  //Kill termination character

  //Now there is the 64byte binary in hash
  for(int i=0; i<64; i++)
  {
    printf("%02x", hash[i]);
  }
  printf("\n");
}

Edited to just output the hex value no commas or spaces.



来源:https://stackoverflow.com/questions/47702475/how-to-convert-a-raw-64-byte-binary-to-hex-or-ascii-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!