2014-12-26 3 views
1

과 일치하지 않습니다. Android 앱을 개발 중이며 서버에서 Android 기기로 일부 데이터를 전송해야합니다.Android의 문자열 해시가 serverisde의

앱이 너무 많은 데이터를 다운로드하는 것을 방지하기 위해 Android에서 제공하는 해시 (마지막 다운로드 한 데이터의 md5 해시)를 가져와 서버의 최신 데이터 해시와 비교하는 PHP 서비스를 작성했습니다. 해시가 서로 일치하면 'no_new_data'를 출력하고, 그렇지 않으면 최신 데이터를 인쇄합니다. PHP는 해시를 계산하기 위해 md5 ($ string) 메소드를 사용합니다.이 부분은 정상적으로 작동하는 것 같습니다.

문제는 장치에서 계산 된 해시 값이 서버의 값과 일치하지 않는다는 것입니다. 문자열이 같아도 문제는 아닙니다. 인코딩을 변경해도 시도했지만 도움이되지 않았습니다.

내 MD5 자바 코드 : 공공 정적 문자열의 MD5 (문자열 기반) { 시도 { MessageDigest 등 MD = MessageDigest.getInstance ("MD5"); md.update (base.getBytes());

 byte byteData[] = md.digest(); 

     //convert the byte to hex format method 1 
     StringBuffer sb = new StringBuffer(); 
     for (int i = 0; i < byteData.length; i++) { 
      sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); 
     } 

     //System.out.println("Digest(in hex format):: " + sb.toString()); 

     //convert the byte to hex format method 2 
     StringBuffer hexString = new StringBuffer(); 
     for (int i=0;i<byteData.length;i++) { 
      String hex=Integer.toHexString(0xff & byteData[i]); 
      if(hex.length()==1) hexString.append('0'); 
      hexString.append(hex); 
     } 
     return hexString.toString(); 
    }catch (Exception e){ 
     return "a"; 
    } 
} 

는 Thnks는

답변

1

때때로 MD5 해시는 서버 측 해시 다른 :). 이 방법을 사용해보십시오.

public static String getMD5Hash(String s) throws NoSuchAlgorithmException { 

    String result = s; 
    if (s != null) { 
     MessageDigest md = MessageDigest.getInstance("MD5"); // or "SHA-1" 
     md.update(s.getBytes()); 
     BigInteger hash = new BigInteger(1, md.digest()); 
     result = hash.toString(16); 
     while (result.length() < 32) { // 40 for SHA-1 
      result = "0" + result; 
     } 
    } 
    return result; 
} 
+0

nope :/동일한 결과 –

0

마십시오, 지금까지 거의 절대 당신이 원하는 없습니다 플랫폼 디폴트 캐릭터 세트에 의존하는, String.getBytes()을 사용하지 않습니다. 플랫폼 기본 문자 세트가 Android와 서버 측에서 다를 수 있습니다.

대신 Charset을 전달하십시오.

myString.getBytes(StandardCharsets.UTF_8) 

당신이 자바 7이있는 경우, 또는

myString.getBytes("UTF-8") 

당신이 할 수없는 경우

.

관련 문제