keys android asp.net security sha asp.net-web-api

android - api keys c#



Computar SHA256 Hash en Android/Java y C# (1)

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

Intento 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.

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 implementación corregida de Android / Java (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(); }