App 的資料安全,早已是開發者最在意的一環。單靠 MD5 或 Base64 這類手段,放在今天的標準下幾乎等於門戶洞開。本文帶你動手實作 AES 與 Base64 的複合加解密流程。
AES(Advanced Encryption Standard,高階加密標準)源自比利時密碼學家 Joan Daemen 與 Vincent Rijmen 提出的 Rijndael 演算法。美國政府為取代日漸老舊的 DES,經歷約五年的公開甄選,最終由美國國家標準與技術研究院(NIST)於 2001 年 11 月 26 日以 FIPS PUB 197 正式發布,並在隔年 5 月 26 日生效。到了 2006 年,AES 已成為對稱式金鑰加密領域最主流的演算法之一。
在 iOS 上,我們不需要自己刻演算法,Apple 提供的 CommonCrypto 函式庫就已經把 CCCrypt 這類底層 API 準備好了。實務上常見的做法是:先用 AES 把 bytes 加密,再用 Base64 把結果轉成可安全傳輸的純文字。因為 AES 的輸出是任意二進位內容,直接塞進 JSON 或 URL 往往會出問題,Base64 正好扮演「編碼外殼」的角色。
先在專案裡新增一個 NSData 的分類(Category),命名為 NSData+AES,然後在標頭檔匯入 CommonCrypto 的相關標頭:
#import <Foundation/Foundation.h> #import <CommonCrypto/CommonDigest.h> #import <CommonCrypto/CommonCryptor.h> @interface NSData (AES) // 加密 - (NSData *)AES256_EncryptWithKey:(NSString *)key; // 解密 - (NSData *)AES256_DecryptWithKey:(NSString *)key; // 取得 Base64 字串 - (NSString *)base64EncodedStringFromData; // 直接把字串轉成 Base64 + (NSString *)base64EncodeString:(NSString *)str; @end
在 .m 檔中依序實作。這裡的關鍵在於金鑰的準備:AES-256 需要 32 bytes 的金鑰,所以我們先把 buffer 清零,再把使用者傳入的 NSString 轉成 C 字串寫入。
#import "NSData+AES.h"
static const char kBase64Table[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@implementation NSData (AES)
#pragma mark - 加密
- (NSData *)AES256_EncryptWithKey:(NSString *)key {
char keyPtr[kCCKeySizeAES256 + 1];
memset(keyPtr, 0, sizeof(keyPtr));
[key getCString:keyPtr
maxLength:sizeof(keyPtr)
encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus status = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding | kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
NULL, /* ECB 模式不需要 IV */
[self bytes],
dataLength,
buffer,
bufferSize,
&numBytesEncrypted);
if (status == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;
}
#pragma mark - 解密
- (NSData *)AES256_DecryptWithKey:(NSString *)key {
char keyPtr[kCCKeySizeAES256 + 1];
memset(keyPtr, 0, sizeof(keyPtr));
[key getCString:keyPtr
maxLength:sizeof(keyPtr)
encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus status = CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding | kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
NULL,
[self bytes],
dataLength,
buffer,
bufferSize,
&numBytesDecrypted);
if (status == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer);
return nil;
}
@end
Base64 的原理是每 3 bytes(24 bits)切分成 4 段 6 bits,各自對應到 64 個字元表中的一個。不足的部分則以 = 補齊。
- (NSString *)base64EncodedStringFromData {
const unsigned char *bytes = (const unsigned char *)[self bytes];
NSUInteger length = [self length];
char *out = malloc(((length + 2) / 3) * 4 + 1);
if (out == NULL) {
return nil;
}
NSUInteger j = 0;
for (NSUInteger i = 0; i < length; i += 3) {
NSUInteger remain = length - i;
unsigned long value = ((unsigned long)bytes[i]) << 16;
if (remain > 1) { value |= ((unsigned long)bytes[i + 1]) << 8; }
if (remain > 2) { value |= (unsigned long)bytes[i + 2]; }
out[j++] = kBase64Table[(value >> 18) & 0x3F];
out[j++] = kBase64Table[(value >> 12) & 0x3F];
out[j++] = (remain > 1) ? kBase64Table[(value >> 6) & 0x3F] : '=';
out[j++] = (remain > 2) ? kBase64Table[value & 0x3F] : '=';
}
out[j] = '\0';
return [[NSString alloc] initWithBytesNoCopy:out
length:j
encoding:NSASCIIStringEncoding
freeWhenDone:YES];
}
+ (NSString *)base64EncodeString:(NSString *)str {
if ([str length] == 0) {
return @"";
}
const char *source = [str UTF8String];
int strLength = (int)strlen(source);
char *characters = malloc(((strLength + 2) / 3) * 4);
if (characters == NULL) {
return nil;
}
NSUInteger length = 0;
NSUInteger i = 0;
while (i < strLength) {
char buffer[3] = {0, 0, 0};
short bufferLength = 0;
while (bufferLength < 3 && i < strLength) {
buffer[bufferLength++] = source[i++];
}
characters[length++] = kBase64Table[(buffer[0] & 0xFC) >> 2];
characters[length++] = kBase64Table[((buffer[0] & 0x03) << 4) |
((buffer[1] & 0xF0) >> 4)];
characters[length++] = (bufferLength > 1)
? kBase64Table[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)]
: '=';
characters[length++] = (bufferLength > 2)
? kBase64Table[buffer[2] & 0x3F]
: '=';
}
return [[NSString alloc] initWithBytesNoCopy:characters
length:length
encoding:NSASCIIStringEncoding
freeWhenDone:YES];
}
如果不想處理 Base64,也可以把加密結果轉成十六進位字串,這種表示法只包含 0-9 與 a-f,同樣能安全地放進任何文字協定裡。做法幾乎和上面一樣,只要再建一個 NSString+AES 的分類即可。
#import <Foundation/Foundation.h> #import "NSData+AES.h" @interface NSString (AES) // 加密,回傳十六進位字串 - (NSString *)AES256_EncryptWithKey:(NSString *)key; // 解密 - (NSString *)AES256_DecryptWithKey:(NSString *)key; @end
#import "NSString+AES.h"
@implementation NSString (AES)
// 加密
- (NSString *)AES256_EncryptWithKey:(NSString *)key {
const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:strlen(cstr)];
// 交由 NSData 的分類完成實際加密
NSData *result = [data AES256_EncryptWithKey:key];
if (result == nil || result.length == 0) {
return nil;
}
// 轉為十六進位字串
Byte *bytes = (Byte *)[result bytes];
NSMutableString *output = [NSMutableString stringWithCapacity:result.length * 2];
for (NSUInteger i = 0; i < result.length; i++) {
[output appendFormat:@"%02x", bytes[i]];
}
return output;
}
// 解密
- (NSString *)AES256_DecryptWithKey:(NSString *)key {
// 十六進位字串還原成 Data
NSMutableData *data = [NSMutableData dataWithCapacity:self.length / 2];
unsigned char wholeByte;
char byteChars[3] = {'\0', '\0', '\0'};
for (NSUInteger i = 0; i < [self length] / 2; i++) {
byteChars[0] = [self characterAtIndex:i * 2];
byteChars[1] = [self characterAtIndex:i * 2 + 1];
wholeByte = (unsigned char)strtol(byteChars, NULL, 16);
[data appendBytes:&wholeByte length:1];
}
NSData *result = [data AES256_DecryptWithKey:key];
if (result != nil && result.length > 0) {
return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
}
return nil;
}
@end
加密的類別寫好之後,呼叫起來非常直覺。以下在 ViewController 裡同時示範兩種用法:
#import "ViewController.h"
#import "NSString+AES.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 這個 key 必須和後端約定一致,否則無法解密
NSString *key = @"12345678";
NSString *secret = @"aes Bison base64";
// 字串加密
NSString *cipherHex = [secret AES256_EncryptWithKey:key];
NSLog(@"字串加密 --- %@", cipherHex);
// 字串解密
NSLog(@"字串解密 --- %@", [cipherHex AES256_DecryptWithKey:key]);
// NSData 加密 + Base64
NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];
NSData *cipher = [plain AES256_EncryptWithKey:key];
NSLog(@"NSData 加密 + Base64 ++++ %@", [cipher base64EncodedStringFromData]);
// 解密還原
NSData *decrypted = [cipher AES256_DecryptWithKey:key];
NSLog(@"NSData 解密 + Base64 ++++ %@",
[[NSString alloc] initWithData:decrypted encoding:NSUTF8StringEncoding]);
}
@end
執行後,主控台大致會印出這樣的結果:
2016-03-30 17:31:55.686 AES_256[14242:198853] 字串加密 --- 07815ca46d20acc3ba4e43d6930c7537496e851a36dbeac34fa30c5796089b02 2016-03-30 17:31:55.687 AES_256[14242:198853] 字串解密 --- aes Bison base64 2016-03-30 17:31:55.687 AES_256[14242:198853] NSData 加密 + Base64 ++++ B4FcpG0grMO6TkPWkwx1N0luhRo22+rDT6MMV5YImwI 2016-03-30 17:31:55.687 AES_256[14242:198853] NSData 解密 + Base64 ++++ aes Bison base64
金鑰必須與後端一致。這是新手最常踩的坑。雙方約定的 key、編碼(UTF-8)、填充方式(PKCS7)與模式都要相同,任何一項對不上,解密就會失敗或得到亂碼。
不要把金鑰寫死並提交進版本庫。App 內的常數再怎麼隱藏,都還是能被逆向取出。較穩妥的做法是透過 HTTPS 協商、使用 Keychain 保存,或改用非對稱加密交換金鑰。
示例中的 ECB 模式只用於教學。ECB 對相同明文會產生相同密文,容易洩漏資料的結構特徵。正式環境建議改用 CBC 或 GCM 模式,並為每次加密產生隨機 IV 一起傳送。
Base64 是編碼,不是加密。它能讓二進位資料安全地通過文字通道,但完全不提供機密性,兩者搭配使用才是原意所在。