Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C equivalent of MessageDigest in Java?

I'm taking a task converting Java code to Objective C.

This is the code in Java that I have to convert:

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;
}

Specifically, what can I use in Objective C which has the same functionality as the MessageDigest class?

like image 772
Fogni Avatar asked Dec 29 '11 12:12

Fogni


2 Answers

Something like this:

#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;
}
like image 127
sedrakpc Avatar answered Oct 21 '22 07:10

sedrakpc


I found a apple framework to support SHA-256 in stackoverflow.com. Thx stackoverflow :)

CommonCrypto/CommonDigest.h

and I realized that I can use this function:

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)

So I can go on my task except this Java code.

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

and I want to know that any Objective C expression of Java circular code below?

for (byte b : bs)

PS : Chuck, I really appreciate for your help. Thank you. :)

like image 35
Fogni Avatar answered Oct 21 '22 08:10

Fogni