Your approach might not give you the intended result if you have NSStrings containing Unicode characters which contains zero bytes. Your strlen() call would stop at that character and not go to the full length of a NSString. So a conversion to NSData and use its length would be better. For ASCII and Laltin1 it wouldnt make a difference though.
so this would be better appraoch: NSData *d = [self dataUsingEncoding:NSUTF8StringEncoding]; unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5( d.bytes, (int)d.length, result ); > On 01 Apr 2020, at 20:19, Andreas Höschler <ahoe...@smartsoft.de> wrote: > > Hi Nikolaus, > >>> I have the following NSString category >>> >>> @implementation NSString (NSStringJsonExtension) >>> >>> - (NSString *)md5 >>> { >>> #ifdef __APPLE__ >>> const char *cStr = [self UTF8String]; >>> unsigned char result[CC_MD5_DIGEST_LENGTH]; >>> CC_MD5( cStr, (int)strlen(cStr), result ); // This is the md5 call >>> return [NSString stringWithFormat: >>> @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", >>> result[0], result[1], result[2], result[3], >>> result[4], result[5], result[6], result[7], >>> result[8], result[9], result[10], result[11], >>> result[12], result[13], result[14], result[15] >>> ]; >>> #else >>> NSLog(@"md5 not yet supported on GNUstep. Please implement"); >> >> https://u10997244.ct.sendgrid.net/ls/click?upn=VVT4Fr0OoZzgz9hrDLZSJzJAAUzBaOKReTGxr-2Fx-2FWq8S8KGFYM7kdQTwqhxshnPa5cfe_tlKK9kH2hVBWbOLd8XAeSMwRALtWbXyaBq-2FNYuoUwQRR7ONi3bYz9ia6xyFyfNbfGhU69Si1801xDwBL5gLvDlSjhmIe2EpVgZRgSu-2Bjb2oNDnA0jfV-2F1YSTyfooUKnYA3nOLXTyorAnt-2FggoCWgkhOboZl-2B5oYqbI3ohAyJ6Xfv0SXaMI2yI3a3qDA3WZzjl-2BgpRcxxS4V6alTPKiv9uaYDw5JfdAc-2BzQ2sIRJZTq7tN73cGjsS3bQPZjOzy-2Fd5 >> >> maybe >> unsigned char *MD5(cStr, strlen(cStr), result); >> >> You need to install openssl devel packages. > > Thanks a lot! Your hint got me on the road. The following snippet > > - (NSString *)md5 > { > // we might have to do the following on Linux to get the code below > working > // apt-get install libssl-dev > // #include <openssl/md5.h> > // Link the framework with -lssl -lcrypto > const char *cStr = [self UTF8String]; > unsigned char result[MD5_DIGEST_LENGTH]; > MD5((const unsigned char *)cStr, strlen(cStr), result); > return [NSString stringWithFormat: > @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", > result[0], result[1], result[2], result[3], > result[4], result[5], result[6], result[7], > result[8], result[9], result[10], result[11], > result[12], result[13], result[14], result[15] > ]; > } > > works like a charm. :-) > > Thanks, > > Andreas > >