2012-02-26 17 views
10

Dato il messaggio e il sale come posso codificarlo restituendo la stringa hash?Come hash SHA nel cacao/iOS

Ho bisogno di riprodurre la funzione php:

hash_hmac('sha256','message','salt'); 

Grazie

+1

Questa domanda ha una risposta che sembra buono: http://stackoverflow.com/ domande/6228092/how-can-i-compute-a-sha-2-ideally-sha-256-or-sha-512-hash-in-ios – Bogatyr

+1

Sì, ma non so come usare il sale ... – Addev

risposta

39

trovato la risposta:

#import <CommonCrypto/CommonHMAC.h> 

-(NSString *) hashString :(NSString *) data withSalt: (NSString *) salt { 


    const char *cKey = [salt cStringUsingEncoding:NSUTF8StringEncoding]; 
    const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding]; 
    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH]; 
    CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC); 

    NSString *hash; 

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

    for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) 
     [output appendFormat:@"%02x", cHMAC[i]]; 
    hash = output; 
    return hash; 

} 
Problemi correlati