2011-12-06 17 views
5

Sto cercando di creare una stringa MD5 hash Android per eguagliare il codice C# sotto:Android: come creare una stringa HMAC MD5?

private string CalculateHMACMd5(string message, string key) 
{ 
    System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); 
    byte[] keyByte = encoding.GetBytes(key); 
    HMACMD5 hmacmd5 = new HMACMD5(keyByte); 
    byte[] messageBytes = encoding.GetBytes(message); 
    byte[] hashmessage = hmacmd5.ComputeHash(messageBytes); 
    string HMACMd5Value = ByteToString(hashmessage); 
    return HMACMd5Value; 
} 

private static string ByteToString(byte[] buff) 
{ 
    string sbinary = ""; 
    for (int i = 0; i < buff.Length; i++) 
    { 
     sbinary += buff[i].ToString("X2"); 
    } 
    return (sbinary); 
} 


codice di Android che attualmente utilizzo [ non generare lo stesso codice C#]:

 public static String sStringToHMACMD5(String sData, String sKey) 
     { 
      SecretKeySpec key; 
      byte[] bytes; 
      String sEncodedString = null; 
      try 
      {  
       key = new SecretKeySpec((sKey).getBytes(), "ASCII"); 
       Mac mac = Mac.getInstance("HMACMD5"); 
       mac.init(key); 
       mac.update(sData.getBytes()); 

       bytes = mac.doFinal(sData.getBytes()); 
       StringBuffer hash = new StringBuffer(); 

       for (int i=0; i<bytes.length; i++) { 
        String hex = Integer.toHexString(0xFF & bytes[i]); 
        if (hex.length() == 1) { 
         hash.append('0'); 
        } 
        hash.append(hex); 
       } 
      sEncodedString = hash.  
      return sEncodedString; 
     } 

Grazie in anticipo.

+0

controllare il codice Android. – Basbous

+0

possibile duplicato di [Come generare HMAC MD5 in Android?] (Http://stackoverflow.com/questions/3140650/how-to-generate-hmac-md5-in-android) – Thilo

+1

@Thilo: ho controllato il collegamento fornito a me stesso, la soluzione non funziona. –

risposta

6

Definire 'non funzionante'. Eccezione? Uscita non come previsto ?, ecc

Una cosa evidente è che si stanno elaborando gli stessi dati due volte:

mac.update(sData.getBytes()); 
bytes = mac.doFinal(sData.getBytes()); 

per elaborare tutti i dati in un unico passaggio, basta usare doFinal() (supponendo che non è troppo grande) . Un'altra cosa che può essere errata è il formato della chiave: qual è il formato di String sKey. Idealmente dovresti usare una stringa codificata BASE64, non le chiamate a getString().

+0

Vedo che lei ha ragione, per favore controlla la mia soluzione, grazie per il suggerimento. – Basbous

+0

Dump (o usa il debugger) in entrambi i programmi 'byte [] keyByte', assicurati che i byte siano gli stessi. Fai lo stesso con 'byte [] messageBytes'. Se tutti quelli corrispondono, anche 'byte [] hashmessage' dovrebbe essere utile, ma controlla anche quello. Se corrispondono, l'errore si trova nella parte finale codifica esadecimale. –

15
public static String sStringToHMACMD5(String s, String keyString) 
    { 
     String sEncodedString = null; 
     try 
     { 
      SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), "HmacMD5"); 
      Mac mac = Mac.getInstance("HmacMD5"); 
      mac.init(key); 

      byte[] bytes = mac.doFinal(s.getBytes("ASCII")); 

      StringBuffer hash = new StringBuffer(); 

      for (int i=0; i<bytes.length; i++) { 
       String hex = Integer.toHexString(0xFF & bytes[i]); 
       if (hex.length() == 1) { 
        hash.append('0'); 
       } 
       hash.append(hex); 
      } 
      sEncodedString = hash.toString(); 
     } 
     catch (UnsupportedEncodingException e) {} 
     catch(InvalidKeyException e){} 
     catch (NoSuchAlgorithmException e) {} 
     return sEncodedString ; 
    } 
+0

Non ignorare le eccezioni. Registrali. – siamii

+0

sicuro ma rimuovo l'eccezione per ridurre il codice sopra. – Basbous