In iOS development, MD5 or other hashes are often used to improve the security of your application. The most common operation is to MD5 the password and then transfer it. Of course, there are a lot of ready-made implementations, the blog is to implement the simplest and most commonly used encapsulation MD5 method, making it very convenient to call.
(1) realize a category called Crypto, inherit from NSString. Since we are all nsstring MD5, it is convenient to write the category call:
Implemented in Nsstring+crypto.h:
#import <Foundation/Foundation.h> @interface NSString (Crypto)-(NSString *) toMD5; @end
Implemented in NSSTRING+CRYPTO.M:
#import "Nsstring+crypto.h" #import <CommonCrypto/CommonDigest.h> @implementation nsstring (Crypto)-(NSString * ) toMD5 { const char *cstr = [self utf8string]; unsigned char result[cc_md5_digest_length]; CC_MD5 (CStr, (Cc_long) 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] ];} @end
Because the string after MD5 contains letters, you can modify the MD5 letters in uppercase or lowercase, depending on your actual needs. The above implementation is the lowercase letter, if required size, you can change "%02x" to "%02x", that is, lowercase x to uppercase X.
(2) method invocation: Directly using the string to be encrypted to call the ToMD5 () method, the returned string is the result of MD5.
#import "HSTestMD5ViewController.h" #import "Nsstring+crypto.h" @interface Hstestmd5viewcontroller () @ End@implementation hstestmd5viewcontroller-(void) viewdidload { [super viewdidload]; NSString *RR = [@ "123" toMD5]; NSLog (@ "%@", RR); } @end
Best practices for iOS development--MD5