-(NSString *)MD5ForLower32Bate:(NSString *)str
{
constchar* input = [str UTF8String];
unsignedchar result[CC_MD5_DIGEST_LENGTH];
CC_MD5(input, (CC_LONG)strlen(input), result);
NSMutableString *digest = [NSMutableStringstringWithCapacity:CC_MD5_DIGEST_LENGTH *2];
for (NSInteger i =0; i < CC_MD5_DIGEST_LENGTH; i++) {
[digest appendFormat:@"%02x", result[i]];
}
return digest;
}
- (NSData *)AES128EncryptWithKey:(NSString *)key //加密
{
char keyPtr[kCCKeySizeAES128+1];
// bzero(keyPtr, sizeof(keyPtr));
memset(keyPtr,0, sizeof(keyPtr));
[key getCString:keyPtrmaxLength:sizeof(keyPtr)encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [selflength];
size_t bufferSize = dataLength +kCCBlockSizeAES128;
void *buffer =malloc(bufferSize);
size_t numBytesEncrypted =0;
CCCryptorStatus cryptStatus =CCCrypt(kCCEncrypt,kCCAlgorithmAES,
0x0000 | kCCOptionECBMode,
keyPtr,kCCBlockSizeAES128,
NULL,
[selfbytes], dataLength,
buffer, bufferSize,
&numBytesEncrypted);
if (cryptStatus ==kCCSuccess) {
return [NSDatadataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
returnnil;
}
- (NSData *)AES128DecryptWithKey:(NSString *)key //解密
{
char keyPtr[kCCKeySizeAES128+1];
// bzero(keyPtr, sizeof(keyPtr));
memset(keyPtr, 0, sizeof(keyPtr));
[key getCString:keyPtrmaxLength:sizeof(keyPtr)encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [selflength];
size_t bufferSize = dataLength +kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted =0;
CCCryptorStatus cryptStatus =CCCrypt(kCCDecrypt,kCCAlgorithmAES128,
kCCOptionPKCS7Padding |kCCOptionECBMode,
keyPtr, kCCBlockSizeAES128,
NULL,
[selfbytes], dataLength,
buffer, bufferSize,
&numBytesDecrypted);
if (cryptStatus ==kCCSuccess) {
return [NSDatadataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer);
return nil;
}
- (NSString *)newStringInBase64FromData //追加64编码
{
NSMutableString *dest = [[NSMutableStringalloc] initWithString:@""];
unsignedchar * working = (unsignedchar *)[selfbytes];
int srcLen = (int)[selflength];
for (int i=0; i< srcLen; i +=3){
for (int nib=0; nib<4; nib++) {
int byt = (nib ==0)?0:nib-1;
int ix = (nib+1)*2;
if (i+byt >= srcLen)break;
unsignedchar curr = ((working[i+byt] << (8-ix)) &0x3F);
if (i+nib < srcLen) curr |= ((working[i+nib] >> ix) &0x3F);
[dest appendFormat:@"%c",base64[curr]];
}
}
return dest;
}
- (NSString *)hexStringFromData:(NSData *)data {
Byte *bytes = (Byte *)[databytes];
// 下面是Byte转换为16进制。
NSString *hexStr =@"";
for(int i=0; i<[datalength]; i++) {
NSString *newHexStr = [NSStringstringWithFormat:@"%x",bytes[i] &0xff]; //16进制数
newHexStr = [newHexStr uppercaseString];
if([newHexStr length] == 1) {
newHexStr = [NSStringstringWithFormat:@"0%@",newHexStr];
}
hexStr = [hexStr stringByAppendingString:newHexStr];
}
return hexStr;
}