2011-06-10 29 views
47

estoy hash algunos valores utilizando HMAC-SHA1, usando el siguiente código en Java:HMAC-SHA1: ¿Cómo hacerlo correctamente en Java?

public static String hmacSha1(String value, String key) { 
    try { 
     // 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(value.getBytes()); 

     // Convert raw bytes to Hex 
     byte[] hexBytes = new Hex().encode(rawHmac); 

     // Covert array of Hex bytes to a String 
     return new String(hexBytes, "UTF-8"); 
    } catch (Exception e) { 
     throw new RuntimeException(e); 
    } 
} 

Hex() pertenece a org.apache.commons.codec

En PHP hay una función similar hash_hmac(algorithm, data, key) que utilizo para comparar los valores devueltos por mi implementación de Java.

Así que el primer intento es:

hash_hmac("sha1", "helloworld", "mykey") // PHP 

que devuelve: 74ae5a4a3d9996d5918defc2c3d475471bbf59ac

función Mi Java vuelve 74ae5a4a3d9996d5918defc2c3d475471bbf59ac también.

Ok, parece funcionar. Entonces trato de usar una clave más complejo:

hash_hmac("sha1", "helloworld", "PRIE7$oG2uS-Yf17kEnUEpi5hvW/#AFo") // PHP 

que devuelve: e98bcc5c5be6f11dc582ae55f520d1ec4ae29f7a

Mientras que esta vez mis Java impl devuelve: c19fccf57c613f1868dd22d586f9571cf6412cd0

el hash devuelto por mi código PHP no es igual a la valor devuelto por mi función Java, y no puedo averiguar por qué.

¿Algún consejo?

+5

¿No interpretaría $ chars en PHP como variable? –

+0

¿Por qué necesitas la fase hexagonal? –

Respuesta

51

En su lado de PHP, utilice comillas simples alrededor de la clave para que el carácter $ no se trate como una referencia de variable. es decir,

hash_hmac("sha1", "helloworld", 'PRIE7$oG2uS-Yf17kEnUEpi5hvW/#AFo') 

De lo contrario, la clave que realmente se obtiene es PRIE7-Yf17kEnUEpi5hvW/#AFo (suponiendo que la variable no está definida $oG2uS).

+5

awesome bugfinder! –

7

Cualquier símbolo de $ entre comillas dobles ("") se considera como una variable en PHP. Puede evitar el error mediante el uso de comillas simples como ha señalado el autor del comentario anterior o se puede escapar el signo del dólar como a continuación

hash_hmac("sha1", "helloworld", "PRIE7\$oG2uS-Yf17kEnUEpi5hvW/#AFo") 

Aviso $ es ahora \ $

0

En Java, y el uso de experto:

Añadir la dependencia a continuación en el pom.xml:

<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec --> 
    <dependency> 
     <groupId>commons-codec</groupId> 
     <artifactId>commons-codec</artifactId> 
     <version>1.4</version> 
    </dependency> 

y luego tratar de firmarlo el uso de este

HmacUtils.hmacSha1Hex(key, string_to_sign); 
Cuestiones relacionadas