Home >Backend Development >Golang >Java vs. Golang HOTP Implementation: Why the Discrepancy in Generated Values?

Java vs. Golang HOTP Implementation: Why the Discrepancy in Generated Values?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-16 10:15:13970browse

Java vs. Golang HOTP Implementation: Why the Discrepancy in Generated Values?

Java vs. Golang for HOTP (rfc-4226)

Issue: Discrepancy in HOTP Generation Between Java and Golang

In attempting to implement HOTP using Java and Golang, a discrepancy was noticed in the generated values. While Java successfully produced a valid HOTP, the Golang implementation differed.

Understanding the Difference

The issue stems from the differing representation of byte types in Java and Go. Java's byte is signed, ranging from -128 to 127, while Golang's byte is an alias of uint8, ranging from 0 to 255.

In the Java code, the line ByteBuffer.allocate(8).putLong(counter).array(); generates an array of bytes from the counter value. However, in Golang, binary.BigEndian.PutUint64(bs, counter) converts the counter to a big-endian representation, resulting in different byte values.

Solution

To port the Java code to Go and ensure the same byte array is generated, one must shift negative values in the Java array by 256 to convert them to unsigned integers. This can be achieved using the code:

for (int i = 0; i < javabytes.length; i++) {
  if (javabytes[i] < 0) {
    javabytes[i] += 256;
  }
}

Additionally, note that the Java code uses hex encoding for the final result, while the Golang code uses Base64 encoding. To match the Java output, one must use hex.EncodeToString(h.Sum(nil)) in the Golang code.

Tips for Debugging

  • To display Java byte values in an unsigned fashion, use byteValue & 0xff.
  • To display Golang byte values in a signed fashion, convert them to int8.

The above is the detailed content of Java vs. Golang HOTP Implementation: Why the Discrepancy in Generated Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn