我正在努力学习obj-C,需要一些帮助。我正在写一个“命令行工具”来创建一个加密的DMG,然后安全地删除包含的文件。当hdiutil创建DMG时,它要求提供用于加密的密码,我正在尝试通过管道将该密码从bin/echo传输到hdiutil。
DMG按预期创建,但当我尝试挂载它时,密码不被接受。我尝试使用空密码和末尾额外的空格进行挂载。
当我NSLog管道中的值时,它看起来是正确的,但这可能是因为我只读取了前4个字符。我猜有一些额外的字符添加到密码,但我不知道为什么和什么。
两个问题1:如何通过管道将“正确”值作为密码从NSTask passwordCmd传输到NSTask backupCmd?
2:如何从管道中设置与传递给backupCmd NSLog :backupCmd的值完全相同的值
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSTask *passwordCmd = [NSTask new];
NSTask *backupCmd = [NSTask new];
NSPipe *pipe;
pipe = [NSPipe pipe];
// Enter password by calling echo with a NStask
[passwordCmd setLaunchPath:@"/bin/echo"];
[passwordCmd setStandardOutput:pipe]; // write to pipe
[passwordCmd setArguments: [NSArray arrayWithObjects: @"test", nil]];
[passwordCmd launch];
[passwordCmd waitUntilExit];
// Log the value of the pipe for debugging
NSData *output = [[pipe fileHandleForReading] readDataOfLength:4];
NSString *string = [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding];
NSLog(@"'%@'", string);
// Create a encrypted DMG based on a folder
[backupCmd setLaunchPath:@"/usr/bin/hdiutil"];
[backupCmd setCurrentDirectoryPath:@"/Volumes/Macintosh HD/Users/kalle/Desktop/test/"];
[backupCmd setArguments:[NSArray arrayWithObjects:@"create",@"-format",@"UDZO",@"-srcfolder",@"backup",@"/Volumes/Macintosh HD/Users/kalle/Desktop/backup.dmg",@"-encryption",@"AES-256",@"-stdinpass",@"-quiet",nil]];
[backupCmd setStandardInput:pipe]; // read from pipe
[backupCmd launch];
[backupCmd waitUntilExit];
// Do some more stuff...
}
return 0;
}任何帮助都是非常感谢的!
发布于 2013-01-07 03:02:52
我在你的代码中发现了两个问题:
1) "hdiutil“文档说明:
-stdinpass
从标准输入中读取以null结尾的密码。..。请注意,密码将在NULL之前包含任何换行符。
但是"/bin/echo“总是会在输出中添加一个换行符。因此,您的密码设置为"test\n“。
2)如果您从日志管道读取密码,数据将“消失”,备份任务将不再读取数据。(编辑:这也是我在写这个答案时由Ramy Al Zuhoury发布的!)
我不会使用"/bin/echo“任务将密码传递给备份任务。您最好将必要的数据直接写入管道:
NSString *passwd = @"test\0\n"; // password + NULL character + newline
NSData *passwdData = [passwd dataUsingEncoding:NSUTF8StringEncoding];
[[pipe fileHandleForWriting] writeData:passwdData];
[[pipe fileHandleForWriting] closeFile];(我不确定"hdiutil“是否真的希望在空字符之后有换行符。您也可以不使用换行符进行尝试。)
发布于 2013-01-07 02:54:04
如果删除以下行,您应该能够做到这一点:
NSData *output = [[pipe fileHandleForReading] readDataOfLength:4];使4个字符在管道中仍然可用。
https://stackoverflow.com/questions/14185362
复制相似问题