2012-03-12 28 views
32

Estoy tratando de generar un hash SHA256 en android, que luego paso a un servicio web ASP.NET Web API y comparo el hash allí. Como tal, necesito construir un hash en Android, que dadas las mismas entradas en ASP.NET generará un hash equivalente. Me estoy tirando de los pelos tratando de descubrir lo que estoy haciendo mal.Computar SHash SHA256 en Android/Java y C#

Aquí está el código de Android:

public String computeHash(String input) throws NoSuchAlgorithmException{ 
    MessageDigest digest = MessageDigest.getInstance("SHA-256"); 
    digest.reset(); 
    try{ 
     digest.update(input.getBytes("UTF-8")); 
    } catch (UnsupportedEncodingException e){ 
     e.printStackTrace(); 
    } 

    byte[] byteData = digest.digest(input.getBytes()); 
    StringBuffer sb = new StringBuffer(); 

    for (int i = 0; i < byteData.length; i++){ 
     sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); 
    } 
    return sb.toString(); 
} 

Y aquí está el código en el servidor (C#):

private static string ComputeHash(string input, HashAlgorithm algorithm) 
    { 

     Byte[] inputBytes = Encoding.UTF8.GetBytes(input); 
     Byte[] hashedBytes = algorithm.ComputeHash(inputBytes); 

     StringBuilder sb = new StringBuilder(); 

     for (int i = 0; i < hashedBytes.Length; i++) 
     { 
      sb.Append(String.Format("{0:x2}", hashedBytes[i])); 
     } 

     return sb.ToString(); 
    } 

ACTUALIZACIÓN: Aquí está la aplicación Android/Java corregido (gracias Nikolay Elenkov):

public String computeHash(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException{ 
    MessageDigest digest = MessageDigest.getInstance("SHA-256"); 
    digest.reset(); 

    byte[] byteData = digest.digest(input.getBytes("UTF-8")); 
    StringBuffer sb = new StringBuffer(); 

    for (int i = 0; i < byteData.length; i++){ 
     sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); 
    } 
    return sb.toString(); 
} 
+2

No puedo creer cuánto tiempo me salvaste hoy. Gracias por publicar la actualizacion. –

+0

¿Cómo puedo convertir de nuevo la cadena Hash a la entrada original en Java? cualquier idea, gracias –

+0

Un hash crytpographic es unidireccional ... consulte el siguiente artículo: http://en.wikipedia.org/wiki/Funcion_haz_criptográfica – Kevin

Respuesta

20

Su código de Java es incorrecto: está agregando los bytes de entrada dos veces. Si está calculando esto de una vez, debe llamar solo al digest(bytes) o llamar al digest() después de update(bytes);

+0

¡Boom! Gracias Nikolay. – Kevin

Cuestiones relacionadas