我正在尝试在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). …