Home >Backend Development >Golang >Java vs. Golang HOTP Implementation: Why the Discrepancy in Generated Values?
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.
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.
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.
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!