【问题标题】:Implementing a file format to be used with Encryption - Cocoa实现与加密一起使用的文件格式 - Cocoa
【发布时间】:2011-12-25 18:41:38
【问题描述】:

我需要在我的加密中实现盐,但要这样做,我需要以我需要创建的文件格式存储它,以便我以后可以检索它来解密。在加密方面,我是菜鸟。文件格式的规范应该是这样的:

密文:密文长度; 盐:盐的长度;

然后把密文和盐写出来。这是 xcode 真正让我感到困惑的地方,例如创建新文件等。

我该怎么做?然后取回盐进行解密?

谢谢,非常感谢您的帮助。

【问题讨论】:

    标签: cocoa encryption aes file-format salt


    【解决方案1】:

    您可以考虑像这样使用NSMutableDictionaryNSKeyedUnarchiver

    // Example ciphertext and salt
    NSString *ciphertext = @"the ciphertext";
    NSString *salt = @"the salt";
    
    // File destination
    NSString *path = @"/Users/Anne/Desktop/Archive.dat";
    
    // Create dictionary with ciphertext and salt
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setObject:ciphertext forKey:@"ciphertext"];
    [dictionary setObject:salt forKey:@"salt"];
    
    // Archive dictionary and write to file
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictionary];
    [data writeToFile:path options:NSDataWritingAtomic error:nil];
    
    // Read file and unarchive
    NSMutableDictionary *theDictionary = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    
    // Get ciphertext and salt
    NSString *theCiphertext = [theDictionary objectForKey:@"ciphertext"];
    NSString *theSalt = [theDictionary objectForKey:@"salt"];
    
    // Show Result
    NSLog(@"Extracted ciphertext: %@",theCiphertext);
    NSLog(@"Extracted salt: %@",theSalt);
    

    输出:

    Extracted ciphertext: the ciphertext
    Extracted salt: the salt
    

    编辑

    回复评论:NSDataNSString 都具有 length

    快速示例:

    NSString *theString = @"Example String";
    NSData *theData = [theString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSUInteger stringLength = [theString length];
    NSUInteger dataLength = [theData length];
    
    NSLog(@"String length: %ld",stringLength);
    NSLog(@"Data length: %ld",dataLength);
    

    输出:

    String length: 14
    Data length: 14
    

    【讨论】:

    • 哇!太好了,所以这可以将加密捆绑到文件格式中并将其写入文件?而且由于加密的数据是 NSData 类型的,所以我必须先将其转换为字符串才能使用这种格式?
    • 或者我可以只使用类型 NSData,如 NSData *ciphertext =@"ciphertext"。可能是一个愚蠢的问题,但只是澄清
    • 所有符合NSCoding协议的类都可以被NSKeyedArchiver使用。例如检查NSData Class Reference 并注意NSCoding 在“符合”部分下提到。综上所述,NSStringNSData都符合NSKeyedArchiver要求的NSCoding协议,都可以使用。
    • 确实NSKeyedArchiver 可用于存储几乎所有内容并且易于实现。
    • 谢谢,帮了大忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 2011-01-31
    • 1970-01-01
    相关资源
    最近更新 更多