2011-12-29 25 views
8

Sto prendendo un compito conversione del codice Java per Objective C.equivalente oggettivo C di MessageDigest in Java?

Questo è il codice in Java che devo convertire:

private String getHash(String input) 
{ 
    String ret = null; 
    try 
    { 
     MessageDigest md = MessageDigest.getInstance("SHA-256"); 

     byte[] bs = md.digest(input.getBytes("US-ASCII")); 


     StringBuffer sb = new StringBuffer(); 
     for (byte b : bs) 
     { 
      String bt = Integer.toHexString(b & 0xff); 
      if(bt.length()==1) 
      { 
       sb.append("0"); 
      } 
      sb.append(bt); 
     } 
     ret = sb.toString(); 
    } 
    catch (Exception e) 
    { 
    } 
    return ret; 
} 

In particolare, quello che posso utilizzare in Objective C che ha la stessa funzionalità del MessageDigest class?

risposta

2

Ho trovato un framework Apple per supportare SHA-256 in stackoverflow.com. Thx StackOverflow :)

CommonCrypto/CommonDigest.h

e ho capito che posso usare questa funzione:

CC_SHA256(const void *data, CC_LONG len, unsigned char *md) 

CC_SHA256_Final(unsigned char *md, CC_SHA256_CTX *c) 

CC_SHA256_Init(CC_SHA256_CTX *c) 

CC_SHA256_Update(CC_SHA256_CTX *c, const void *data, CC_LONG len) 

così posso andare sul mio compito tranne questo codice Java.

byte[] bs = md.digest(input.getBytes("US-ASCII")); 

e voglio sapere che qualsiasi espressione Objective C di codice circolare Java di seguito?

for (byte b : bs) 

PS: Chuck, ho davvero apprezzato il vostro aiuto. Grazie. :)

3

Qualcosa di simile a questo:

#import <CommonCrypto/CommonDigest.h> 

+(NSString*) sha256:(NSString *)input 
{ 
    const char *s=[input cStringUsingEncoding:NSASCIIStringEncoding]; 
    NSData *keyData=[NSData dataWithBytes:s length:strlen(s)]; 

    uint8_t digest[CC_SHA256_DIGEST_LENGTH]={0}; 
    CC_SHA256(keyData.bytes, keyData.length, digest); 
    NSData *out=[NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH]; 
    NSString *hash=[out description]; 
    hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""]; 
    hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""]; 
    hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""]; 
    return hash; 
}