cocoa - 实现与加密一起使用的文件格式 - Cocoa

标签 cocoa encryption aes file-format salt

我需要在加密中实现盐,但要做到这一点,我需要将其存储为我需要创建的文件格式,以便稍后检索它进行解密。在加密方面我是个菜鸟。文件格式规范如下:

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

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

我该怎么做?然后检索盐进行解密?

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

最佳答案

您可以考虑使用 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都具有长度

简单示例:

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

关于cocoa - 实现与加密一起使用的文件格式 - Cocoa,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8073351/

相关文章:

java - 在java中使用cipher,如何使加密文件的长度为16的倍数?

javascript - 为什么 AES 函数返回不同的值?

xcode - Cocoa 框架内静态库和动态库之间的轻松转换

objective-c - 使用 Restkit 为核心数据创建临时对象的更好方法

iphone - 在 iphone/ipad 的持久存储上加密数据的最安全方法是什么?

java - 为什么我每次都会得到不同的加密

Java 密码学扩展和无限力量

objective-c - AVFoundation,如何显示字幕?

cocoa - 我应该使用哪种委托(delegate)方法来响应 NSTextField 上的点击?

python - 使用 py2exe 编译时 passlib.hash import sha256_crypt 给出错误