2

I'm having some trouble converting a command-line OpenSSL SHA256 Digest over to the equivalent in Objective-C. Any assistance would be tremendously appreciated.

When I run OpenSSL on the command-line like so:

    echo 'key=2fvmer3qbk7f9jnqneg58bu2&secret=qvxkmw57pec7&ts=1200603038' | openssl dgst -sha256

I get the (correct/expected) result:

1e673d58756f95fb938ddb42fd6242dc691803578a3503fedd5c0e92aac6c098

I've then created a function in Objective-C as follows -

SHA256HashClass.h:

@interface SHA256Hashclass : NSObject{
    unsigned char SHAInputValue[32];
}

SHA256Hashclass.m:

- (id)createSHA256HashWithBytes:(const void *)bytes length:(NSUInteger)length
{
    // hash
    CC_SHA256(bytes, length, SHAInputValue);

    NSInteger byteLength = sizeof(char value[CC_SHA256_DIGEST_LENGTH]); //sizeof() = 32 bytes

    NSMutableString *stringValue = [NSMutableString stringWithCapacity:byteLength * 2];

    // convert to string
    for (int i = 0; i < byteLength; i++)
    {
        [stringValue appendFormat:@"%02x", SHAInputValue[i]];
    }

    return stringValue;
}

However when I call the above function like so:

NSData *dataIn = [@"key=2fvmer3qbk7f9jnqneg58bu2&secret=qvxkmw57pec7&ts=1200603038" dataUsingEncoding:NSUTF8StringEncoding];

SHA256Hashclass *hashClass = [[SHA256Hashclass alloc] init];

NSLog(@"Result: %@", [hashClass createSHA256HashWithBytes:dataIn.bytes length:dataIn.length]);

I get the following result which clearly differs from the expected OpenSSL SHA256 equivalent shown above:

d8a0771d41c6b9918048c4842415946bcda27c75b0b6ae4948b6ea081eb01196

I've tried changing the encoding from NSUTF8StringEncoding to NSASCIIStringEncoding but it didn't help.

JaredH
  • 2,338
  • 1
  • 30
  • 40

1 Answers1

2

echo adds an extra newline. If we use echo -n we get the expected output:

$ echo -n 'key=2fvmer3qbk7f9jnqneg58bu2&secret=qvxkmw57pec7&ts=1200603038' | openssl dgst -sha256
(stdin)= d8a0771d41c6b9918048c4842415946bcda27c75b0b6ae4948b6ea081eb01196
nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • Thank you! I'm actually looking to include that extra newline character when I pass the string in to be hashed, because I'm hitting an API which I have no control over, and already expects that newline. I have appended an \n to the string. – JaredH Feb 23 '13 at 19:45
  • 1
    In that case, of course, you can just append the newline when you calculate the hash. I would recommend doing that in the function that calls `createSHA256HashWithBytes` since other users of `createSHA256HashWithBytes` will not expect it to add a newline. – nneonneo Feb 23 '13 at 19:46