风险在于您可以在任何应用程序上运行字符串工具( 尝试它, 它有点可怕), 并从代码中获取字符串 。 一般来说, 我建议在应用程序中包装这些秘密, 但将其保留在别处的安全服务器上 。 如果您必须把它放在应用程序中, 您可以做的一件事就是混淆字符串, 这样它就不明显了 。
NSString *secret = kTwitterClientSecret;
NSData *secretData = [secret dataUsingEncoding:NSUTF8StringEncoding];
NSString *key = @"Twitter";
[secretData obfuscateOrDeobfuscateWithKey:key];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [NSString stringWithFormat:@"%@/%@-%@", documentsPath, key, @"output"];
[secretData writeToFile:path atomically:NO];
NSLog(@"Wrote obfuscated data to: %@", documentsPath);
在 NSData 上, 模糊 Or Deobfuscate withkeey 是 NSData 的类别
// Inspiration from: http://iosdevelopertips.com/cocoa/obfuscation-encryption-of-string-nsstring.html
- (void)obfuscateOrDeobfuscateWithKey:(NSString *)key
{
// Get pointer to data to obfuscate
char *dataPtr = (char *) [self bytes];
// Get pointer to key data
char *keyData = (char *) [[key dataUsingEncoding:NSUTF8StringEncoding] bytes];
// Points to each char in sequence in the key
char *keyPtr = keyData;
int keyIndex = 0;
// For each character in data, xor with current value in key
for (int x = 0; x < [self length]; x++) {
// Replace current character in data with current character xor d with current key value.
// Bump each pointer to the next character.
*dataPtr = *dataPtr ^ *keyPtr;
dataPtr++;
keyPtr++;
// If at end of key data, reset count and set key pointer back to start of key value
if (++keyIndex == [key length]) {
keyIndex = 0, keyPtr = keyData;
}
}
}
然后,你可以宣布一个常数是
static unsigned char const kTwitterClientSecret[] = {
0x00, 0x00, 0x00, ... etc ...
};
static unsigned int const kTwitterClientSecret_len = LENGTH;
然后把绳子拿回来,你就可以了
[NSString deobfuscatedStringWithBytes:kTwitterClientSecret length:kTwitterClientSecret_len key:@"Twitter"];
这是NSString的类别
+ (NSString *)deobfuscatedStringWithBytes:(const void *)bytes length:(NSUInteger)length key:(NSString *)key
{
NSData *deobfuscatedData = [NSData dataWithBytes:bytes length:length];
[deobfuscatedData obfuscateOrDeobfuscateWithKey:key];
return [[NSString alloc] initWithData:deobfuscatedData encoding:NSUTF8StringEncoding];
}
这将做非常简单的混淆 并且不会出现在字符串中。