首页 > 代码库 > OC下Base64编码的中文字符编码问题
OC下Base64编码的中文字符编码问题
Base64是常用的编码规范之一,如网络传输中应用广泛,之前列举过base64编码的原理:《base64举例》 以及java实现的base64编码工具类。
这里,贴出OC下的base64代码,在平台之间通信过程中保证编码能通用——中间出现一个编码问题,google官方提供的base64Util包默认用的Utf-8编码,而中文之前统一用的gbk编码,以下代码修正了这个问题:
关键点:将CommonFunc的
base64StringFromText 和 textFromBase64String中的UTF8encoding改成gbkEncoding:
NSData *data = http://www.mamicode.com/[text dataUsingEncoding:NSUTF8StringEncoding];
改成
NSStringEncoding gbkEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSData *data = http://www.mamicode.com/[text dataUsingEncoding:gbkEncoding];
//// CommonFunc.h// Base64Proj//// Created by qslang on 14-6-12.// Copyright (c) 2014年 Dev. All rights reserved.#import <Foundation/Foundation.h>#define __BASE64( text ) [CommonFunc base64StringFromText:text]#define __TEXT( base64 ) [CommonFunc textFromBase64String:base64]@interface CommonFunc : NSObject/****************************************************************************** 函数名称 : + (NSString *)base64StringFromText:(NSString *)text 函数描述 : 将文本转换为base64格式字符串 输入参数 : (NSString *)text 文本 输出参数 : N/A 返回参数 : (NSString *) base64格式字符串 备注信息 : ******************************************************************************/+ (NSString *)base64StringFromText:(NSString *)text;/****************************************************************************** 函数名称 : + (NSString *)textFromBase64String:(NSString *)base64 函数描述 : 将base64格式字符串转换为文本 输入参数 : (NSString *)base64 base64格式字符串 输出参数 : N/A 返回参数 : (NSString *) 文本 备注信息 : ******************************************************************************/+ (NSString *)textFromBase64String:(NSString *)base64;@end
1 // 2 // CommonFunc.m 3 // Base64Proj 4 // 5 // Created by qslang on 14-6-12. 6 // Copyright (c) 2014年 Dev. All rights reserved. 7 // 8 9 #import "CommonFunc.h" 10 11 //引入IOS自带密码库 12 #import <CommonCrypto/CommonCryptor.h> 13 14 //空字符串 15 #define LocalStr_None @"" 16 17 static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 18 19 @implementation CommonFunc 20 21 + (NSString *)base64StringFromText:(NSString *)text 22 { 23 if (text && ![text isEqualToString:LocalStr_None]) { 24 NSStringEncoding gbkEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); 25 26 //取项目的bundleIdentifier作为KEY 改动了此处 27 //NSString *key = [[NSBundle mainBundle] bundleIdentifier]; 28 NSData *data = http://www.mamicode.com/[text dataUsingEncoding:gbkEncoding];//NSUTF8StringEncoding 29 //IOS 自带DES加密 Begin 改动了此处 30 //data = http://www.mamicode.com/[self DESEncrypt:data WithKey:key];> 31 //IOS 自带DES加密 End 32 return [self base64EncodedStringFrom:data]; 33 } 34 else { 35 return LocalStr_None; 36 } 37 } 38 39 + (NSString *)textFromBase64String:(NSString *)base64 40 { 41 if (base64 && ![base64 isEqualToString:LocalStr_None]) { 42 //取项目的bundleIdentifier作为KEY 改动了此处 43 //NSString *key = [[NSBundle mainBundle] bundleIdentifier]; 44 NSData *data =http://www.mamicode.com/ [self dataWithBase64EncodedString:base64]; 45 //IOS 自带DES解密 Begin 改动了此处 46 //data = http://www.mamicode.com/[self DESDecrypt:data WithKey:key];> 47 //IOS 自带DES加密 End 48 NSStringEncoding gbkEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); 49 50 return [[NSString alloc] initWithData:data encoding:gbkEncoding]; 51 } 52 else { 53 return LocalStr_None; 54 } 55 } 56 57 /****************************************************************************** 58 函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key 59 函数描述 : 文本数据进行DES加密 60 输入参数 : (NSData *)data 61 (NSString *)key 62 输出参数 : N/A 63 返回参数 : (NSData *) 64 备注信息 : 此函数不可用于过长文本 65 ******************************************************************************/ 66 + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key 67 { 68 char keyPtr[kCCKeySizeAES256+1]; 69 bzero(keyPtr, sizeof(keyPtr)); 70 71 [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; 72 73 NSUInteger dataLength = [data length]; 74 75 size_t bufferSize = dataLength + kCCBlockSizeAES128; 76 void *buffer = malloc(bufferSize); 77 78 size_t numBytesEncrypted = 0; 79 CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES, 80 kCCOptionPKCS7Padding | kCCOptionECBMode, 81 keyPtr, kCCBlockSizeDES, 82 NULL, 83 [data bytes], dataLength, 84 buffer, bufferSize, 85 &numBytesEncrypted); 86 if (cryptStatus == kCCSuccess) { 87 return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted]; 88 } 89 90 free(buffer); 91 return nil; 92 } 93 94 /****************************************************************************** 95 函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key 96 函数描述 : 文本数据进行DES解密 97 输入参数 : (NSData *)data 98 (NSString *)key 99 输出参数 : N/A100 返回参数 : (NSData *)101 备注信息 : 此函数不可用于过长文本102 ******************************************************************************/103 + (NSData *)DESDecrypt:(NSData *)data WithKey:(NSString *)key104 {105 char keyPtr[kCCKeySizeAES256+1];106 bzero(keyPtr, sizeof(keyPtr));107 108 [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];109 110 NSUInteger dataLength = [data length];111 112 size_t bufferSize = dataLength + kCCBlockSizeAES128;113 void *buffer = malloc(bufferSize);114 115 size_t numBytesDecrypted = 0;116 CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,117 kCCOptionPKCS7Padding | kCCOptionECBMode,118 keyPtr, kCCBlockSizeDES,119 NULL,120 [data bytes], dataLength,121 buffer, bufferSize,122 &numBytesDecrypted);123 124 if (cryptStatus == kCCSuccess) {125 return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];126 }127 128 free(buffer);129 return nil;130 }131 132 133 /******************************************************************************134 函数名称 : + (NSData *)dataWithBase64EncodedString:(NSString *)string135 函数描述 : base64格式字符串转换为文本数据136 输入参数 : (NSString *)string137 输出参数 : N/A138 返回参数 : (NSData *)139 备注信息 :140 ******************************************************************************/141 + (NSData *)dataWithBase64EncodedString:(NSString *)string142 {143 if (string == nil)144 [NSException raise:NSInvalidArgumentException format:nil];145 if ([string length] == 0)146 return [NSData data];147 148 static char *decodingTable = NULL;149 if (decodingTable == NULL)150 {151 decodingTable = malloc(256);152 if (decodingTable == NULL)153 return nil;154 memset(decodingTable, CHAR_MAX, 256);155 NSUInteger i;156 for (i = 0; i < 64; i++)157 decodingTable[(short)encodingTable[i]] = i;158 }159 160 const char *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];161 if (characters == NULL) // Not an ASCII string!162 return nil;163 char *bytes = malloc((([string length] + 3) / 4) * 3);164 if (bytes == NULL)165 return nil;166 NSUInteger length = 0;167 168 NSUInteger i = 0;169 while (YES)170 {171 char buffer[4];172 short bufferLength;173 for (bufferLength = 0; bufferLength < 4; i++)174 {175 if (characters[i] == ‘\0‘)176 break;177 if (isspace(characters[i]) || characters[i] == ‘=‘)178 continue;179 buffer[bufferLength] = decodingTable[(short)characters[i]];180 if (buffer[bufferLength++] == CHAR_MAX) // Illegal character!181 {182 free(bytes);183 return nil;184 }185 }186 187 if (bufferLength == 0)188 break;189 if (bufferLength == 1) // At least two characters are needed to produce one byte!190 {191 free(bytes);192 return nil;193 }194 195 // Decode the characters in the buffer to bytes.196 bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4);197 if (bufferLength > 2)198 bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2);199 if (bufferLength > 3)200 bytes[length++] = (buffer[2] << 6) | buffer[3];201 }202 203 bytes = realloc(bytes, length);204 return [NSData dataWithBytesNoCopy:bytes length:length];205 }206 207 + (NSString *)stringWithBase64EncodedString:(NSString *)string withEncoding:(NSStringEncoding)encoding208 {209 NSData *data = http://www.mamicode.com/[self dataWithBase64EncodedString:string];210 if (data)211 {212 return [[self alloc] initWithData:data encoding:encoding];213 }214 return nil;215 216 }217 218 //+ (NSString *)base64DecodedString:(NSStringEncoding)encoding219 //{220 // // return [self stringWithBase64EncodedString: withEncoding:encoding];221 // //data = http://www.mamicode.com/[self DESEncrypt:data WithKey:key];>222 //223 //}224 225 /******************************************************************************226 函数名称 : + (NSString *)base64EncodedStringFrom:(NSData *)data227 函数描述 : 文本数据转换为base64格式字符串228 输入参数 : (NSData *)data229 输出参数 : N/A230 返回参数 : (NSString *)231 备注信息 :232 ******************************************************************************/233 + (NSString *)base64EncodedStringFrom:(NSData *)data234 {235 if ([data length] == 0)236 return @"";237 238 char *characters = malloc((([data length] + 2) / 3) * 4);239 if (characters == NULL)240 return nil;241 NSUInteger length = 0;242 243 NSUInteger i = 0;244 while (i < [data length])245 {246 char buffer[3] = {0,0,0};247 short bufferLength = 0;248 while (bufferLength < 3 && i < [data length])249 buffer[bufferLength++] = ((char *)[data bytes])[i++];250 251 // Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.252 characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];253 characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];254 if (bufferLength > 1)255 characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];256 else characters[length++] = ‘=‘;257 if (bufferLength > 2)258 characters[length++] = encodingTable[buffer[2] & 0x3F];259 else characters[length++] = ‘=‘;260 }261 262 return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];263 }264 265 266 267 @end
调用代码:
NSString *str1 = @"*&*我爱你中国"; NSLog(@"baseStr=======%@",str1); NSString *encodes = [CommonFunc base64StringFromText:str1]; NSLog(@"encodeStr=========%@",[CommonFunc base64StringFromText:str1]); NSLog(@"decodeStr========%@",[CommonFunc textFromBase64String:encodes]);
结果:
2014-06-17 16:04:19.275 Base64Proj[23496:303] baseStr=======*&*我爱你中国2014-06-17 16:04:19.277 Base64Proj[23496:303] encodeStr=========KiYqztKwrsTj1tC5+g==2014-06-17 16:04:19.278 Base64Proj[23496:303] decodeStr========*&*我爱你中国Program ended with exit code: 0
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。