我正在尝试使用CommonCrypto
生成密钥,PBKDF2
但我似乎无法导入CommonCrypto/CommonKeyDerivation.h
,我只是找不到它的错误。
有任何想法吗?
编辑:我可能应该提到我已经添加了安全框架,我可以导入所有其他CommonCrypto
标头。
我正在尝试使用CommonCrypto
生成密钥,PBKDF2
但我似乎无法导入CommonCrypto/CommonKeyDerivation.h
,我只是找不到它的错误。
有任何想法吗?
编辑:我可能应该提到我已经添加了安全框架,我可以导入所有其他CommonCrypto
标头。
这是我生成 AES256 密钥的方式。唯一有趣的是,我让 CommonCrypto 为我估算要使用多少轮。这似乎很简单。
#import <CommonCrypto/CommonKeyDerivation.h>
...
// Makes a random 256-bit salt
- (NSData*)generateSalt256 {
unsigned char salt[32];
for (int i=0; i<32; i++) {
salt[i] = (unsigned char)arc4random();
}
return [NSData dataWithBytes:salt length:32];
}
...
// Make keys!
NSString* myPass = @"MyPassword1234";
NSData* myPassData = [myPass dataUsingEncoding:NSUTF8StringEncoding];
NSData* salt = [self generateSalt256];
// How many rounds to use so that it takes 0.1s ?
int rounds = CCCalibratePBKDF(kCCPBKDF2, myPassData.length, salt.length, kCCPRFHmacAlgSHA256, 32, 100);
// Open CommonKeyDerivation.h for help
unsigned char key[32];
CCKeyDerivationPBKDF(kCCPBKDF2, myPassData.bytes, myPassData.length, salt.bytes, salt.length, kCCPRFHmacAlgSHA256, rounds, key, 32);
这是我使用的代码:
// Salt data getting from salt string.
NSData *saltData = [@"Salt String" dataUsingEncoding:NSUTF8StringEncoding];
// Data of String to generate Hash key(hexa decimal string).
NSData *passwordData = [@"Hash key generated string" dataUsingEncoding:NSUTF8StringEncoding];
// Hash key (hexa decimal) string data length.
NSMutableData *hashKeyData = [NSMutableData dataWithLength:CC_SHA1_DIGEST_LENGTH];
// Key Derivation using PBKDF2 algorithm.
int result = CCKeyDerivationPBKDF(kCCPBKDF2, passwordData.bytes, passwordData.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, 1000, hashKeyData.mutableBytes, hashKeyData.length);
// Hexa decimal or hash key string from hash key data.
NSString *hexDecimalString = hashKeyData.description;
NSLog(@"Hexa decimal string:%@", hexDecimalString);
你在为 iOS5 构建吗?或更早的版本?
头文件中定义的APICCKeyDerivationPBKDF
和CCCalibratePBKDF
仅在 IOS5(或 OSX 10.7)及更高版本上可用。
您可以通过在终端窗口中执行此操作来确保文件存在:
$ find /Developer/ -name CommonKeyDerivation.h
/Developer//Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/usr/include/CommonCrypto/CommonKeyDerivation.h
/Developer//Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk/usr/include/CommonCrypto/CommonKeyDerivation.h
/Developer//SDKs/MacOSX10.7.sdk/usr/include/CommonCrypto/CommonKeyDerivation.h