2012-03-12 9 views
32

में SHA256 हैश की गणना करें मैं एंड्रॉइड में SHA256 हैश उत्पन्न करने की कोशिश कर रहा हूं, फिर मैं एक एएसपी.नेट वेब एपीआई वेब सेवा में जाता हूं और वहां हैश की तुलना करता हूं। इस प्रकार, मुझे एंड्रॉइड में हैश बनाने की जरूरत है, जो एएसपी.नेट में एक ही इनपुट को बराबर हैश उत्पन्न करेगा। मैं यह पता लगाने की कोशिश कर रहा हूं कि मैं क्या गलत कर रहा हूं।एंड्रॉइड/जावा और सी #

यहां 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(); 
} 

और यहाँ पर सर्वर (ग #) कोड है:

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(); 
    } 

अद्यतन: यहाँ सुधारा एंड्रॉयड/जावा कार्यान्वयन है (धन्यवाद निकोले एलेंकोव):

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

मुझे विश्वास नहीं है कि आज आपने मुझे कितना समय बचाया है। अद्यतन पोस्ट करने के लिए धन्यवाद। –

+0

मैं जावा में मूल इनपुट में हैश स्ट्रिंग को वापस कैसे परिवर्तित कर सकता हूं। कोई विचार धन्यवाद –

+0

एक क्रिप्टोग्राफिक हैश एक तरफा है ... कृपया निम्नलिखित आलेख देखें: http://en.wikipedia.org/wiki/Cryptographic_hash_function – Kevin

उत्तर

20

आपका जावा कोड गलत है: आप दो बार इनपुट बाइट जोड़ रहे हैं। यदि आप इसे एक बार में गणना कर रहे हैं, तो आपको update(bytes) के बाद केवल digest(bytes) पर कॉल करने या digest() पर कॉल करने की आवश्यकता है;

+0

बूम! धन्यवाद निकोले। – Kevin