使用 HMAC SHA1 哈希为 DigitEyes 签署请求时出现问题 Api

Problems with sigining a request using HMAC SHA-1 hashing for DigitEyes Api

我一直在尝试签署对 DigitEyes 条码的请求 api 以便我可以检索给定条码的产品信息。但是,对于请求,我必须提交使用授权密钥的 SHA-1 散列以及 UPC 和 base64 加密结果生成的签名。吨 但是,无论我尝试多少,我都无法获得他们在示例中生成的签名。

他们使用的字段是: 授权密钥("M" 代码):Cf47U2b4d4Vt5Gz8

样本UPC/EAN:5201279013028

他们得到了: 签名样本:Mb+LqZ7PM4bGxJDAWB/n7/LSj9A=

有如下所示的示例,但是其中 none 使用 JAVA,这是我尝试使用的语言。示例如下所示。

http://www.digit-eyes.com/specs/UPCAPIImplementation.pdf

我正在使用的代码如下所示,我相信它可以工作,但没有给我他们所拥有的。

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Formatter;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class HmacSha1Signature {
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

    private static String toHexString(byte[] bytes) {
        Formatter formatter = new Formatter();

        for (byte b : bytes) {
            formatter.format("%02x", b);
        }

        return formatter.toString();
    }

    public static String calculateRFC2104HMAC(String data, String key)
        throws SignatureException, NoSuchAlgorithmException, InvalidKeyException
{
    SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    return toHexString(mac.doFinal(data.getBytes()));
}

public static void main(String[] args) throws Exception {
    String hmac = calculateRFC2104HMAC("5201279013028", "Cf47U2b4d4Vt5Gz8");

    System.out.println(hmac);
    byte[] encodedBytes = Base64.encodeBase64(hmac.getBytes());
    System.out.println("encodedBytes " + new String(encodedBytes));
    byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
    System.out.println("decodedBytes " + new String(decodedBytes));

    }
}

看起来问题出在 toHexString()
不要将 mac.doFinal() 输出转换为十六进制
将输出字节直接转成base64即可得到需要的结果。