Objective C equivalent of MessageDigest in Java?
Asked Answered
G

3

8

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?

Gorgias answered 29/12, 2011 at 12:42 Comment(0)
W
3

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;
}
Walford answered 12/5, 2014 at 11:52 Comment(0)
G
2

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. :)

Gorgias answered 30/12, 2011 at 2:22 Comment(0)
C
0

You want the OpenSSL library. See the answers to generate sha256 with openssl and C++ for an example (the title says C++, but OpenSSL is just a basic C library).

Corroboree answered 29/12, 2011 at 23:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.