Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Read NSInputStream and generate SHA of contents
#import <CommonCrypto/CommonDigest.h>
// From the people who brought you goto fail;
// http://www.opensource.apple.com/source/CommonCrypto/CommonCrypto-55010/LocalTests/XTSTest/hexString.c
static char PIHexbyteMap[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
static int PIHexbyteMapLen = sizeof(PIHexbyteMap);
/* Utility function to convert nibbles (4 bit values) into a hex character representation */
static char
PIHexnibbleToChar(uint8_t nibble)
{
if(nibble < PIHexbyteMapLen) return PIHexbyteMap[nibble];
return '*';
}
/* Convert a buffer of binary values into a hex string representation */
char
*PIHexbytesToHexString(uint8_t *bytes, size_t buflen)
{
char *retval;
int i;
size_t stringLen = buflen*2;
retval = malloc(stringLen + 1);
for(i=0; i<buflen; i++) {
retval[i*2] = PIHexnibbleToChar(bytes[i] >> 4);
retval[i*2+1] = PIHexnibbleToChar(bytes[i] & 0x0f);
}
retval[stringLen] = '\0';
return retval;
}
CC_SHA1_CTX digest;
int CC_result = CC_SHA1_Init(&digest);
NSAssert(1 == CC_result, @"Unexpected initialization result: %i", CC_result);
NSInputStream *stream = request.HTTPBodyStream;
[stream open];
NSMutableData *data = [NSMutableData data];
u_int8_t buffer[4096];
NSInteger result = 0;
result = [stream read:buffer maxLength:4096];
while((result = [stream read:buffer maxLength:4096]) != 0) {
[data appendBytes:buffer length:result];
CC_result = CC_SHA1_Update(&digest, buffer, result);
NSAssert(1 == CC_result, @"Unexpected digest update result: %i", CC_result);
}
NSAssert(0 == result, @"Unexpected end of stream: %i", result);
[stream close];
unsigned char md[CC_SHA1_DIGEST_LENGTH];
CC_result = CC_SHA1_Final(md, &digest);
NSAssert(1 == CC_result, @"Unexpected digest finalize result: %i", CC_result);
char *shasum = PIHexbytesToHexString(md, CC_SHA1_DIGEST_LENGTH);
NSLog(@"SHA of upload: %s", shasum);
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"As a string: %@", dataString);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.