代码之家  ›  专栏  ›  技术社区  ›  kgerber

将Powershell Securestring传递到7zip,但之后无法解压缩存档

  •  0
  • kgerber  · 技术社区  · 9 年前

    备份我的数据的Powershell脚本从命令行读取密码并将其传递到7zip(7z):

    ....
    $pw = Read-Host -assecurestring -Prompt 'Input Backup Master Passphrase: '
    $pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))
    ....
    & 'C:\Program Files\7-Zip\7z.exe' a -v900M -t7z -mhe=on -mx=9 -p$pw $target/myarchive.7z $src
    

    但当我在7zip(GUI)中打开存档时,它会显示一个密码提示,输入密码后,它显示一个文件(同样是7zip文件),该文件也是加密的,但不会响应密码。

    当我在另一个Powershell脚本中提取文件时,它工作正常。

    # $pw is read again from commandline via Read-Host....&PtrToStringAuto
    & 'C:\Program Files\7-Zip\7z.exe' x -p$pw $target/myarchive.7z
    

    为什么提取只能在CLI上工作,而不能通过GUI工作?

    1 回复  |  直到 9 年前
        1
  •  0
  •   Eris    9 年前

    经过大量实验(为了科学!),我发现7z线路没有按预期工作。在原始代码中 -p$pw 实际上将密码设置为文字 $pw .

    快速&脏方法是使用 Invoke-Expression 相反:

    $inpw = Read-Host -assecurestring -Prompt 'Input Backup Master Passphrase: '
    $zpw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($inpw))
    
    $archive = "myarchive.7z"
    $src = "testfile.txt"
    # using a string formatter to avoid a mess of escaping characters 
    Invoke-Expression ('& "{0}" a -v900M -t7z -mhe=on -mx=9 -p{1} {2} {3}' -f 'C:\Program Files\7-Zip\7z.exe', $zpw, $archive, $src)
    

    然而,这会带来字符串插值和其他安全/数据问题的重新发行。你也可以看看 Start-Process ,或使用.NET Process.Start 方法进行更多控制。