首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Objective-C 加密實戰:CocoaSecurity 實現 MD5、SHA1、SHA256、AES

     編輯:關於C語言

專案背景

用戶登入 API 需要對學號與請求時間串接字串進行 MD5 加密。採用成熟開源框架 CocoaSecurity (GitHub: paulery2014/CocoaSecurity) 實現多種加密演算法。

整合步驟

  1. 下載 CocoaSecurity 專案
  2. 拖入 Base64.h/m、CocoaSecurity.h/m 等核心檔案
  3. 在需使用處 #import "CocoaSecurity.h"

核心 API 使用範例

雜湊演算法 (單向)

// 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)

// 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) - 適用小資料量

// 需配合公鑰/私鑰使用,框架提供完整 RSA 簽名/驗證/加密/解密
// 具體 API 請參考 CocoaSecurity.h

CocoaSecurityResult 物件結構

@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;
}

安全性注意事項

  • MD5/SHA1 已不安全:碰撞攻擊風險,新專案請用 SHA256+
  • AES 金鑰管理:嚴禁硬編碼金鑰,應使用 Keychain/安全儲存
  • 傳輸加密:務必配合 HTTPS,加密不替代傳輸層安全
  • 時間戳防重放:伺服器端驗證時間窗口 (如 ±5 分鐘)

替代方案

若不想引入第三方框架,可直接使用 CommonCrypto 系統框架:

#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

// CC_MD5, CC_SHA1, CC_SHA256, CCCrypt 等 C API
// 需自行處理資料轉換與記憶體管理

結語

CocoaSecurity 封裝了 CommonCrypto 的複雜細節,提供簡潔的 Objective-C 介面,適合快速整合常見加密需求。生產環境請根據安全審計選擇適當演算法與金鑰管理策略。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved