目标 C:SHA1 [英] Objective C: SHA1

查看:33
本文介绍了目标 C:SHA1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在目标 c 中 sha1 一个字符串或一组数字?

How do i sha1 a string or set of numbers in Objective c?

推荐答案

CommonCrypto(Apple 框架)具有计算 SHA-1 哈希的函数,包括一步哈希:

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'. */
...

请注意,这并没有考虑字节序.在 PowerPC 系统上使用此代码计算的 SHA-1 将不同于在 i386 或 ARM 系统上计算的 SHA-1.解决方案很简单——在计算之前将整数的字节交换为已知的字节序:

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));
    }

这篇关于目标 C:SHA1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆