用戶登入 API 需要對學號與請求時間串接字串進行 MD5 加密。採用成熟開源框架 CocoaSecurity (GitHub: paulery2014/CocoaSecurity) 實現多種加密演算法。
Base64.h/m、CocoaSecurity.h/m 等核心檔案#import "CocoaSecurity.h"// MD5
CocoaSecurityResult *md5 = [CocoaSecurity md5:@"input_string"];
NSLog(@"MD5 Hex: %@", md5.hex); // 十六進制大寫
NSLog(@"MD5 HexLower: %@", md5.hexLower); // 十六進制小寫
NSLog(@"MD5 Base64: %@", md5.base64); // Base64 編碼
// SHA1
CocoaSecurityResult *sha1 = [CocoaSecurity sha1:@"input_string"];
// SHA256
CocoaSecurityResult *sha256 = [CocoaSecurity sha256:@"input_string"];
// AES 加密
CocoaSecurityResult *aes = [CocoaSecurity aesEncrypt:@"plaintext" key:@"secretkey"];
NSLog(@"AES Hex: %@", aes.hex);
NSLog(@"AES Base64: %@", aes.base64);
// AES 解密
CocoaSecurityResult *dec = [CocoaSecurity aesDecrypt:aes.hex key:@"secretkey"];
NSLog(@"解密結果: %@", dec.string);
// 需配合公鑰/私鑰使用,框架提供完整 RSA 簽名/驗證/加密/解密
// 具體 API 請參考 CocoaSecurity.h
@interface CocoaSecurityResult : NSObject
@property (nonatomic, strong) NSString *hex; // 大寫十六進制
@property (nonatomic, strong) NSString *hexLower; // 小寫十六進制
@property (nonatomic, strong) NSString *base64; // Base64 編碼
@property (nonatomic, strong) NSString *string; // 原始字串 (解密時)
@property (nonatomic, strong) NSData *data; // 原始二進制資料
@end
- (NSString *)generateLoginSignature:(NSString *)studentId timestamp:(NSInteger)timestamp {
// 串接字串:學號 + 時間戳
NSString *raw = [NSString stringWithFormat:@"%@%ld", studentId, (long)timestamp];
// MD5 加密
CocoaSecurityResult *result = [CocoaSecurity md5:raw];
// 返回小寫十六進制 (API 常見要求)
return result.hexLower;
}
若不想引入第三方框架,可直接使用 CommonCrypto 系統框架:
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
// CC_MD5, CC_SHA1, CC_SHA256, CCCrypt 等 C API
// 需自行處理資料轉換與記憶體管理
CocoaSecurity 封裝了 CommonCrypto 的複雜細節,提供簡潔的 Objective-C 介面,適合快速整合常見加密需求。生產環境請根據安全審計選擇適當演算法與金鑰管理策略。