如何在Objective c中sha1一个字符串或一组数字?
答案 0 :(得分:63)
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));
}
答案 1 :(得分:4)
另一个带有消息摘要库的解决方案(nv-ios-digest):
(1)字符串
// Create an SHA1 instance, update it with a string and do final.
SHA1 sha1 = [SHA1 sha1WithString:@"Hello"];
// Get the pointer of the internal buffer that holds the message digest value.
// The life of the internal buffer ends when the SHA1 instance is discarded.
// Copy the buffer as necessary. The size of the buffer can be obtained by
// 'bufferSize' method.
unsigned char *digestAsBytes = [sha1 buffer];
// Get the string expression of the message digest value.
NSString *digestAsString = [sha1 description];
(2)数字
// Create an SHA1 instance.
SHA1 sha1 = [[SHA1 alloc] init];
// Update the SHA1 instance with numbers.
// (Sorry, the current implementation is endianness-dependent.)
[sha1 updateWithShort:(short)1];
[sha1 updateWithInt:(int)2];
[sha1 updateWithLong:(long)3];
[sha1 updateWithLongLong:(long long)4];
[sha1 updateWithFloat:(float)5];
[sha1 updateWithDouble:(double)6];
// Do final. 'final' method returns the pointer of the internal buffer
// that holds the message digest value. 'buffer' method returns the same.
// The life of the internal buffer ends when the SHA1 instance is discarded.
// Copy the buffer as necessary. The size of the buffer can be obtained by
// 'bufferSize' method.
unsigned char *digestAsBytes = [sha1 final];
// Get the string expression of the message digest value.
NSString *digestAsString = [sha1 description];
消息摘要库支持MD5,SHA-1,SHA-224,SHA-256,SHA-384和SHA-512。
[博客] 带有专用班级的iOS上的消息摘要(MD5,SHA1等) http://darutk-oboegaki.blogspot.jp/2013/04/message-digests-md5-sha1-etc-on-ios.html
[图书馆] nv-ios-digest
https://github.com/TakahikoKawasaki/nv-ios-digest
答案 2 :(得分:2)
SHA1实际上没有Objective-C。您可以使用hashdeep
的C源代码和在公共域下获得许可的朋友(因为它是由美国政府的员工编写的):http://md5deep.sourceforge.net/。