CommonCrypto(Apple 框架)具有计算 SHA-1 哈希值的函数,包括一步哈希值:
#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'. */
...
}
对于一组数字,我们假设您指的是已知长度的整数数组。对于此类数据,迭代构建摘要比使用一次性函数更容易:
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'. */
...
请注意,这没有考虑字节顺序。在 PowerPC 系统上使用此代码计算的 SHA-1 将不同于在 i386 或 ARM 系统上计算的 SHA-1。解决方案很简单——在计算之前将整数的字节交换为已知的字节顺序:
for (size_t i = 0; i < numIntegers; i++) {
uint32_t swapped = CFSwapInt32HostToLittle(someIntegers[i]); /* or HostToBig */
CC_SHA1_Update(&ctx, &swapped, sizeof(swapped));
}