在Java中使用Base64 HMAC SHA1无法获得预期的结果

时间:2012-09-08 10:59:46

标签: java base64 hmacsha1

我正在尝试使用HMAC SHA1单向算法

这是我的代码

@Test
public void encodeTest() {

    String HMAC_SHA1_ALGORITHM = "HmacSHA1";
    String EXPECTED_BASE_64 = "g9OrJ8pQNYprnXuBPFXcirrqpxE=";

    String text = "encodeme";
    String result;

    try {
        SecretKeySpec signingKey = new SecretKeySpec(
                "MSbN2crsrdTEsLetTixpV46q+fTZotdZjwoEpO62vYk=".getBytes(),
                HMAC_SHA1_ALGORITHM);
        // Get an hmac_sha1 Mac instance and initialise with the signing key
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
        // Compute the hmac
        byte[] rawHmac = mac.doFinal(text.getBytes());
        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);
        // Covert array of Hex bytes to a String

        result = new String(hexBytes, "ISO-8859-1");
        // Ok, this matches with the web
        System.out.println("HEX:" + result);

        String encodedBase64 = new String(Base64.encodeBase64(hexBytes));
        System.out.println("BASE64:" + encodedBase64);

        // In the web i get a smaller chain, why?
        System.out.println("EXPECTED BASE64:" + EXPECTED_BASE_64);
        Assert.assertEquals(EXPECTED_BASE_64, encodedBase64);

    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

输出

HEX:83d3ab27ca50358a6b9d7b813c55dc8abaeaa711 BASE64:ODNkM2FiMjdjYTUwMzU4YTZiOWQ3YjgxM2M1NWRjOGFiYWVhYTcxMQ ==

预期BASE64:g9OrJ8pQNYprnXuBPFXcirrqpxE =

我使用这些在线网站定义了我的期望

http://hash.online-convert.com/sha1-generator

文本= encodeme

使用共享密钥

键= MSbN2crsrdTEsLetTixpV46q + fTZotdZjwoEpO62vYk =

我得到的结果略有不同

hex:83d3ab27ca50358a6b9d7b813c55dc8abaeaa711 HEX:83D3AB27CA50358A6B9D7B813C55DC8ABAEAA711 h:e:x:83:d3:ab:27:ca:50:35:8a:6b:9d:7b:81:3c:55:dc:8a:ba:ea:a7:11 base64:g9OrJ8pQNYprnXuBPFXcirrqpxE =

如您所见,十六进制输出匹配100%,但base64输出根本不匹配

为了验证问题不在该网站,我去了另一个 只是要使用base64对十六进制字符串进行编码,然后我得到了相同的结果......

http://tomeko.net/online_tools/hex_to_base64.php?lang=en

任何人都知道为什么会这样?

提前致谢!

0 个答案:

没有答案