2010-08-12 18 views
29

¿Cómo puedo sha1 una cadena o un conjunto de números en Objective c?Objetivo C: SHA1

+0

Esta pregunta se hace sorprendentemente similar a http://stackoverflow.com/questions/756492/objective-c-sample-code-for-hmac-sha1. Aún no hay respuestas por allí, pero publico para completar. – Eli

+0

¿Es esto para una plataforma en particular? – ThomasW

+0

@ThomasW Mac os x solo – Daniel

Respuesta

61

CommonCrypto (un marco de Apple) tiene funciones para el cálculo de hash SHA-1, que incluye un hash de un solo paso:

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

Para un conjunto de números, supongamos que quiere decir una matriz de enteros de conocida longitud. Para este tipo de datos, es más fácil de construir de forma iterativa el resumen en lugar de utilizar la función de un solo disparo:

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

Tenga en cuenta que esto no toma en cuenta endianness. El SHA-1 calculado con este código en un sistema PowerPC diferirá del calculado en un sistema i386 o ARM. La solución es simple - SWAP los bytes de los números enteros a una endianness conocido antes de hacer el cálculo:

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

Common Crypto no está separado del SDK más – Daniel

+1

Desde 4.0.2, sí lo es. ¡Sigue adelante e inténtalo! –

+1

Por supuesto, esto es algo específico de iOS. No viene con el lenguaje Objective-C. –

2

SHA1 en realidad no viene con Objective-C. Puede usar el código fuente C para hashdeep y sus amigos, que tiene licencia bajo el dominio público (porque fue escrito por un empleado del gobierno de los Estados Unidos): http://md5deep.sourceforge.net/.

+0

Otra opción sería libgcrypt, de los creadores de GnuPG (http://www.gnupg.org/related_software/libraries.en.html#lib-libgcrypt). – schot

+0

¿Hay alguna encriptación segura que sea compatible directamente con obj c y php? – Daniel

+1

@schot: Pero libcrypt tiene una licencia mucho más restrictiva. @ Daniel: No fuera de la caja, no. Objective-C no viene con mucho en el camino de las bibliotecas. –

4

Otra solución con una biblioteca digerir mensaje (NV-ios-digieren):

(1) cadena

// 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) números

// 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]; 

La biblioteca de resumen de mensajes admite MD5, SHA-1, SHA-224, SHA-256, SHA-384 y SHA-512.

[Blog] resúmenes de mensajes (MD5, SHA1, etc.) en IOS con las clases dedicadas
http://darutk-oboegaki.blogspot.jp/2013/04/message-digests-md5-sha1-etc-on-ios.html

[Biblioteca] NV-ios-digieren
https://github.com/TakahikoKawasaki/nv-ios-digest