解密后0 KB输出文件

时间:2017-08-26 12:52:49

标签: batch-file gnupg pgp

我可以手动使用GNUPG或Kleopatra(gpg4win)解密文件,但是当我通过批处理运行时,我得到0 KB输出,任何原因?下面是我的代码;

@echo off
set LOGFILE=Log.log
call :LOG > %LOGFILE%
exit
:LOG

for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set "dt=%%a"
set "YYYY=%dt:~0,4%"
set "MM=%dt:~4,2%"
set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%"
set "Min=%dt:~10,2%"
set "Sec=%dt:~12,2%"
set "secret=mypassword"

set datestamp=%YYYY%%MM%%DD%

set origPath=D:\Encrypted\
set origFile=my_test_file
set origExt=.PGP
set origCompleteFile=%origPath%%origFile%%datestamp%%origExt%

set destPath=D:\Encrypted\
set destFile=my_test_file_ddmmyyyy
set destExt=.csv
set destCompleteFile=%destPath%%destFile%%YYYY%-%MM%-%DD%%destExt%

set ctaFolder=N:\Test\

echo Decrypt file : "%origCompleteFile%"
echo Save decrypted file in : "%destCompleteFile%"

rem decrypt CTA File
gpg --batch --passphrase "%secret%" --decrypt "%origCompleteFile%" > "%destCompleteFile%"

rem copy to CTA folder in .54
xcopy /s/y "%destCompleteFile%" "%ctaFolder%"

1 个答案:

答案 0 :(得分:0)

无法将二进制数据重定向到文件中。 Windows命令行界面专为文本数据而设计,不适用于二进制数据。此外,:LOG stdout 下面的命令输出的所有内容都会被批处理文件重定向到文件Log.log

GPG manual解释了此控制台应用程序的所有可用命令行选项。

选项--decrypt解释说,解密数据是为了处理 stdout 或在选项--output之后指定的文件而编写的。

因此解决方案只是使用选项--output而不是将 stdout 重定向到文件。

gpg --batch --passphrase "%secret%" --output "%destCompleteFile%" --decrypt "%origCompleteFile%"

可以针对此代码优化整个批处理代码:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "secret=mypassword"

rem Get current date in format YYYYMMDD for usage in file name (DDMMYYYY commented out).
for /F "tokens=2 delims==." %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS GET LocalDateTime /VALUE') do set "LocalDateTime=%%I"
rem set "FileNameDate=%LocalDateTime:~6,2%%LocalDateTime:~4,2%%LocalDateTime:~0,4%"
set "FileNameDate=%LocalDateTime:~0,8%"

set "origPath=D:\Encrypted\"
set "origFile=my_test_file_"
set "origExt=.csv.gpg"
set "origCompleteFile=%origPath%%origFile%%FileNameDate%%origExt%"

set "destPath=D:\Encrypted\"
set "destFile=my_test_file_"
set "destExt=.csv"
set "destCompleteFile=%destPath%%destFile%%FileNameDate%%destExt%"

set "ctaFolder=N:\Test\"

echo Decrypt file: "%origCompleteFile%"
echo Save decrypted file in: "%destCompleteFile%"

rem Decrypt CTA file
gpg --batch --passphrase "%secret%" --output "%destCompleteFile%" --decrypt "%origCompleteFile%"

rem Copy to CTA folder in .54
%SystemRoot%\System32\xcopy.exe "%destCompleteFile%" "%ctaFolder%" /Q /Y >nul
endlocal

当然可以直接在环境变量ctaFolder定义的文件夹中生成解密文件。