不要将用户密码保存在设置包中。
它不安全。
记住,你不需要知道原始密码是什么,你需要知道用户输入的密码是否匹配原始密码。在 iOS 中处理密码的正确方法是
- 使用钥匙串,就像其他人提到的那样
- 使用 SHA-512 或其他加密生成加密单向哈希函数,并将生成的哈希和盐存储在
NSUserDefaults
在这些选项中,加密密码和存储哈希+盐是迄今为止最简单的。存储密码的方法如下:
- 从用户那里获取密码
- 创建随机盐值
- 使用 SHA-512 和随机盐值创建只进哈希
- 将生成的哈希值和盐值存储在
NSUserDefaults 中——黑客无法使用这些值来确定原始密码,因此无需将它们存储在安全的地方。
现在,当用户输入他们的密码并且您必须验证它是否正确时,您需要执行以下操作:
- 从用户那里获取密码
- 从
NSUserDefaults获取之前保存的哈希值+盐值
- 使用与加密原始密码相同的单向散列函数创建一个只进散列 - 将尝试的密码和来自
NSUserDefaults 的盐值传递给它
- 将生成的哈希值与存储在
NSUSerDefaults 中的哈希值进行比较。如果它们相同,则用户输入了正确的密码。
这是生成盐和只进哈希的代码:
NSString *FZARandomSalt(void) {
uint8_t bytes[16] = {0};
int status = SecRandomCopyBytes(kSecRandomDefault, 16, bytes);
if (status == -1) {
NSLog(@"Error using randomization services: %s", strerror(errno));
return nil;
}
NSString *salt = [NSString stringWithFormat: @"%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
bytes[0], bytes[1], bytes[2], bytes[3],
bytes[4], bytes[5], bytes[6], bytes[7],
bytes[8], bytes[9], bytes[10], bytes[11],
bytes[12], bytes[13], bytes[14], bytes[15]];
return salt;
}
NSData *FZAHashPassword(NSString *password, NSString *salt) {
NSCParameterAssert([salt length] >= 32);
uint8_t hashBuffer[64] = {0};
NSString *saltedPassword = [[salt substringToIndex: 32] stringByAppendingString: password];
const char *passwordBytes = [saltedPassword cStringUsingEncoding: NSUTF8StringEncoding];
NSUInteger length = [saltedPassword lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
CC_SHA512(passwordBytes, length, hashBuffer);
for (NSInteger i = 0; i < 4999; i++) {
CC_SHA512(hashBuffer, 64, hashBuffer);
}
return [NSData dataWithBytes: hashBuffer length: 64];
}
此示例的代码可在此处找到:http://blog.securemacprogramming.com/2011/04/storing-and-testing-credentials-cocoa-touch-edition/