Best practices for iOS development--MD5

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.