0

I'm trying to get message digest of a string on IOS. I have tried nv-ios-digest 3rd party Hash lib but still no use.

Below is the function i'm using to get the base64encoded string of a message digest.

-(NSString*) sha1:(NSString*)input //sha1- Digest
{
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, data.length, digest);
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++){
        [output appendFormat:@"%02x", digest[i]];//digest
    }
    return [NSString stringWithFormat:@"%@",[[[output description] dataUsingEncoding:NSUTF8StringEncoding]base64EncodedStringWithOptions:0]]; //base64 encoded 


}

Here is my sample input string - '530279591878676249714013992002683ec3a85216db22238a12fcf11a07606ecbfb57b5'

When I use this string either in java or python I get same result - '5VNqZRB1JiRUieUj0DufgeUbuHQ='

But in IOS I get 'ZTU1MzZhNjUxMDc1MjYyNDU0ODllNTIzZDAzYjlmODFlNTFiYjg3NA=='

Here is the code I'm using in python:

import hashlib
import base64

def checkForDigestKey(somestring):
     msgDigest = hashlib.sha1()
     msgDigest.update(somestring)
     print base64.b64encode(msgDigest.digest())

Let me know if there is anyway to get the same result for IOS.

1 Answers1

3

You are producing a binary digest in Python, a hexadecimal digest in iOS.

The digests are otherwise equal:

>>> # iOS-produced base64 value
...
>>> 'ZTU1MzZhNjUxMDc1MjYyNDU0ODllNTIzZDAzYjlmODFlNTFiYjg3NA=='.decode('base64')
'e5536a65107526245489e523d03b9f81e51bb874'
>>> # Python-produced base64 value
...
>>> '5VNqZRB1JiRUieUj0DufgeUbuHQ='.decode('base64')
'\xe5Sje\x10u&$T\x89\xe5#\xd0;\x9f\x81\xe5\x1b\xb8t'
>>> from binascii import hexlify
>>> # Python-produced value converted to a hex representation
...
>>> hexlify('5VNqZRB1JiRUieUj0DufgeUbuHQ='.decode('base64'))
'e5536a65107526245489e523d03b9f81e51bb874'

Use base64.b64encode(msgDigest.hexdigest()) in Python to produce the same value, or Base-64 encode the digest bytes instead of hexadecimal characters in iOS.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • @vivianaranha: you already *have* binary, you are converting that to hex. – Martijn Pieters May 29 '14 at 22:02
  • 1
    @vivianaranha: convert the `uint8_t digest` array to base 64 instead. [how to convert array of bytes to base64 String in iphone?](http://stackoverflow.com/q/6466083) looks relevant. – Martijn Pieters May 29 '14 at 22:04