简体   繁体   English

在 C++ 和 JAVA 中发现相同字符串的 SHA-1 不同

[英]SHA-1 for same string found different in C++ and JAVA

SHA-1 for the same string is different is Java and C++相同字符串的 SHA-1 不同的是 Java 和 C++

String to hash - 38902566字符串到 hash - 38902566

SHA-1 in java - 6ffc3d4038943971cd91db0cf0f3de8ecf1b2853 (confirmed online sha1 tool produces same) java - 6ffc3d4038943971cd91db0cf0f3de8ecf1b2853 中的 SHA-1(确认在线 sha1 工具产生相同的结果)

SHA-1 in C++ - 093288D2933CE7D55295450EBFE711F3E1AE3BF2 C++ 中的 SHA-1 - 093288D2933CE7D55295450EBFE711F3E1AE3BF2

Java implementation: Java实现:

  MessageDigest md = MessageDigest.getInstance("SHA-1");
  byte[] messageDigest = md.digest(customerId.getBytes());
  BigInteger no = new BigInteger(1, messageDigest);

  String hashtext = no.toString(16);

  while (hashtext.length() < 32) {
    hashtext = "0" + hashtext;
  }
  return hashtext;

C++ implementation C++ 实现

int hash_SHA1(const char* cid, int len, char* digest)
{
    /* Creating Id Digest. */
    int rc = 0, i;
    unsigned char idDgst[21] = { '\0' };
    char buffer[3] = { '\0' };

    rc = SHA1(cid, len, idDgst) == NULL ? -1 : 0;
    for(i = 0; !rc && (i < sizeof(idDgst)-1); i++)
    {
        sprintf(buffer, "%02X", idDgst[i]);
        strncat(digest, buffer, 3);
    }
    return rc == 0;
}

C++ code was shared with me to implement in Java. C++ 代码与我共享以在 Java 中实现。 What am I doing wrong here?我在这里做错了什么?

There was extra char getting appended to the input string from where the function was called in the C code.在 C 代码中调用 function 的输入字符串中附加了额外的字符。 Giving the right input gave the exact same result.给出正确的输入给出了完全相同的结果。 Thanks @Topaco, for validating the code.感谢@Topaco,用于验证代码。

Java can use 16-bit for each character in String. Java 可以对 String 中的每个字符使用 16 位。 C++ - not. C++ - 不是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM