1

我正在努力学习 obj-C 并且可以使用一些帮助。我正在编写一个“命令行工具”来创建加密的 DMG,然后安全地删除包含的文件。当 hdiutil 创建 DMG 时,它会要求提供加密密码,我正在尝试将此密码从 bin/echo 传输到 hdiutil。

DMG 是按预期创建的,但是当我尝试安装它时,密码不被接受。我尝试使用空白密码和末尾的额外空间进行挂载。

当我 NSLog 管道中的值时,它看起来是正确的,但这可能是因为我刚刚读取了前 4 个字符。我猜密码中添加了一些额外的字符,但我不知道为什么和什么。

两个问题 1:如何将“正确”值作为密码从 NSTask passwordCmd 传送到 NSTask backupCmd?

2:我如何 NSLog 与传递给 [backupCmd setStandardInput:pipe] 的管道中的值完全相同

#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;
}

任何帮助深表感谢!

4

2 回答 2

3

我在您的代码中看到两个问题:

1)“hdiutil”文档指出:

-stdinpass
从标准输入中读取以空字符结尾的密码。...请注意,密码将包含 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”是否真的希望在 NULL 字符之后有一个换行符。您也可以在没有换行符的情况下尝试它。)

于 2013-01-06T19:02:51.583 回答
1

您已经从管道中读取了这些字符,这些字符非常“消耗”,下次您读取它们时,您将不再找到它们。

如果删除此行,您应该可以做到:

NSData *output = [[pipe fileHandleForReading] readDataOfLength:4];

使管道中仍有 4 个字符可用。

于 2013-01-06T18:54:04.377 回答