Created
September 26, 2014 03:13
-
-
Save qingjoin/1c31b4c3d95afd04a0bb to your computer and use it in GitHub Desktop.
iOS 经常用到的一些方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// GLSupprot.h | |
// GameLive | |
// | |
// Created by qingyun on 5/3/13. | |
// Copyright (c) 2013 qingyun. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
#import <UIKit/UIKit.h> | |
#import <QuartzCore/QuartzCore.h> | |
#import <commoncrypto/CommonDigest.h> | |
@interface GLSupprot : NSObject | |
//是否为数字或字母 | |
+(BOOL)isGlalnum:(NSString*)str; | |
+(NSString*)randomStr; | |
+ (UIImage *)GLimageNamed:(NSString *)name; | |
+(NSString*)md5Str:(NSString*)str; | |
//判断当前屏幕朝向。Yes 为竖屏 | |
+(BOOL)isViewPortrait; | |
//转json 格式 | |
+(NSString*)dataTOjsonString:(id)object; | |
+(BOOL)ismyIos7; | |
//Yes 为phone | |
+(BOOL)isPhoneOrPad; | |
//是否有网络 | |
+(BOOL)isNetworkStatus; | |
//电话号码是否正确 | |
+(BOOL)isPhoneNum:(NSString*)num; | |
//data to jsonString | |
+(NSString*)DataTojsonString:(id)object; | |
//Mac address 7.0后不支持 | |
+ (NSString *)macaddress; | |
+(NSString *) platform; | |
+(NSString *) platformString; | |
//url encode | |
+(NSString*)UrlValueEncode:(NSString*)str; | |
//字符串里取数字 | |
+ (NSString *)getOnlyNum:(NSString *)str; | |
+ (UIColor *)colorWithString:(NSString*)colorString alpha:(CGFloat)alpha; | |
//文本先进行DES加密。然后再转成base64 | |
+ (NSString *)base64StringFromText:(NSString *)text withKey:(NSString*)key; | |
//先把base64转为文本。然后再DES解密 | |
+ (NSString *)textFromBase64String:(NSString *)base64 withKey:(NSString*)key; | |
//文本数据进行DES加密 | |
+ (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key; | |
//文本数据进行DES解密 | |
+ (NSData *)DESDecrypt:(NSData *)data WithKey:(NSString *)key; | |
//base64格式字符串转换为文本数据 | |
+ (NSData *)dataWithBase64EncodedString:(NSString *)string; | |
//文本数据转换为base64格式字符串 | |
+ (NSString *)base64EncodedStringFrom:(NSData *)data; | |
//字节数组转化16进制数 | |
+(NSString *) parseByteArray2HexString:(Byte[]) bytes; | |
//将16进制数据转化成NSData 数组 | |
+(NSData*) parseHexToByteArray:(NSString*) hexString; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// GLSupprot.m | |
// GameLive | |
// | |
// Created by qingyun on 5/3/13. | |
// Copyright (c) 2013 qingyun. All rights reserved. | |
// | |
#import "GLSupprot.h" | |
#import "GLLoginViewController.h" | |
#import "CommonCrypto/CommonDigest.h" //MD5 | |
#import <SystemConfiguration/SystemConfiguration.h> | |
#import <CommonCrypto/CommonCryptor.h> //DES 加密 | |
//mac address | |
#include <sys/socket.h> // Per msqr | |
#include <sys/sysctl.h> | |
#include <net/if.h> | |
#include <net/if_dl.h> | |
#define my_ImgSize ([GLSupprot isPhoneOrPad])? 2: 1 //iphone时。原图缩小一倍 | |
@implementation GLSupprot | |
static const char _randomStr[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^*()"; | |
+(NSString*)randomStr | |
{ | |
char datas[32]; | |
for (int x=0;x<32;datas[x++] =_randomStr[arc4random()%71]); | |
return [[NSString alloc] initWithBytes:datas length:32 encoding:NSUTF8StringEncoding]; | |
} | |
//是否为数字或字母 | |
+(BOOL)isGlalnum:(NSString*)str; | |
{ | |
const char *ch = [str cStringUsingEncoding:NSASCIIStringEncoding]; | |
for (int i = 0; i < strlen(ch); i++) | |
{ | |
if( isalnum(ch[i])) | |
{ | |
return YES; | |
} | |
else | |
{ | |
return NO; | |
} | |
} | |
return YES; | |
} | |
//资源文件读取 | |
+ (UIImage *)GLimageNamed:(NSString *)name | |
{ | |
NSBundle * libBundle = MYBUNDLE ; | |
if ( libBundle && name ){ | |
NSString * s=[[libBundle resourcePath ] stringByAppendingPathComponent : name]; | |
if ( [[[UIDevice currentDevice] systemVersion] intValue] >= 4 || [[UIScreen mainScreen] scale] == 2.0 ) { | |
// NSLog(@"scale=2"); | |
return [UIImage imageWithCGImage:[[UIImage imageWithContentsOfFile:s] CGImage] | |
scale:my_ImgSize orientation:UIImageOrientationUp]; //2.0 | |
} | |
return [UIImage imageWithContentsOfFile:s]; | |
} | |
return nil; | |
} | |
//MD5 加密 | |
+(NSString*)md5Str:(NSString*)str | |
{ | |
NSString *md5str; | |
const char *cStr = [str UTF8String]; | |
unsigned char result[CC_MD5_DIGEST_LENGTH]; | |
// unsigned char result[64]; | |
CC_MD5(cStr, strlen(cStr), result); | |
NSMutableString *hash = [NSMutableString string]; | |
for (int i = 0; i < 16; i++) | |
{ | |
[hash appendFormat:@"%02X", result[i]]; | |
} | |
md5str = [hash lowercaseString]; | |
return md5str; | |
// const char* Cstr = [str UTF8String]; | |
// unsigned char result[CC_MD5_DIGEST_LENGTH]; | |
// CC_MD5(Cstr, strlen(Cstr), result); | |
// | |
// NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2]; | |
// for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) { | |
// [ret appendFormat:@"%02x",result[i]]; | |
// } | |
// return ret; | |
} | |
+(BOOL)isViewPortrait | |
{ | |
if(UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation)) | |
{ | |
return YES; | |
} | |
return NO; | |
} | |
+(BOOL)isPhoneOrPad //YES 为iphone | |
{ | |
if([GamePlusAPI sharedGamePlus].isSupportOnlyInIphone ) | |
{ | |
return YES; | |
} | |
if([[UIDevice currentDevice].model isEqualToString:@"iPhone"] || [[UIDevice currentDevice].model isEqualToString:@"iPhone Simulator"] ||[[UIDevice currentDevice].model isEqualToString:@"iPod touch"]) | |
{ | |
return YES; | |
} | |
if([[UIDevice currentDevice].model isEqualToString:@"iPad"] || [[UIDevice currentDevice].model isEqualToString:@"iPad Simulator"]) | |
{ | |
return NO; | |
} | |
return NO; | |
} | |
+(BOOL)ismyIos7 | |
{ | |
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) | |
{ | |
return NO; | |
} | |
return YES; | |
} | |
//转json 格式 | |
+(NSString*)dataTOjsonString:(id)object | |
{ | |
NSString *jsonString = nil; | |
NSError *error; | |
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object | |
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string | |
error:&error]; | |
if (! jsonData) { | |
NSLog(@"Got an error: %@", error); | |
} else { | |
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; | |
} | |
return jsonString; | |
} | |
//data to jsonString | |
+(NSString*)DataTojsonString:(id)object | |
{ | |
NSString *jsonString = nil; | |
NSError *error; | |
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object | |
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string | |
error:&error]; | |
if (! jsonData) { | |
NSLog(@"Got an error: %@", error); | |
} else { | |
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; | |
} | |
return jsonString; | |
} | |
//是否有网络 | |
+(BOOL)isNetworkStatus | |
{ | |
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES; | |
const char *host = "www.baidu.com"; | |
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host); | |
SCNetworkReachabilityFlags flags; | |
BOOL connected = SCNetworkReachabilityGetFlags(reachability, &flags); | |
BOOL isConnected = YES; | |
isConnected = connected && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired); | |
CFRelease(reachability); | |
return isConnected; | |
} | |
//电话号码是否正确 | |
+(BOOL)isPhoneNum:(NSString*)num | |
{ | |
NSError *error = NULL; | |
NSString *pattern = @"^(13[0-9]|15[0-9]|18[0-9]|14[0-9])[0-9]{8}$"; | |
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern | |
options:NSRegularExpressionCaseInsensitive | |
error:&error]; | |
NSUInteger numberofMatch = [regex numberOfMatchesInString:num | |
options:NSMatchingReportProgress | |
range:NSMakeRange(0, num.length)]; | |
if(numberofMatch > 0) | |
{ | |
return YES; | |
} | |
else | |
{ | |
return NO; | |
} | |
} | |
//url encode | |
+(NSString*)UrlValueEncode:(NSString*)str | |
{ | |
NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, | |
(__bridge CFStringRef)str, | |
NULL, | |
CFSTR("!*'();:@&=+$,/?%#[]"), | |
kCFStringEncodingUTF8); | |
[result autorelease]; | |
return result; | |
} | |
//字符串里取数字 | |
+ (NSString *)getOnlyNum:(NSString *)str | |
{ | |
NSString *onlyNumStr = [str stringByReplacingOccurrencesOfString:@"[^0-9,]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [str length])]; | |
return onlyNumStr; | |
} | |
//颜色#XXXXX | |
+ (UIColor *)colorWithString:(NSString*)colorString alpha:(CGFloat)alpha{ | |
NSString *hexColor = [[colorString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString]; | |
if ([hexColor length] < 6) { | |
return [UIColor blackColor]; | |
} | |
if ([hexColor hasPrefix:@"#"]) { | |
hexColor = [hexColor substringFromIndex:1]; | |
} | |
if ([hexColor length] != 6 && [hexColor length] != 8) { | |
return [UIColor blackColor]; | |
} | |
NSRange range; | |
range.location = 0; | |
range.length = 2; | |
NSString *rString = [hexColor substringWithRange:range]; | |
range.location = 2; | |
NSString *gString = [hexColor substringWithRange:range]; | |
range.location = 4; | |
NSString *bString = [hexColor substringWithRange:range]; | |
range.location = 6; | |
NSString *aString = @"FF"; | |
if ([hexColor length] == 8) { | |
aString = [hexColor substringWithRange:range]; | |
} | |
// Scan values | |
unsigned int r, g, b, a; | |
[[NSScanner scannerWithString:rString] scanHexInt:&r]; | |
[[NSScanner scannerWithString:gString] scanHexInt:&g]; | |
[[NSScanner scannerWithString:bString] scanHexInt:&b]; | |
[[NSScanner scannerWithString:aString] scanHexInt:&a]; | |
return [UIColor colorWithRed:((float) r / 255.0f) | |
green:((float) g / 255.0f) | |
blue:((float) b / 255.0f) | |
alpha:alpha]; | |
} | |
#pragma mark Mac address7.0不支持 | |
//mac address | |
// Return the local MAC addy | |
// Courtesy of FreeBSD hackers email list | |
// Accidentally munged during previous update. Fixed thanks to erica sadun & mlamb. | |
+ (NSString *)macaddress{ | |
int mib[6]; | |
size_t len; | |
char *buf; | |
unsigned char *ptr; | |
struct if_msghdr *ifm; | |
struct sockaddr_dl *sdl; | |
mib[0] = CTL_NET; | |
mib[1] = AF_ROUTE; | |
mib[2] = 0; | |
mib[3] = AF_LINK; | |
mib[4] = NET_RT_IFLIST; | |
if ((mib[5] = if_nametoindex("en0")) == 0) { | |
printf("Error: if_nametoindex error\n"); | |
return NULL; | |
} | |
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { | |
printf("Error: sysctl, take 1\n"); | |
return NULL; | |
} | |
if ((buf = malloc(len)) == NULL) { | |
printf("Could not allocate memory. error!\n"); | |
return NULL; | |
} | |
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { | |
printf("Error: sysctl, take 2"); | |
free(buf); | |
return NULL; | |
} | |
ifm = (struct if_msghdr *)buf; | |
sdl = (struct sockaddr_dl *)(ifm + 1); | |
ptr = (unsigned char *)LLADDR(sdl); | |
NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X", | |
*ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)]; | |
free(buf); | |
return outstring; | |
} | |
#pragma mark phone infomation | |
//device | |
+(NSString *) platform{ | |
size_t size; | |
sysctlbyname("hw.machine", NULL, &size, NULL, 0); | |
char *machine = malloc(size); | |
sysctlbyname("hw.machine", machine, &size, NULL, 0); | |
NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding]; | |
free(machine); | |
return platform; | |
} | |
+(NSString *) platformString{ | |
NSString *platform = [self platform]; | |
if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 1G"; | |
if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G"; | |
if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS"; | |
if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4"; | |
if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G"; | |
if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G"; | |
if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G"; | |
if ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G"; | |
if ([platform isEqualToString:@"iPad1,1"]) return @"iPad"; | |
if ([platform isEqualToString:@"i386"] || [platform isEqualToString:@"x86_64"]) return @"iPhone Simulator"; | |
return platform; | |
} | |
//文本先进行DES加密。然后再转成base64 | |
+ (NSString *)base64StringFromText:(NSString *)text withKey:(NSString*)key | |
{ | |
if (text && ![text isEqualToString:@""]) { | |
//取项目的bundleIdentifier作为KEY | |
//NSString *key = [[NSBundle mainBundle] bundleIdentifier]; | |
NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding]; | |
//IOS 自带DES加密 Begin | |
data = [self DESEncrypt:data WithKey:key]; | |
//IOS 自带DES加密 End | |
return [self base64EncodedStringFrom:data]; | |
} | |
else { | |
return @""; | |
} | |
} | |
//先把base64转为文本。然后再DES解密 | |
+ (NSString *)textFromBase64String:(NSString *)base64 withKey:(NSString*)key | |
{ | |
if (base64 && ![base64 isEqualToString:@""]) { | |
//取项目的bundleIdentifier作为KEY | |
//NSString *key = [[NSBundle mainBundle] bundleIdentifier]; | |
NSData *data = [self dataWithBase64EncodedString:base64]; | |
//IOS 自带DES解密 Begin | |
data = [self DESDecrypt:data WithKey:key]; | |
//IOS 自带DES加密 End | |
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; | |
} | |
else { | |
return @""; | |
} | |
} | |
/****************************************************************************** | |
函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key | |
函数描述 : 文本数据进行DES加密 | |
输入参数 : (NSData *)data | |
(NSString *)key | |
输出参数 : N/A | |
返回参数 : (NSData *) | |
备注信息 : 此函数不可用于过长文本 | |
******************************************************************************/ | |
+ (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key | |
{ | |
char keyPtr[kCCKeySizeAES256+1]; | |
bzero(keyPtr, sizeof(keyPtr)); | |
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; | |
NSUInteger dataLength = [data length]; | |
size_t bufferSize = dataLength + kCCBlockSizeAES128; | |
void *buffer = malloc(bufferSize); | |
size_t numBytesEncrypted = 0; | |
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES, | |
kCCOptionPKCS7Padding | kCCOptionECBMode, | |
keyPtr, kCCBlockSizeDES, | |
NULL, | |
[data bytes], dataLength, | |
buffer, bufferSize, | |
&numBytesEncrypted); | |
if (cryptStatus == kCCSuccess) { | |
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted]; | |
} | |
free(buffer); | |
return nil; | |
} | |
/****************************************************************************** | |
函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key | |
函数描述 : 文本数据进行DES解密 | |
输入参数 : (NSData *)data | |
(NSString *)key | |
输出参数 : N/A | |
返回参数 : (NSData *) | |
备注信息 : 此函数不可用于过长文本 | |
******************************************************************************/ | |
+ (NSData *)DESDecrypt:(NSData *)data WithKey:(NSString *)key | |
{ | |
char keyPtr[kCCKeySizeAES256+1]; | |
bzero(keyPtr, sizeof(keyPtr)); | |
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; | |
NSUInteger dataLength = [data length]; | |
size_t bufferSize = dataLength + kCCBlockSizeAES128; | |
void *buffer = malloc(bufferSize); | |
size_t numBytesDecrypted = 0; | |
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES, | |
kCCOptionPKCS7Padding | kCCOptionECBMode, | |
keyPtr, kCCBlockSizeDES, | |
NULL, | |
[data bytes], dataLength, | |
buffer, bufferSize, | |
&numBytesDecrypted); | |
if (cryptStatus == kCCSuccess) { | |
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted]; | |
} | |
free(buffer); | |
return nil; | |
} | |
/****************************************************************************** | |
函数名称 : + (NSData *)dataWithBase64EncodedString:(NSString *)string | |
函数描述 : base64格式字符串转换为文本数据 | |
输入参数 : (NSString *)string | |
输出参数 : N/A | |
返回参数 : (NSData *) | |
备注信息 : | |
******************************************************************************/ | |
static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | |
+ (NSData *)dataWithBase64EncodedString:(NSString *)string | |
{ | |
if (string == nil) | |
[NSException raise:NSInvalidArgumentException format:nil]; | |
if ([string length] == 0) | |
return [NSData data]; | |
static char *decodingTable = NULL; | |
if (decodingTable == NULL) | |
{ | |
decodingTable = malloc(256); | |
if (decodingTable == NULL) | |
return nil; | |
memset(decodingTable, CHAR_MAX, 256); | |
NSUInteger i; | |
for (i = 0; i < 64; i++) | |
decodingTable[(short)encodingTable[i]] = i; | |
} | |
const char *characters = [string cStringUsingEncoding:NSASCIIStringEncoding]; | |
if (characters == NULL) // Not an ASCII string! | |
return nil; | |
char *bytes = malloc((([string length] + 3) / 4) * 3); | |
if (bytes == NULL) | |
return nil; | |
NSUInteger length = 0; | |
NSUInteger i = 0; | |
while (YES) | |
{ | |
char buffer[4]; | |
short bufferLength; | |
for (bufferLength = 0; bufferLength < 4; i++) | |
{ | |
if (characters[i] == '\0') | |
break; | |
if (isspace(characters[i]) || characters[i] == '=') | |
continue; | |
buffer[bufferLength] = decodingTable[(short)characters[i]]; | |
if (buffer[bufferLength++] == CHAR_MAX) // Illegal character! | |
{ | |
free(bytes); | |
return nil; | |
} | |
} | |
if (bufferLength == 0) | |
break; | |
if (bufferLength == 1) // At least two characters are needed to produce one byte! | |
{ | |
free(bytes); | |
return nil; | |
} | |
// Decode the characters in the buffer to bytes. | |
bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4); | |
if (bufferLength > 2) | |
bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2); | |
if (bufferLength > 3) | |
bytes[length++] = (buffer[2] << 6) | buffer[3]; | |
} | |
bytes = realloc(bytes, length); | |
// alloc memory 20140227 内存释放 | |
//(decodingTable); | |
// alloc memory 20140227 内存释放 | |
return [NSData dataWithBytesNoCopy:bytes length:length]; | |
} | |
/****************************************************************************** | |
函数名称 : + (NSString *)base64EncodedStringFrom:(NSData *)data | |
函数描述 : 文本数据转换为base64格式字符串 | |
输入参数 : (NSData *)data | |
输出参数 : N/A | |
返回参数 : (NSString *) | |
备注信息 : | |
******************************************************************************/ | |
+ (NSString *)base64EncodedStringFrom:(NSData *)data | |
{ | |
if ([data length] == 0) | |
return @""; | |
char *characters = malloc((([data length] + 2) / 3) * 4); | |
if (characters == NULL) | |
return nil; | |
NSUInteger length = 0; | |
NSUInteger i = 0; | |
while (i < [data length]) | |
{ | |
char buffer[3] = {0,0,0}; | |
short bufferLength = 0; | |
while (bufferLength < 3 && i < [data length]) | |
buffer[bufferLength++] = ((char *)[data bytes])[i++]; | |
// Encode the bytes in the buffer to four characters, including padding "=" characters if necessary. | |
characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2]; | |
characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)]; | |
if (bufferLength > 1) | |
characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)]; | |
else characters[length++] = '='; | |
if (bufferLength > 2) | |
characters[length++] = encodingTable[buffer[2] & 0x3F]; | |
else characters[length++] = '='; | |
} | |
//NSLog(@"xxxxx:%@",[[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES]); | |
return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES]; | |
//NSString *str = [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES]; | |
// alloc memory 20140227 内存释放 | |
//free(characters); | |
//NSLog(@"strff:%@",str); | |
// alloc memory 20140227 内存释放 | |
//return str; | |
} | |
/** | |
字节数组转化16进制数 | |
*/ | |
+(NSString *) parseByteArray2HexString:(Byte[]) bytes | |
{ | |
NSMutableString *hexStr = [[NSMutableString alloc]init]; | |
int i = 0; | |
if(bytes) | |
{ | |
while (bytes[i] != '\0') | |
{ | |
NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数 | |
if([hexByte length]==1) | |
[hexStr appendFormat:@"0%@", hexByte]; | |
else | |
[hexStr appendFormat:@"%@", hexByte]; | |
i++; | |
} | |
} | |
NSLog(@"bytes 的16进制数为:%@",hexStr); | |
return [hexStr uppercaseString]; | |
} | |
/* | |
将16进制数据转化成NSData 数组 | |
*/ | |
+(NSData*) parseHexToByteArray:(NSString*) hexString | |
{ | |
int j=0; | |
Byte bytes[hexString.length]; | |
for(int i=0;i<[hexString length];i++) | |
{ | |
int int_ch; /// 两位16进制数转化后的10进制数 | |
unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16) | |
int int_ch1; | |
if(hex_char1 >= '0' && hex_char1 <='9') | |
int_ch1 = (hex_char1-48)*16; //// 0 的Ascll - 48 | |
else if(hex_char1 >= 'A' && hex_char1 <='F') | |
int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65 | |
else | |
int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97 | |
i++; | |
unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位) | |
int int_ch2; | |
if(hex_char2 >= '0' && hex_char2 <='9') | |
int_ch2 = (hex_char2-48); //// 0 的Ascll - 48 | |
else if(hex_char2 >= 'A' && hex_char1 <='F') | |
int_ch2 = hex_char2-55; //// A 的Ascll - 65 | |
else | |
int_ch2 = hex_char2-87; //// a 的Ascll - 97 | |
int_ch = int_ch1+int_ch2; | |
bytes[j] = int_ch; ///将转化后的数放入Byte数组里 | |
j++; | |
} | |
NSData *newData = [[NSData alloc] initWithBytes:bytes length:hexString.length/2]; | |
//NSLog(@"newData=%@",newData); | |
return newData; | |
} | |
///****************************************************************************** | |
//DES加密 | |
static Byte iv[] = {1,2,3,4,5,6,7,8}; | |
+(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key | |
{ | |
NSString *ciphertext = nil; | |
const char *textBytes = [plainText UTF8String]; | |
NSUInteger dataLength = [plainText length]; | |
unsigned char buffer[1024]; | |
memset(buffer, 0, sizeof(char)); | |
size_t numBytesEncrypted = 0; | |
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES, | |
kCCOptionECBMode|kCCOptionPKCS7Padding, //kCCOptionECBMode kCCOptionPKCS7Padding | |
[key UTF8String], kCCKeySizeDES, | |
iv, | |
textBytes, dataLength, | |
buffer, 1024, | |
&numBytesEncrypted); | |
if (cryptStatus == kCCSuccess) { | |
NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted]; | |
//ciphertext = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; | |
//NSLog(@"ssf:%s",buffer); | |
ciphertext = [GLSupprot base64Encoding:data]; | |
// NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted]; | |
// Byte* bb = (Byte*)[data bytes]; | |
// ciphertext = [self parseByteArray2HexString:bb]; | |
} | |
return ciphertext; | |
} | |
//base64Encoding string | |
+(NSString *)base64Encoding:(NSData*) text | |
{ | |
if (text.length == 0) | |
return @""; | |
char *characters = malloc(text.length*3/2); | |
if (characters == NULL) | |
return @""; | |
int end = text.length - 3; | |
int index = 0; | |
int charCount = 0; | |
int n = 0; | |
while (index <= end) { | |
int d = (((int)(((char *)[text bytes])[index]) & 0x0ff) << 16) | |
| (((int)(((char *)[text bytes])[index + 1]) & 0x0ff) << 8) | |
| ((int)(((char *)[text bytes])[index + 2]) & 0x0ff); | |
characters[charCount++] = encodingTable[(d >> 18) & 63]; | |
characters[charCount++] = encodingTable[(d >> 12) & 63]; | |
characters[charCount++] = encodingTable[(d >> 6) & 63]; | |
characters[charCount++] = encodingTable[d & 63]; | |
index += 3; | |
if(n++ >= 14) | |
{ | |
n = 0; | |
characters[charCount++] = ' '; | |
} | |
} | |
if(index == text.length - 2) | |
{ | |
int d = (((int)(((char *)[text bytes])[index]) & 0x0ff) << 16) | |
| (((int)(((char *)[text bytes])[index + 1]) & 255) << 8); | |
characters[charCount++] = encodingTable[(d >> 18) & 63]; | |
characters[charCount++] = encodingTable[(d >> 12) & 63]; | |
characters[charCount++] = encodingTable[(d >> 6) & 63]; | |
characters[charCount++] = '='; | |
} | |
else if(index == text.length - 1) | |
{ | |
int d = ((int)(((char *)[text bytes])[index]) & 0x0ff) << 16; | |
characters[charCount++] = encodingTable[(d >> 18) & 63]; | |
characters[charCount++] = encodingTable[(d >> 12) & 63]; | |
characters[charCount++] = '='; | |
characters[charCount++] = '='; | |
} | |
NSString * rtnStr = [[NSString alloc] initWithBytesNoCopy:characters length:charCount encoding:NSUTF8StringEncoding freeWhenDone:YES]; | |
return rtnStr; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment