Pergunta

Estou procurando um Java equivalente a esta chamada PHP:

hash_hmac('sha1', "test", "secret")

Eu tentei isso usando java.crypto.mac, mas os dois não concordam:

String mykey = "secret";
String test = "test";
try {
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(mykey.getBytes(),"HmacSHA1");
    mac.init(secret);
    byte[] digest = mac.doFinal(test.getBytes());
    String enc = new String(digest);
    System.out.println(enc);  
} catch (Exception e) {
    System.out.println(e.getMessage());
}

As saídas com key = "secret" e test = "teste" não parecem corresponder.

Foi útil?

Solução

Na verdade, eles concordam.
Como o Hans Doggen já observou o PHP, o PHP produz o resumo da mensagem usando a notação hexadecimal, a menos que você defina o parâmetro de saída bruto como true.
Se você quiser usar a mesma notação em java, você pode usar algo como

for (byte b : digest) {
    System.out.format("%02x", b);
}
System.out.println();

para formatar a saída de acordo.

Outras dicas

Você pode tentar isso em Java:

private static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException {

    SecretKey secretKey = null;

    byte[] keyBytes = keyString.getBytes();
    secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");

    Mac mac = Mac.getInstance("HmacSHA1");

    mac.init(secretKey);

    byte[] text = baseString.getBytes();

    return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
}

Esta é a minha implementação:

        String hmac = "";

    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(llave.getBytes(), "HmacSHA1");
    mac.init(secret);
    byte[] digest = mac.doFinal(cadena.getBytes());
    BigInteger hash = new BigInteger(1, digest);
    hmac = hash.toString(16);

    if (hmac.length() % 2 != 0) {
        hmac = "0" + hmac;
    }

    return hmac;

Parece -me que o PHP usa a notação hexadecimal para os bytes que Java produz (1A = 26) - mas não verifiquei toda a expressão.

O que acontece se você executar a matriz de bytes através do método em isto página?

Minha implementação para o HMACMD5 - basta alterar o algoritmo para hmacsha1:

SecretKeySpec keySpec = new SecretKeySpec("secretkey".getBytes(), "HmacMD5");
Mac mac = Mac.getInstance("HmacMD5");
mac.init(keySpec);
byte[] hashBytes = mac.doFinal("text2crypt".getBytes());
return Hex.encodeHexString(hashBytes);

Não testei, mas tente o seguinte:

        BigInteger hash = new BigInteger(1, digest);
        String enc = hash.toString(16);
        if ((enc.length() % 2) != 0) {
            enc = "0" + enc;
        }

Isso é instantâneo do meu método que torna o MD5 e o SHA1 PHP de Java.

Dessa forma, eu poderia obter exatamente a mesma string que estava recebendo com hash_hmac em php

String result;

try {
        String data = "mydata";
        String key = "myKey";
        // Get an hmac_sha1 key from the raw key bytes
        byte[] keyBytes = key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.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");
        out.println("MAC : " + result);
}
catch (Exception e) {

}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top