最近在Android和IOS上都需要对用户的某些输入进行简单的加密,于是采用MD5加密方式。
- 首先将目的字符串加密一次,获得32位字符串
- 然后将32位字符串拆为2段,分别加密1次
- 最后将加密后的2段拼接,加密100次
下面是Android的Java部分和IOS的Objective-C部分
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util
{
public static String getMD5(String content) {
String s = makeMD5(content);
String s1 = null;
if (s != null) {
s1 = s.substring(0, 16);
}
String s2 = null;
if (s != null) {
s2 = s.substring(16, 32);
}
s1 = makeMD5(s1);
s2 = makeMD5(s2);
s = s1 + s2;
for (int i = 0; i < 100; i++) {
s = makeMD5(s);
}
return s;
}
private static String makeMD5(String content) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(content.getBytes());
return getHashString(messageDigest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
private static String getHashString(MessageDigest messageDigest) {
StringBuilder builder = new StringBuilder();
for (byte b : messageDigest.digest()) {
builder.append(Integer.toHexString( ( b >> 4 ) & 0xf ) );
builder.append(Integer.toHexString( b & 0xf ) );
}
return builder.toString();
}
}
#import "MD5Utils.h"
#import <CommonCrypto/CommonDigest.h>
@implementation MD5Utils
+(NSString*)MD5:(NSString *)input{
NSString* s = [self makeMd5:input];
NSString* s1 = [s substringToIndex:16];
NSString* s2 =[s substringFromIndex:16];
s1 = [self makeMd5:s1];
s2 = [self makeMd5:s2];
NSMutableString* md5String = [NSMutableString stringWithString:s1];
[md5String appendString:s2];
for(int i =0;i<100;i++){
md5String = [self makeMd5WithMutaleString:md5String];
}
return md5String;
}
+ (NSString*)makeMd5:(NSString*) str{
const char * pointer = [str UTF8String];
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
CC_MD5(pointer, (CC_LONG)strlen(pointer), md5Buffer);
NSMutableString *string = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[string appendFormat:@"%02x",md5Buffer[i]];
return string;
}
+ (NSMutableString*)makeMd5WithMutaleString:(NSMutableString*) str{
const char * pointer = [str UTF8String];
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
CC_MD5(pointer, (CC_LONG)strlen(pointer), md5Buffer);
NSMutableString *string = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[string appendFormat:@"%02x",md5Buffer[i]];
return string;
}
@end