¿Cómo puedo calcular un hash SHA-2 (idealmente SHA 256 o SHA 512) en iOS?


La API de servicios de seguridad no parece permitirme calcular un hash directamente. Hay un montón de dominio público y versiones liberalmente licenciadas disponibles, pero prefiero usar una implementación de biblioteca del sistema si es posible.

Los datos son accesibles a través de NSData, o punteros simples.

La fuerza criptográfica del hash es importante para mí. SHA-256 es el tamaño mínimo aceptable de hash.

Author: James, 2011-06-03

6 answers

Esto es lo que estoy usando para SHA1:

#import <CommonCrypto/CommonDigest.h>

+ (NSData *)sha1:(NSData *)data {
    unsigned char hash[CC_SHA1_DIGEST_LENGTH];
    if ( CC_SHA1([data bytes], [data length], hash) ) {
        NSData *sha1 = [NSData dataWithBytes:hash length:CC_SHA1_DIGEST_LENGTH];        
        return sha1;
    }
return nil;
}

Sustitúyase CC_SHA1 por CC_SHA256 (o lo que sea necesario), así como CC_SHA1_DIGEST_LENGTH por CC_SHA256_DIGEST_LENGTH.

 79
Author: alex-i,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-17 20:44:20

Aquí hay uno bastante similar basado en NSString

+ (NSString *)hashed_string:(NSString *)input
{
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    uint8_t digest[CC_SHA256_DIGEST_LENGTH];

    // This is an iOS5-specific method.
    // It takes in the data, how much data, and then output format, which in this case is an int array.
    CC_SHA256(data.bytes, data.length, digest);

    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];

    // Parse through the CC_SHA256 results (stored inside of digest[]).
    for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }

    return output;
}

(Los créditos van a http://www.raywenderlich.com/6475/basic-security-in-ios-5-tutorial-part-1 )

 32
Author: Ege Akpinar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-11 15:43:49

Esto es lo que funcionó para mí

func sha256(securityString : String) -> String {
    let data = securityString.dataUsingEncoding(NSUTF8StringEncoding)!
    var hash = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0)
    CC_SHA256(data.bytes, CC_LONG(data.length), &hash)
    let output = NSMutableString(capacity: Int(CC_SHA1_DIGEST_LENGTH))
    for byte in hash {
        output.appendFormat("%02x", byte)
    }
    return output as String
}
 3
Author: mdkr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-18 22:06:19

El siguiente enlace lo utilicé para crear el valor hash del documento y es muy simple y fácil de calcular el valor hash especialmente para archivos grandes.

Enlace : http://www.joel.lopes-da-silva.com/2010/09/07/compute-md5-or-sha-hash-of-large-file-efficiently-on-ios-and-mac-os-x/comment-page-1/#comment-18533

 1
Author: Sunil aruru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-12 07:33:31
+ (NSData *)sha256DataFromData:(NSData *)data {
    unsigned char result[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256([data bytes], (int)[data length], result);
    return [NSData dataWithBytes:result length:CC_SHA256_DIGEST_LENGTH];
}
 0
Author: Boris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-24 16:55:30

He limpiado https://stackoverflow.com/a/13199111/1254812 un poco y lo estructuró como una extensión NSString

@interface NSString (SHA2HEX)

/*
 Get the SHA2 (256 bit) digest as a hex string.
 */
@property (nonatomic, readonly) NSString* sha2hex;
@end

@implementation NSString (SHA2HEX)

- (NSString*)sha2hex
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];

    if (data.length > UINT32_MAX)
        return nil;

    uint8_t digest[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(data.bytes, (CC_LONG)data.length, digest);

    const int hexlen = CC_SHA256_DIGEST_LENGTH * 2;
    NSMutableString *hexstr = [NSMutableString stringWithCapacity:hexlen];

    for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
        [hexstr appendFormat:@"%02x", digest[i]];
    }

    return hexstr;
}

@end
 0
Author: dcow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-30 04:37:38