Comment puis-je calculer un hash SHA-2 (idéalement SHA 256 ou SHA 512) dans iOS?

L'API des services de sécurité ne semble pas me permettre de calculer un hachage directement. Il y a beaucoup de versions disponibles dans le domaine public et sous licence libre, mais je préfère utiliser une implémentation de bibliothèque système si possible.

Les données sont accessibles via NSData, ou de simples pointeurs.

la force cryptographique du hash est importante pour moi. SHA-256 est la taille de hachage minimale acceptable.

57
demandé sur James 2011-06-03 18:02:52

6 réponses

C'est ce que j'utilise pour 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;
}

remplacer CC_SHA1 par CC_SHA256 (ou celui dont vous avez besoin), ainsi que CC_SHA1_DIGEST_LENGTH par CC_SHA256_DIGEST_LENGTH .

79
répondu alex-i 2018-07-17 20:44:20

voici un assez similaire basé sur 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;
}

(les crédits vont à http://www.raywenderlich.com/6475/basic-security-in-ios-5-tutorial-part-1 )

32
répondu Ege Akpinar 2013-02-11 15:43:49

C'est ce qui a fonctionné pour moi

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
répondu mdkr 2016-03-18 22:06:19

sous le lien j'ai utilisé pour créer la valeur de hachage de document et son très simple et facile à calculer la valeur de hachage spécialement pour les grands dossiers.

lien : 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
répondu Sunil aruru 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
répondu Boris 2017-05-24 16:55:30

j'ai nettoyé https://stackoverflow.com/a/13199111/1254812 un peu et structuré comme un NSString extension

@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
répondu dcow 2018-03-30 04:37:38