我正试图在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));
}在围棋中:
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行呢?
发布于 2017-12-13 15:49:51
Java中的byte类型是签名的,它有一个范围的-128..127,而在Go中,byte是uint8的别名,并且有一个范围的0..255。因此,如果要比较结果,就必须通过256 (添加256)来转换负的256值。
提示:要以无符号方式显示Java byte值,请使用:byteValue & 0xff将其转换为int,使用byte的8位作为int__中最低的8位。或者更好:显示这两种形态的结果,这样你就不用关心符号了.
在负Java字节值中添加256个,输出的几乎与Go‘s相同:最后一个字节关闭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中返回十六进制编码的结果,而在Go中则返回Base64编码的结果(它们是两个不同的编码,结果完全不同)。正如您确认的,在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 https://stackoverflow.com/questions/47797100
复制相似问题