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?
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;
}
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With