Java与Golang for HOTP(rfc-4226)

我正在尝试在Golang中实现HOTP(rfc-4226),我正在努力生成有效的HOTP。 我可以在java中生成它但由于某种原因我在Golang中的实现是不同的。 以下是样本:

public static String constructOTP(final Long counter, final String key) throws NoSuchAlgorithmException, DecoderException, InvalidKeyException { final Mac mac = Mac.getInstance("HmacSHA512"); final byte[] binaryKey = Hex.decodeHex(key.toCharArray()); mac.init(new SecretKeySpec(binaryKey, "HmacSHA512")); final byte[] b = ByteBuffer.allocate(8).putLong(counter).array(); byte[] computedOtp = mac.doFinal(b); return new String(Hex.encodeHex(computedOtp)); } 

在Go:

 func getOTP(counter uint64, key string) string { str, err := hex.DecodeString(key) if err != nil { panic(err) } h := hmac.New(sha512.New, str) bs := make([]byte, 8) binary.BigEndian.PutUint64(bs, counter) h.Write(bs) return base64.StdEncoding.EncodeToString(h.Sum(nil)) } 

我相信问题是Java行: ByteBuffer.allocate(8).putLong(counter).array(); 生成与Go行不同的字节数组: binary.BigEndian.PutUint64(bs, counter)

在Java中,生成以下字节数组: 83 -116 -9 -98 115 -126 -3 -48和Go: 83 140 247 158 115 130 253 207

有没有人知道这两行的区别以及如何移植java行?

Java中的byte类型是有符号的,它的范围是-128..127 ,而Go byteuint8的别名,范围是0..255 。 因此,如果要比较结果,则必须将负Java值移动256 (添加256 )。

提示:要以无符号方式显示Java byte值,请使用: byteValue & 0xff ,使用byte的8位作为int的最低8位将其转换为int 或者更好:以hexforms显示两个结果,这样您就不必关心签名……

将256加到负的Java字节值,输出几乎与Go的相同:最后一个字节关闭1:

 javabytes := []int{83, -116, -9, -98, 115, -126, -3, -48} for i, b := range javabytes { if b < 0 { javabytes[i] += 256 } } fmt.Println(javabytes) 

输出是:

 [83 140 247 158 115 130 253 208] 

所以Java数组的最后一个字节是208而Go是207 。 我猜你的counter会在你未发布的代码中的其他位置递增一次。

不同的是,在Java中,您返回hex编码结果,而在Go中,您返回Base64编码结果(它们是两种不同的编码,给出完全不同的结果)。 如你hex.EncodeToString(h.Sum(nil)) ,在Go中返回hex.EncodeToString(h.Sum(nil)) ,结果匹配。

提示#2:要以签名方式显示Go的字节,只需将它们转换为int8 (已签名),如下所示:

 gobytes := []byte{83, 140, 247, 158, 115, 130, 253, 207} for _, b := range gobytes { fmt.Print(int8(b), " ") } 

这输出:

 83 -116 -9 -98 115 -126 -3 -49