【发布时间】:2016-04-09 23:41:12
【问题描述】:
我有一个加密字符串和平的方法。方法似乎工作得很好。我的问题是我不知道如何使用它,所以我可以将数据存储在加密的核心数据中。
在我的实现下面,我有以下代码行:
#define CC_USERNAME @"myusername"
#define CC_PASSWORD @"mypassrod"
#define CC_SALTED_STRING [NSString stringWithFormat:@"someRandomStringHere%@anDhEreAsWEll", CC_PASSWORD]
方法如下:
-(void)encryptWebsiteUrl {
NSData *hash = [NSData sha256forData:CC_SALTED_STRING];
NSData *iVector = [NSData generateRandomIV:16];
NSInteger row = [self.websitesTableView selectedRow];
NSTableColumn *column = [self.websitesTableView tableColumnWithIdentifier:@"websiteUrl"];
NSCell *cell = [column dataCellForRow:row];
NSLog(@"cell value:%@", [cell stringValue]);
NSString *message = [cell stringValue]; // here, I should get the cell value
NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *encryptedData = [[NSMutableData alloc] initWithData:iVector];
NSData *payLoad = [NSData encrypt:messageData key:hash iv:iVector];
[encryptedData appendData:payLoad];
message = encryptedData;
NSLog(@"Encrypted message is: %@",message);
NSData *pureData = [encryptedData subdataWithRange:NSMakeRange(16, [encryptedData length] - 16)];
NSData *extractedVector = [encryptedData subdataWithRange:NSMakeRange(0, 16)];
NSData *decryptedData = [NSData decrypt:pureData key:hash iv:extractedVector];
NSString *decryptedMessage = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
//NSLog(@"Decrypted message is: %@",decryptedMessage);
}
现在,我这样调用这个方法:
-(void)controlTextDidEndEditing:(NSNotification *)obj {
[self encryptWebsiteUrl];
}
在控制台日志中,我有以下输出:
单元格值:www.newone.com 加密消息为:
在加密方式中,我使用的是self.websitesTableView。那是只有一列的表格视图,我在其中存储了我的数据,并且该列被命名为 websiteUrl(参见方法中的代码)
我的问题是:如何使用这种方法将 websiteUrl 的加密值存储在现在未加密存储的核心数据中。
我想在这里提到两件事。一,在核心数据中,属性 websiteUrl 是可转换的,二是我使用了绑定,这也是我没有在 websiteTableView 中发布任何与保存或插入数据相关的代码的原因。
【问题讨论】:
-
你能在绑定中使用值转换器吗?
-
我不知道该怎么做。
-
如果你使用绑定,使用
arraycontroller.selectedObjects而不是tableview.selectedRow来获取数据。 -
对不起,我的意思是价值转换器。查找
NSValueTransformer。 -
格式化程序 (
NSFormatter) 也可以解决问题。
标签: cocoa core-data encryption