【问题标题】:How to convert a raw 64-byte binary to Hex or ASCII in C如何在 C 中将原始 64 字节二进制文件转换为十六进制或 ASCII
【发布时间】:2018-05-21 23:57:10
【问题描述】:

我在 C 中使用 SHA512 来获取哈希值。我是这样做的:

#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

我尝试通过以下方式将其转换为十六进制:

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;
    }

但这不是我想要的。

如何将 unsigned char 中的二进制文件转换为人类可读的格式?用于打印的 char[] 中的最佳情况。

“要散列的数据”的散列应该是:

d98f945fee6c9055592fa8f398953b3b7cf33a47cfc505667cbca1adb344ff18a4f442758810186fb480da89bc9dfa3328093db34bd9e4e4c394aec083e1773a

【问题讨论】:

    标签: c hash binary type-conversion sha512


    【解决方案1】:

    只需在 printf() 中使用 %x 打印每个字符。不要转换,只使用原始数据:

    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");
    }
    

    编辑为只输出十六进制值,没有逗号或空格。

    【讨论】:

    • 完美,非常感谢。我不知道这很容易。我可以使用 sprintf 和 for 循环将最终字符串保存在变量中吗?
    • @Henne。那将是使用 sprintf() 的好地方
    猜你喜欢
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 2015-12-02
    • 2016-07-07
    • 2014-07-14
    • 1970-01-01
    • 2014-11-16
    相关资源
    最近更新 更多