IOS development diary 8-MD5 encryption, ios diary 8-MD5
Today, the blogger has a password encryption requirement and has encountered some difficulties. I would like to share with you the hope to make common progress.
MD5 encryption and SHA-1 encryption are two important encryption algorithms in the computer world. MD5 encryption is usually used to encrypt NSString, While SHA-1 encryption is usually used to encrypt URLs. Today we will share with you the MD5 encryption method.
To use MD5 encryption, add a category to NSString and import the header file <CommonCrypto/CommonDigest. h>.
Content in. h:
# Import <Foundation/Foundation. h>
# Import <CommonCrypto/CommonDigest. h>
@ Interface NSString (MD5encrypt)
-(NSString *) md5HexDigest;
@ End
. M content:
# Import "NSString + MD5encrypt. h"
@ Implementation NSString (MD5encrypt)
-(NSString *) md5HexDigest
{
Const char * original_str = [self UTF8String];
Unsigned char result [CC_MD5_DIGEST_LENGTH];
// CC_MD5 (original_str, strlen (original_str), result); the usage here is obviously incorrect. When original_str contains null characters (\ 0)
CC_MD5 (original_str, (unsigned int) self. length, result );
NSMutableString * hash = [NSMutableString string];
For (int I = 0; I <16; I ++)
[Hash appendFormat: @ "% 02X", result [I];
Return [hash lowercaseString];
}
@ End
Currently, MD5 is no longer absolutely secure. To solve this problem, We Can slightly improve MD5 to increase the difficulty of decryption:
1. Add Salt (Salt): Insert a random string at a fixed position in the plain text, and then perform MD5
2. Encryption first, followed by out-of-order: MD5 is performed on the plaintext, and then the characters in the encrypted MD5 string are in out-of-order.
In short, the objective is: Even if Hackers break the database, they cannot decrypt the correct plaintext.
/*** Use MD5 encryption directly */-(NSString *) digest :( NSString *) str {NSString * anwen = [str md5String];
NSLog (@ "% @-% @", str, anwen); return anwen;}/*** salt adding */-(NSString *) digest2 :( NSString *) str {str = [str stringByAppendingString: Salt]; NSString * anwen = [str md5String]; NSLog (@ "% @-% @", str, anwen); return anwen ;} /*** multiple MD5 */-(NSString *) digest3 :( NSString *) str {NSString * anwen = [str md5String]; anwen = [anwen md5String]; NSLog (@ "% @-% @", str, anwen); return anwen ;}
/*** Encrypt the data first and then unordered. We recommend that you use */-(NSString *) digest4 :( NSString *) str {NSString * anwen = [str md5String]; NSString * header = [anwen substringToIndex: 2]; NSString * footer = [anwen substringFromIndex: 2]; anwen = [footer stringByAppendingString: header]; NSLog (@ "% @-% @", str, anwen); return anwen ;}