Pregunta

Estoy buscando un java equivalente a esta llamada php:

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

Probé esto, usando java.crypto.Mac , pero los dos no están de acuerdo:

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());
}

Las salidas con clave = " secreto " y prueba = " prueba " no parecen coincidir.

¿Fue útil?

Solución

De hecho, están de acuerdo.
Como Hans Doggen ya notó, PHP genera el resumen del mensaje usando notación hexadecimal a menos que establezca el parámetro de salida sin formato en verdadero. Si desea usar la misma notación en Java, puede usar algo como

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

para formatear la salida en consecuencia.

Otros consejos

Puedes probar esto en 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 es mi implementación:

        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;

Me parece que PHP usa la notación HEX para los bytes que produce Java (1a = 26), pero no verifiqué toda la expresión.

¿Qué sucede si ejecuta la matriz de bytes a través del método en esto ? página?

Mi implementación para HmacMD5 - simplemente cambie el algoritmo a 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);

No lo he probado, pero prueba esto:

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

Esta es una instantánea de mi método que hace que java md5 y sha1 coincidan con php.

De esta manera podría obtener la misma cadena exacta que estaba obteniendo con hash_hmac en 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 bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top