Adding MD5 to a UITextField
Sorry if this is a silly question but hav开发者_如何学Pythoning difficulty in getting this working!!
I have searched hi and low and it seems the code below will generate an md5 hash but im not sure how to get my 2 password textfields to use it to generate to send to the server. Please advise I would be greatful thankful.
Mike
#import <CommonCrypto/CommonDigest.h>
- (NSString *)stringWithMD5Hash:(NSString *)inStr {
const char *cStr = [inStr UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5( cStr, strlen(cStr), result );
return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15] ];
}
Call [self stringWithMD5Hash:yourTextField.text]
. You might want to lowerCase the return of the function as most server side languages generate MD5 hashes with lowercase characters.
Quite easy Assuming the method is in the same class as your textfield, just do this:
NSString *md5 = [self stringWithMD5Hash:textField.text];
You should put this code into a Category
(see the Apple documentation) which adds it to the NSString class. You can add it either as a class
+ (NSString *)stringWithMD5Hash:(NSString *)inStr {
const char *cStr = [inStr UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5( cStr, strlen(cStr), result );
return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15] ];
}
or as an instance method
- (NSString *)MD5Hash {
const char *cStr = [self UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5( cStr, strlen(cStr), result );
return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15] ];
}
Then you can call it just as sudo rm -rf
said:
NSString *md5 = [NSString stringWithMD5Hash:textField.text];
or
NSString *md5 = [textField.text MD5Hash];
精彩评论