Подтвердить что ты не робот

Цель C: SHA1

Как сделать sha1 строку или набор чисел в Objective c?

4b9b3361

Ответ 1

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

Для набора чисел предположим, что вы имеете в виду массив из ints известной длины. Для таких данных легче итерационно построить дайджест, а не использовать одноразовую функцию:

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

Обратите внимание, что это не учитывает утверждение. SHA-1, рассчитанный с помощью этого кода в системе PowerPC, будет отличаться от того, который рассчитан для системы i386 или ARM. Решение прост - поменяйте байты целых чисел на известную континентность перед выполнением вычисления:

    for (size_t i = 0; i < numIntegers; i++) {
        uint32_t swapped = CFSwapInt32HostToLittle(someIntegers[i]); /* or HostToBig */
        CC_SHA1_Update(&ctx, &swapped, sizeof(swapped));
    }

Ответ 2

Другое решение с библиотекой дайджеста сообщений (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.

[Блог] Рассылки сообщений (MD5, SHA1 и т.д.) на iOS с выделенными классами
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

Ответ 3

SHA1 на самом деле не поставляется с Objective-C. Вы можете использовать исходный код C для hashdeep и друзей, который лицензируется под общим доменом (поскольку он был написан сотрудником правительства Соединенных Штатов): http://md5deep.sourceforge.net/.