Base64編碼過程:將二進制序列轉換爲Base64字符序列(ASCII碼序列)。ui
1、標準Base64字符表編碼
2、Base64編碼示例spa
編碼字符串"Hello!!",輸出結果"SGVsbG8hIQ=="code
3、Base64編碼blog
原理:一個字節包括8位二進制, 然而字符表總共才64個字符,用6位二進制徹底容納64個字符,因此每6位二進制轉換爲對應的Base64字符。接口
編碼過程:第一次讀6位二進制,該子節剩餘的2位轉到下一次操做。剛好最少3個字節(24位)能轉換成4個Base64字符,因此新數據的長度爲原來數據3分之4倍。字符串
特殊狀況處理:當原來數據的字節數不是3的倍數時,若是除3餘1時,規定在編碼後添加2個"=",若是除3餘2時,規定在編碼後添加1個"="。input
4、Base64編碼本身實現it
+(NSString*)base64fromData:(NSData*)originData
{
const uint8_t* input = (const uint8_t*)[originData bytes]; NSInteger originLength = [originData length]; static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; NSMutableData* encodeData = [NSMutableData dataWithLength:((originLength + 2) / 3) * 4]; uint8_t* output = (uint8_t*)encodeData.mutableBytes; NSInteger i; for (i=0; i < originLength; i += 3) { NSInteger value = 0; NSInteger j; for (j = i; j < (i + 3); j++) { value <<= 8; if (j < originLength) { value |= (0xFF & input[j]); } } NSInteger theIndex = (i / 3) * 4; output[theIndex + 0] = table[(value >> 18) & 0x3F]; output[theIndex + 1] = table[(value >> 12) & 0x3F]; output[theIndex + 2] = (i + 1) < originLength ? table[(value >> 6) & 0x3F] : '='; output[theIndex + 3] = (i + 2) < originLength ? table[(value >> 0) & 0x3F] : '='; } return [[NSString alloc] initWithData:encodeData encoding:NSASCIIStringEncoding]; }
5、NSData官方提供的Base64編碼接口io
/* Create an NSData from a Base-64 encoded NSString using the given options. By default, returns nil when the input is not recognized as valid Base-64. */ - (nullable instancetype)initWithBase64EncodedString:(NSString *)base64String options:(NSDataBase64DecodingOptions)options NS_AVAILABLE(10_9, 7_0); /* Create a Base-64 encoded NSString from the receiver's contents using the given options. */ - (NSString *)base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)options NS_AVAILABLE(10_9, 7_0); /* Create an NSData from a Base-64, UTF-8 encoded NSData. By default, returns nil when the input is not recognized as valid Base-64. */ - (nullable instancetype)initWithBase64EncodedData:(NSData *)base64Data options:(NSDataBase64DecodingOptions)options NS_AVAILABLE(10_9, 7_0); /* Create a Base-64, UTF-8 encoded NSData from the receiver's contents using the given options. */ - (NSData *)base64EncodedDataWithOptions:(NSDataBase64EncodingOptions)options NS_AVAILABLE(10_9, 7_0);