Possible Dupli开发者_JAVA技巧cate:
Sha256 in Objective-C for iPhone
Greetings,
I'm having terrible trouble generating a SHA256 string in Objective C (probably because I'm so new to the language).
In jQuery, all I have to do is this:
var sha256String=$.sha256("Hello");
which produces the hash as expected.
But in Objective-C, I've tried the following to no avail:
NSString *pword=[[NSString alloc]
initWithString:login_pword.text];
unsigned char result[64];
CC_SHA256([pword UTF8String], [pword lengthOfBytesUsingEncoding:NSASCIIStringEncoding],result);
UIAlertView *msg=[[UIAlertView alloc] initWithTitle:@"Hi" message:result delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[msg show];
[msg release];
Is there some function that I can call such as:
NSString *sha256String=[self getSHA256:pword];
This is what I'm trying to create and I'm finding it very difficult!
I hope someone can help.
Many thanks in advance,
After much playing around today, I finally came up with a function to get the SHA256:
-(NSString*) sha256:(NSString *)clear{
const char *s=[clear 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;
}
This gives the same output as PHP. It can easily be converted to SHA1 - just change 'SHA256' to 'SHA1'.
Hope it helps someone.
You are passing result
into the UIAlertView
's init
method. result
is a char[]
, and UIAlertView
expects an NSString*
. You need to convert your char[]
to an NSString *
.
Try this:
NSString *resultString = [NSString stringWithCString:result encoding:NSASCIIStringEncoding];
UIAlertView *msg=[[UIAlertView alloc] initWithTitle:@"Hi" message:resultString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
Also see this article on hashing on the iPhone.
You will need to use the OpenSSL C functions. See for example this question on how to do that. As input string, you'd use [myString UTFString]
with length [myString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]
.
精彩评论