[IOS] MD5 encryption and Network Data Security

Source: Internet
Author: User

When creating network applications, you must always ensure the security of user data and therefore encrypt the data. MD5 algorithms are widely used in China.
MD5 Algorithm features: * The same data encryption results are the same. (32 characters) * irreversible. (reverse decryption is not allowed) * can be used for file verification/fingerprint recognition.
The MD5 algorithm is public, and the MD5 algorithm has been packaged in iOS. It can be written as a string classification:

- (NSString *)md5String{const char *string = self.UTF8String;int length = (int)strlen(string);unsigned char bytes[CC_MD5_DIGEST_LENGTH];CC_MD5(string, length, bytes);return [self stringFromBytes:bytes length:CC_MD5_DIGEST_LENGTH];}


It is very important to encrypt and store user login data in iOS programs. The original data cannot be restored even if the data is hijacked.
1. Common MD5 Encryption
The MD5 encryption is too simple to be cracked. It is usually used for MD5 encryption. "Add seasoning".
Simple MD5 can be cracked on this website: www.20.5.com
The following is the MD5 encryption method: TokenIt is a plus string, which can be an odd string of any length.
-(IBAction) login :( UIButton *) sender {[self postLogin];}/** it is relatively safe to use post when submitting user data. at the same time, it is best to convert user data into a model */-(void) postLogin {// 1. URLNSString * urlStr = [NSString stringWithFormat: @ "http: // localhost/login. php "]; NSURL * url = [NSURL URLWithString: urlStr]; // 2. create MutablerequestNSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; // 3. set request. HTTPMethod = @ "POST"; // you can find NSString * pwd = self in firebug. userPwd. text; // Add salt first and use MD5 encryption. (the server simply stores salt and encrypted storage ). in reality, there are public and private keys, and the server does not simply store passwords. pwd = [pwd stringByAppendingString: token]; pwd = [pwd md5String]; NSLog (@ "% @", pwd); NSString * body = [NSString stringWithFormat: @ "username = % @ & password = % @", self. userName. text, pwd]; request. HTTPBody = [body dataUsingEncoding: NSUTF8StringEncoding]; // 4. establish a connection. (data is the obtained data, just like get) [NSURLConnection sendAsynchronousRequest: request queue: [[NSOperationQueue alloc] init] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError) {NSString * str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (@ "% @, % @", [NSThread currentThread], str); // The update display must be in the main thread [[NSOperationQueue mainQueue] addOperationWithBlock: ^ {self. label. text = str; NSLog (@ "% @, % @", [NSThread currentThread], str) ;}];}

2. More advanced methods
Use the public key and private key concepts.
A Public Key (both known) and a private key (only known to the server ). the password must be dynamically changed. * User: Use the token + time for encryption and transfer to the server * server: retrieve the user password (use the private key for encryption during storage ), compare the time + public key with the password sent by the client. (The server also needs to check the time difference between sending passwords, within 1 minute)
For details, see the note: From Liu Lao.
-(IBAction) login :( id) sender {NSString * pwd = self. pwdText. text; // perform MD5 encryption pwd = [pwd stringByAppendingString: token]; // It is the same every time! For example, if a hacker intercepts data in a vro, the hacker can obtain the encrypted password! Pwd = [pwd md5String]; // In the server background, the MD5 password string pwd = [NSString stringWithFormat: @ "% @", pwd, publicKey, @ "2014062914: 14: 30"]; // Date used, the encrypted string is not the same as pwd = [pwd md5String]; // The content submitted to the server: new password, password generation event,/** server processing: 1. remove the user's password from the server (encrypted with a private key. the server knows the master key and compares it with the password submitted by the client based on the given time (a new password is dynamically generated. at the same time, the server needs to check the difference between the password submission event and the date submitted by the client within one minute. */NSLog (@ "% @", pwd); [self postLogonWithUserName: self. userNameText. text password: pwd] ;}# pragma mark-POST logon-(void) postLogonWithUserName :( NSString *) userName password :( NSString *) password {// 1. url NSString * urlStr = @ "http: // 192.168.25.2/login. php "; NSURL * url = [NSURL URLWithString: urlStr]; // 2. request, POST method, you need to create a variable request NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url ]; // 1> POST method. All data transmission involving user privacy must be submitted in POST mode! Request. HTTPMethod = @ "POST"; // 2> data body NSString * bodyStr = [NSString stringWithFormat: @ "username =%@ & password =%@", userName, password]; // convert the string into binary data request. HTTPBody = [bodyStr dataUsingEncoding: NSUTF8StringEncoding]; // 3. sends an "Asynchronous" request, which works in other threads and does not block the current thread program from executing [NSURLConnection sendAsynchronousRequest: request queue: [[NSOperationQueue alloc] init] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError) {// 1> JSON, which is in the same format as NSDictionary's quick packaging. // convert JSON to the dictionary Serialization NSDictionary * dict = [NSJSONSerialization JSONObjectWithData: data options: 1 error: NULL]; CZUserInfo * userInfo = [CZUserInfo userInfoWithDict: dict]; NSLog (@ "% @", userInfo. userId, userInfo. userName) ;}]; NSLog (@ "====== ");}


Reprinted please indicate the source: http://blog.csdn.net/xn4545945

Related Article

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.