【发布时间】:2017-12-14 00:31:43
【问题描述】:
我正在尝试在 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 go cryptography sha512