在 Kotlin 中生成 HMAC-SHA1 签名

问题描述

我正在尝试使用他们的 API 从数据库获取产品。

文档内容如下:

The "signature" is an encrypted version of the UPC or EAN code that is SHA-1 hashed with your authorization key

我曾尝试在 Kotlin 中执行此操作,但返回“无效签名”。

object HmacSha1Signature {
    private val HMAC_SHA1_ALGORITHM = "HmacSHA1"

    private fun toHexString(bytes: ByteArray): String {
        val formatter = Formatter()

        for (b in bytes) {
            formatter.format("%02x",b)
        }

        return formatter.toString()
    }

    @Throws(SignatureException::class,NoSuchAlgorithmException::class,InvalidKeyException::class)
    fun calculateRFC2104HMAC(data: String,key: String): String {
        val encoder = Base64.getEncoder()
        // get an hmac_sha1 key from the raw key bytes
        val signingKey = SecretKeySpec(key.toByteArray(),"HmacSHA1")
        // get an hmac_sha1 Mac instance and initialize with the signing key
        val mac = Mac.getInstance("HmacSHA1")
        mac.init(signingKey)
        // compute the hmac on input data bytes
        val rawHmac = mac.doFinal(data.toByteArray())
        return encoder.encodetoString(rawHmac)
    }
}

URL 的格式是正确的,因为它表示无效签名。

我相信它需要 64 位编码。因为他们提供了其他语言的示例,似乎除了 Java 之外的每一个都提供:(

C#

private string GetDigitEyesverificationCode(string UpcCode) {
    var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(AuthKey));
    var m = hmac.ComputeHash(Encoding.UTF8.GetBytes(UpcCode));
    return Convert.ToBase64String(m);
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)