【问题标题】:Store a formated printed value in a new variable将格式化的打印值存储在新变量中
【发布时间】:2015-12-22 01:14:02
【问题描述】:

在加密函数 (sha256) 中,我有这段代码用于打印最终结果:

void print_hash(unsigned char hash[]) 
   {
       int idx;
       for (idx=0; idx < 32; idx++)
          printf("%02x",hash[idx]);
       printf("\n");
    }

当hash进入函数时是这样的:

/A�`�}#.�O0�T����@�}N�?�#=\&@

然后,通过循环,我进入控制台

182f419060f17d2319132eb94f30b7548d81c0c740977d044ef1edbb9b97233d

我想知道如何在控制台中将最终值存储在变量中。 我读过一些关于 sscanf 的文章,但你能帮帮我吗?

【问题讨论】:

  • 你应该阅读的函数sprintf
  • ... strcat。或者阅读指针算法
  • SHA256 不是加密,是单向哈希函数,无法从生成的哈希中恢复原始数据。

标签: c sha256


【解决方案1】:

您可以使用sprintf 将其存储在一个数组中(通过指针传入参数):

void print_hash(unsigned char hash[], unsigned char output[])
{
    int idx;
    for (idx = 0; idx < 32; idx++)
        sprintf(&output[2 * idx], "%02x", hash[idx]);
}

确保为output 中的空终止符保留一个额外的字节(即char output[2 * 32 + 1])。

【讨论】:

  • 你也需要在循环体中增加output,否则输出将只是最后一个元素。
  • @ouah 那应该是&amp;output[2*idx],假设每次循环迭代附加 2 个字符。
  • 试试char *result = output; result += sprintf(result, "%02x", hash[idx]);
  • 谢谢大家。谁能告诉我为什么我的问题有-1分? :c
【解决方案2】:

使用sprintf,此函数将其输出(相当于printf 写入控制台的内容)存储在字符串缓冲区中。在您的情况下如何使用它的示例:

char buffer[65]; //Make this buffer large enough for the string and a nul terminator
for(int idx = 0; idx < 32; ++idx)
{
    sprintf(&buffer[2*idx], "%02x", hash[idx]); //Write to the correct position in the buffer
}

终止的 nul 字符由 sprintf 自动附加。

【讨论】:

    【解决方案3】:

    你也可以避免使用sprintf(),像这样做一个更高效的函数

    void
    hash2digest(char *result, const char *const hash, size_t length)
    {
        const char *characters = "0123456789abcdef";
        for (size_t i = 0 ; i < length ; ++i)
        {
            result[2 * i] = characters[(hash[i] >> 0x04) & 0x0F];
            result[2 * i + 1] = characters[hash[i] & 0x0F];
        }
        result[2 * length] = '\0';    
    }
    

    请注意,您可以像这样从任何地方调用它(假设 hash 已经声明和定义)

    char digest[65];
    hash2digest(digest, hash, 32);
    

    这又可以重复用于SHA1,例如,像这样

    char digest[41];
    hash2digest(digest, hash, 20);
    

    并使用动态内存分配

    char *
    hash2digest(const char *const hash, size_t length)
    {
        const char *characters = "0123456789abcdef";
        char *result;
        result = malloc(2 * length + 1);
        if (result == NULL)
            return NULL;
        for (size_t i = 0 ; i < length ; ++i)
        {
            result[2 * i] = characters[(hash[i] >> 0x04) & 0x0F];
            result[2 * i + 1] = characters[hash[i] & 0x0F];
        }
        result[2 * length] = '\0';
    
        return result;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-10
      • 2013-06-20
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多