|
|
Cocoa and SHA1 hashing
|
|
|
|
Mac Elite
Join Date: Jul 2002
Status:
Offline
|
|
I need to hash an NSString using SHA1 and return the result. Here's the method I have now, which doesn't seem to work:
Code:
- (NSMutableString *) hashInfoString: (NSString *) aString
{
NSMutableString *hashValue = [[NSMutableString alloc] initWithCapacity: 20];
uint8_t md[SHA_DIGEST_LENGTH];
unsigned char *stringToBeHashed[[aString length]];
NSLog(@"stringToBeHashed allocated, going to coversion loop.");
for (int i = 0; i < [aString length]; i++)
{
stringToBeHashed[i] = [aString characterAtIndex:i];
}
NSLog(@"Through conversion of NSString to char, string to be hashed is %C", stringToBeHashed);
unsigned char *answer;
answer = SHA1(stringToBeHashed, (unsigned long)6, md);
NSLog(@"SHA1 function done, appending mutable string, answer is %C", answer);
[hashValue appendFormat: @"%C", answer];
NSLog(@"Mutable string appended, returning.");
return hashValue;
}
Please be gentle, I really have no idea what I'm doing.
Basically, I need to know how to covert my NSString to a char, use SHA1 on that char, and turn the result back into an NSString. All this while I need to ensure I'm using the proper string formats.
Any thoughts on hashing a file in Cocoa are also appreciated.
|
|
|
|
|
|
|
|
|
Mac Elite
Join Date: Jul 2002
Status:
Offline
|
|
Okay, it looks like this now:
Code:
- (NSString *) hashInfoString: (NSString *) aString
{
uint8_t md[SHA_DIGEST_LENGTH];
const char* stringToBeHashed = [aString UTF8String];
NSLog(@"Through conversion of NSString to char, string to be hashed is %s", stringToBeHashed);
char* answer;
answer = SHA1(stringToBeHashed, (unsigned long)[aString length], md);
NSLog(@"SHA1 function done, appending mutable string, answer is %s", answer);
NSString *hashValue = [NSString stringWithUTF8String: answer];
NSLog(@"String created, returning.");
return hashValue;
}
Problem is, the returned NSString is null.
|
|
|
|
|
|
|
|
|
Mac Elite
Join Date: Sep 2000
Location: Tempe, AZ
Status:
Offline
|
|
The returned string 'answer' probably doesn't have its zero terminator, since there's no room for it. Also, "answer' and 'md' are probably the same pointer. Try these (untested) changes:
Code:
uint8_t md[SHA_DIGEST_LENGTH+1];
char *answer = SHA1(stringToBeHashed, strlen(stringToBeHashed), md);
md[SHA_DIGEST_LENGTH] = 0;
|
Geekspiff - generating spiffdiddlee software since before you began paying attention.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Forum Rules
|
|
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
|
HTML code is Off
|
|
|
|
|
|
|
|
|
|
|
|