How do i sha1 a string or set of numbers in Objective c?
CommonCrypto (an Apple framework) has functions for calculating SHA-1 hashes, including a one-step hash:
#include <CommonCrypto/CommonDigest.h>
unsigned char digest[CC_SHA1_DIGEST_LENGTH];
NSData *stringBytes = [someString dataUsingEncoding: NSUTF8StringEncoding]; /* or some other encoding */
if (CC_SHA1([stringBytes bytes], [stringBytes length], digest)) {
/* SHA-1 hash has been calculated and stored in 'digest'. */
...
}
For a set of numbers, let us assume you mean an array of ints of known length. For such data, it is easier to iteratively construct the digest rather than use the one-shot function:
unsigned char digest[CC_SHA1_DIGEST_LENGTH];
uint32_t *someIntegers = ...;
size_t numIntegers = ...;
CC_SHA1_CTX ctx;
CC_SHA1_Init(&ctx);
{
for (size_t i = 0; i < numIntegers; i++)
CC_SHA1_Update(&ctx, someIntegers + i, sizeof(uint32_t));
}
CC_SHA1_Final(digest, &ctx);
/* SHA-1 hash has been calculated and stored in 'digest'. */
...
Note that this does not take endianness into account. The SHA-1 calculated with this code on a PowerPC system will differ from the one calculated on an i386 or ARM system. The solution is simple--swap the bytes of the integers to a known endianness before doing the calculation:
for (size_t i = 0; i < numIntegers; i++) {
uint32_t swapped = CFSwapInt32HostToLittle(someIntegers[i]); /* or HostToBig */
CC_SHA1_Update(&ctx, &swapped, sizeof(swapped));
}