Java与Golang for HOTP(rfc-4226)

Zac*_*man 5 java cryptography go sha512

我正在尝试在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));
}
Run Code Online (Sandbox Code Playgroud)

在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))
}
Run Code Online (Sandbox Code Playgroud)

我认为问题在于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行?

icz*_*cza 10

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

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

在负的Java字节值中加256,输出几乎与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)
Run Code Online (Sandbox Code Playgroud)

输出是:

[83 140 247 158 115 130 253 208]
Run Code Online (Sandbox Code Playgroud)

所以你的Java数组的最后一个字节是208Go的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), " ")
}
Run Code Online (Sandbox Code Playgroud)

这输出:

83 -116 -9 -98 115 -126 -3 -49 
Run Code Online (Sandbox Code Playgroud)

  • @ZachKauffman Base64和十六进制编码是完全不同的东西(给出完全不同的结果).所以基本上长 - >字节数组转换在你的情况下是正确的,但在你的例子中``counter`值是不同的. (2认同)