在NSString中存储密码而不在内存中可读,可以使用加密技术来实现。常见的加密算法有AES、RSA等。
在iOS开发中,可以使用Apple提供的加密库CommonCrypto来实现加密和解密。具体实现步骤如下:
在Xcode中,选择项目 -> 目标 -> 通用 -> 链接框架与库 -> 添加 -> 搜索CommonCrypto -> 添加
- (NSString *)AES256EncryptWithKey:(NSString *)key {
char keyPtr[kCCKeySizeAES256 + 1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL,
[self UTF8String], dataLength,
buffer, bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
return [NSString stringWithFormat:@"%@", [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted]];
}
free(buffer);
return nil;
}
- (NSString *)AES256DecryptWithKey:(NSString *)key {
char keyPtr[kCCKeySizeAES256 + 1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL,
[self bytes], dataLength,
buffer, bufferSize,
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
return [[NSString alloc] initWithBytes:buffer length:numBytesDecrypted encoding:NSUTF8StringEncoding];
}
free(buffer);
return nil;
}
NSString *password = @"password";
NSString *key = @"1234567890123456";
NSString *encryptedPassword = [password AES256EncryptWithKey:key];
NSString *decryptedPassword = [encryptedPassword AES256DecryptWithKey:key];
这样,在NSString中存储密码时,就可以使用加密技术来保证密码的安全性,同时避免在内存中可读。
领取专属 10元无门槛券
手把手带您无忧上云