iOS工具 - Base64

Base64

1 - Base64 是网络上最常见的用于传输 8 Bit 字节码的编码方式之一,Base64 就是一种基于 64 个可打印字符来表示二进制数据的方法

2 - 代码封装

// - Base64.h

复制代码
 1 #define __BASE64( text )        [CommonFunc base64StringFromText:text]
 2 #define __TEXT( base64 )        [CommonFunc textFromBase64String:base64]
 3 #import <Foundation/Foundation.h>
 4 @interface Base64 : NSObject
 5 
 6 // Base64 编码
 7 + (NSString *)base64StringFromText:(NSString *)text;// 方式一
 8 + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key;// 方式二
 9 
10 // Base64 解码
11 + (NSString *)textFromBase64String:(NSString *)base64;// 方式一
12 + (NSData *)DESDecrypt:(NSData *)data WithKey:(NSString *)key;// 方式二
13 
14 // base64 格式字符串转换为文本数据
15 + (NSData *)dataWithBase64EncodedString:(NSString *)string;
16 // 文本数据转换为 base64 格式字符串
17 + (NSString *)base64EncodedStringFrom:(NSData *)data;
18 
19 
20 @end
复制代码

// - Base64.m

复制代码
  1 #import "Base64.h"
  2 #import <CommonCrypto/CommonCryptor.h>
  3 #define  LocalStr_None  @""
  4 static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5 @implementation Base64
  6 
  7 // Base64 编码
  8 + (NSString *)base64StringFromText:(NSString *)text{
  9     if (text && ![text isEqualToString:LocalStr_None]) {
 10         // 获取项目的 bundleIdentifier 作为 KEY
 11         //NSString *key = [[NSBundle mainBundle] bundleIdentifier];
 12         NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
 13         // iOS 自带 DES 加密 Begin
 14         //data = [self DESEncrypt:data WithKey:key];
 15         // iOS 自带 DES 加密 End
 16         return [self base64EncodedStringFrom:data];
 17     }
 18     else {
 19         return LocalStr_None;
 20     }
 21 }
 22 
 23 // Base64 解码
 24 + (NSString *)textFromBase64String:(NSString *)base64{
 25     if (base64 && ![base64 isEqualToString:LocalStr_None]) {
 26         // 获取项目的 bundleIdentifier 作为 KEY
 27         //NSString *key = [[NSBundle mainBundle] bundleIdentifier];
 28         NSData *data = [self dataWithBase64EncodedString:base64];
 29         // iOS 自带 DES 解密 Begin
 30         //data = [self DESDecrypt:data WithKey:key];
 31         // iOS 自带 DES 加密 End
 32         return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
 33     }
 34     else {
 35         return LocalStr_None;
 36     }
 37 }
 38 
 39 // Base64加密(不可用于过长文本)
 40 + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key{
 41     char keyPtr[kCCKeySizeAES256+1];
 42     bzero(keyPtr, sizeof(keyPtr));
 43 
 44     [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
 45 
 46     NSUInteger dataLength = [data length];
 47 
 48     size_t bufferSize = dataLength + kCCBlockSizeAES128;
 49     void *buffer = malloc(bufferSize);
 50 
 51     size_t numBytesEncrypted = 0;
 52     CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
 53                                           kCCOptionPKCS7Padding | kCCOptionECBMode,
 54                                           keyPtr, kCCBlockSizeDES,
 55                                           NULL,
 56                                           [data bytes], dataLength,
 57                                           buffer, bufferSize,
 58                                           &numBytesEncrypted);
 59     if (cryptStatus == kCCSuccess) {
 60         return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
 61     }
 62 
 63     free(buffer);
 64     return nil;
 65 }
 66 
 67 // Base64 解密(不可用于过长文本)
 68 + (NSData *)DESDecrypt:(NSData *)data WithKey:(NSString *)key{
 69     char keyPtr[kCCKeySizeAES256+1];
 70     bzero(keyPtr, sizeof(keyPtr));
 71 
 72     [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
 73 
 74     NSUInteger dataLength = [data length];
 75 
 76     size_t bufferSize = dataLength + kCCBlockSizeAES128;
 77     void *buffer = malloc(bufferSize);
 78 
 79     size_t numBytesDecrypted = 0;
 80     CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,
 81                                           kCCOptionPKCS7Padding | kCCOptionECBMode,
 82                                           keyPtr, kCCBlockSizeDES,
 83                                           NULL,
 84                                           [data bytes], dataLength,
 85                                           buffer, bufferSize,
 86                                           &numBytesDecrypted);
 87 
 88     if (cryptStatus == kCCSuccess) {
 89         return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
 90     }
 91 
 92     free(buffer);
 93     return nil;
 94 }
 95 
 96 // base64 格式字符串转换为文本数据
 97 + (NSData *)dataWithBase64EncodedString:(NSString *)string{
 98     if (string == nil)
 99         [NSException raise:NSInvalidArgumentException format:@""];
100     if ([string length] == 0)
101         return [NSData data];
102 
103     static char *decodingTable = NULL;
104     if (decodingTable == NULL)
105     {
106         decodingTable = malloc(256);
107         if (decodingTable == NULL)
108             return nil;
109         memset(decodingTable, CHAR_MAX, 256);
110         NSUInteger i;
111         for (i = 0; i < 64; i++)
112             decodingTable[(short)encodingTable[i]] = i;
113     }
114 
115     const char *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];
116     if (characters == NULL)     //  Not an ASCII string!
117         return nil;
118     char *bytes = malloc((([string length] + 3) / 4) * 3);
119     if (bytes == NULL)
120         return nil;
121     NSUInteger length = 0;
122 
123     NSUInteger i = 0;
124     while (YES)
125     {
126         char buffer[4];
127         short bufferLength;
128         for (bufferLength = 0; bufferLength < 4; i++)
129         {
130             if (characters[i] == '\0')
131                 break;
132             if (isspace(characters[i]) || characters[i] == '=')
133                 continue;
134             buffer[bufferLength] = decodingTable[(short)characters[i]];
135             if (buffer[bufferLength++] == CHAR_MAX)      //  Illegal character!
136             {
137                 free(bytes);
138                 return nil;
139             }
140         }
141 
142         if (bufferLength == 0)
143             break;
144         if (bufferLength == 1)      //  At least two characters are needed to produce one byte!
145         {
146             free(bytes);
147             return nil;
148         }
149 
150         //  Decode the characters in the buffer to bytes.
151         bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4);
152         if (bufferLength > 2)
153             bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2);
154         if (bufferLength > 3)
155             bytes[length++] = (buffer[2] << 6) | buffer[3];
156     }
157 
158     bytes = realloc(bytes, length);
159     return [NSData dataWithBytesNoCopy:bytes length:length];
160 }
161 
162 // 文本数据转换为 base64 格式字符串
163 + (NSString *)base64EncodedStringFrom:(NSData *)data{
164     if ([data length] == 0)
165         return @"";
166 
167     char *characters = malloc((([data length] + 2) / 3) * 4);
168     if (characters == NULL)
169         return nil;
170     NSUInteger length = 0;
171 
172     NSUInteger i = 0;
173     while (i < [data length])
174     {
175         char buffer[3] = {0,0,0};
176         short bufferLength = 0;
177         while (bufferLength < 3 && i < [data length])
178             buffer[bufferLength++] = ((char *)[data bytes])[i++];
179 
180         //  Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.
181         characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];
182         characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
183         if (bufferLength > 1)
184             characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
185         else characters[length++] = '=';
186         if (bufferLength > 2)
187             characters[length++] = encodingTable[buffer[2] & 0x3F];
188         else characters[length++] = '=';
189     }
190 
191     return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
192 }
193 
194 @end
复制代码

 

posted on   低头捡石頭  阅读(21)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示