【问题标题】:Why is my MD5 value printing with extra "f" characters?为什么我的 MD5 值打印带有额外的“f”字符?
【发布时间】:2011-04-28 04:57:46
【问题描述】:

我在使用 std::string 的 at() 方法时遇到了奇怪的问题。我想使用这个库计算给定字符串的 md5 哈希:http://sourceforge.net/projects/libmd5-rfc/files/ 哈希计算正确,但以人为方式打印存在问题。输出是:

af04084897ebbf299b04082d105ab724
ffffffaf040848ffffff97ffffffebffffffbf29ffffff9b04082d105affffffb724

代码是:

  #include <stdio.h>
  #include<string>
  #include<iostream>

  extern "C" {
      #include "md5.h"
  }

  int main()
  {
      md5_state_t state;
      md5_byte_t digest[16];

      std::string callid("f83bc385-26da-df11-95d5-0800275903dd@pc-archdev");

      md5_init(&state);
      md5_append(&state, (const md5_byte_t*)callid.c_str(), callid.length());

      std::string callid_digest((const char*)digest, 16);

      for(int i = 0; i < 16; ++i) {
          printf("%02x", digest[i]);
      }

      printf("\n");

      for(int i = 0; i < 16; ++i) {
          const char c = callid_digest.at(i);
          printf("%02x", c);
      }

      printf("\n");
  }

“f”字符从何而来?

【问题讨论】:

  • pejotr,我购买了代码,因为人们认为问题尽可能独立。我还更改了标题以使其更能说明问题。希望你不要介意。干杯。

标签: c++ md5 stdstring


【解决方案1】:

您的字节值正在符号扩展。

当您将 (signed) char 提升为更宽的类型并设置最高位时会发生这种情况,因为它试图保留符号(这就是为什么您只看到大于的值的额外 f 字符0x7f)。使用unsigned char 应该可以解决问题:

const unsigned char c = callid_digest.at(i); // may need to cast.

【讨论】:

  • 或者更好,使用md5_byte_t,即unsigned char
  • 或使用 std::cout 以便自动检测类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-28
相关资源
最近更新 更多