AesGcm
是高级加密标准(AES)的伽罗瓦/计数器模式(GCM)的 ObjC 实现。
安装
AesGcm 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中
pod "AesGcm"
使用
#import <AesGcm/IAGAesGcm.h>
#import <CommonCrypto/CommonCrypto.h>
// Define an Encryption Key
u_char keyBytes[kCCKeySizeAES128] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10};
NSData *key = [NSData dataWithBytes:keyBytes length:sizeof(keyBytes)];
// Define an Initialization Vector
// GCM recommends a IV size of 96 bits (12 bytes), but you are free to use other sizes
u_char ivBytes[12] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C};
NSData *iv = [NSData dataWithBytes:ivBytes length:sizeof(ivBytes)];
// Define an Additional Authenticated Data
NSData *aad = [@"AdditionalAuthenticatedData" dataUsingEncoding:NSUTF8StringEncoding];
// Now, we are ready to encrypt some plain data
NSData *expectedPlainData = [@"PlainData" dataUsingEncoding:NSUTF8StringEncoding];
// The returned ciphered data is a simple class with 2 properties: the actual encrypted data and the authentication tag.
// The authentication tag can have multiple sizes and it is up to you to set one, in this case the size is 128 bits
// (16 bytes)
IAGCipheredData *cipheredData = [IAGAesGcm cipheredDataByAuthenticatedEncryptingPlainData:expectedPlainData
withAdditionalAuthenticatedData:aad
authenticationTagLength:IAGAuthenticationTagLength128
initializationVector:iv
key:key
error:nil];
// And now, de-cypher the encrypted data to see if the returned plain data is as expected
NSData *plainData = [IAGAesGcm plainDataByAuthenticatedDecryptingCipheredData:cipheredData
withAdditionalAuthenticatedData:aad
initializationVector:iv
key:key
error:nil];
XCTAssertEqualObjects(expectedPlainData, plainData);
致谢
此实现基于以下文件
许可证
AesGcm 在 MIT 许可下可用。更多信息请参阅 LICENSE 文件。