我想“加密”一个文件。这只是为了好玩,不打算使用这种“加密”存储或发送任何感性数据。
此代码示例旨在说明我想要做的事情......
SET A=D
SET B=S
SET C=Q
SET D=G
ECHO %A%%B%%C%%D%
文本ABCD现在将显示为DSQG insted(如果我写了一些有意义的“加密”结果并不意味着什么)。
我的问题是:
我可以(如果是,如何?)在文件中的每个字符前后添加'%'?
我搜索了如何使用批处理读取文件,发现这个(jeb的答案): Batch files: How to read a file?
我是否可以阅读普通文件,加密并存储为加密版本?
非常感谢您的回答!
答案 0 :(得分:2)
这借用了来自jeb的strlen,
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET PT_FILE=plain.txt
IF NOT "%~1"=="" SET "PT_FILE=%~1"
CALL :INIT_CIPHER
FOR /F "tokens=*" %%l IN ('findstr.exe /R /N "^" "%PT_FILE%"') DO @(
REM @ECHO(
REM @ECHO( %%l
SET "LINE=%%~l"
SET "LINE=!LINE:*:=!"
REM @ECHO(!LINE!
CALL :strlen LINE_LEN LINE
REM @ECHO(Length(!LINE_LEN!^)
IF !LINE_LEN! EQU 0 (
ECHO(
) ELSE (
SET OUTLINE_E=
FOR /L %%i IN (0,1,!LINE_LEN!) DO (
SET "CHAR=!LINE:~%%i,1!"
IF "!CHAR!"==" " (
SET "OUTLINE_E=!OUTLINE_E! "
) ELSE (
@ECHO !CHAR!|findstr.exe /R "[A-Za-z]" >NUL
IF ERRORLEVEL 1 (
SET "OUTLINE_E=!OUTLINE_E!!CHAR!"
) ELSE (
SET CHAR_E=
CALL :ENC "!CHAR!" "CHAR_E"
REM @ECHO '!CHAR!' =^> E(!CHAR_E!^)
SET "OUTLINE_E=!OUTLINE_E!!CHAR_E!"
)
)
)
ECHO(!OUTLINE_E!
)
)
GOTO :EOF
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:ENC
CALL SET "%~2=!%~1!"
REM ECHO E(!%~2!^)
EXIT /B
:: https://stackoverflow.com/questions/5837418/how-do-you-get-the-string-length-in-a-batch-file
:strlen <resultVar> <stringVar>
(
setlocal EnableDelayedExpansion
set "s=!%~2!#"
set "len=0"
for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if "!s:~%%P,1!" NEQ "" (
set /a "len+=%%P"
set "s=!s:~%%P!"
)
)
)
(
endlocal
set "%~1=%len%"
exit /b
)
:: Substitution Cipher
:: ABCDEFGHIJKLMNOPQRSTUVWXYZ
:: ZYXWVUTSRQPONMLKJIHGFEDCBA
:: perl -e "@a=('a'..'z');for ($i=0; $i<@a; $i++) { print('SET '.uc($a[$i]).'='.uc($a[$#a-$i]).qq(\n)); }"
:INIT_CIPHER
SET A=Z
SET B=Y
SET C=X
SET D=W
SET E=V
SET F=U
SET G=T
SET H=S
SET I=R
SET J=Q
SET K=P
SET L=O
SET M=N
SET N=M
SET O=L
SET P=K
SET Q=J
SET R=I
SET S=H
SET T=G
SET U=F
SET V=E
SET W=D
SET X=C
SET Y=B
SET Z=A
EXIT /B
注意:
结果:
>>> type plain.txt
This is a simple file to be encrypted.
This is a second line. A blank line follows.
This is the fourth line.
This line has a colon (:) in the middle of it.
This line has quotes: "I said, 'Pass the bread, please,' as politely as possible."
>>> enc plain.txt
GSRH RH Z HRNKOV UROV GL YV VMXIBKGVW.
GSRH RH Z HVXLMW ORMV. Z YOZMP ORMV ULOOLDH.
GSRH RH GSV ULFIGS ORMV.
GSRH ORMV SZH Z XLOLM (:) RM GSV NRWWOV LU RG.
GSRH ORMV SZH JFLGVH: "R HZRW, 'KZHH GSV YIVZW, KOVZHV,' ZH KLORGVOB ZH KLHHRYOV."
>>> enc > cipher.txt
enc > cipher.txt
>>> enc cipher.txt
THIS IS A SIMPLE FILE TO BE ENCRYPTED.
THIS IS A SECOND LINE. A BLANK LINE FOLLOWS.
THIS IS THE FOURTH LINE.
THIS LINE HAS A COLON (:) IN THE MIDDLE OF IT.
THIS LINE HAS QUOTES: "I SAID, 'PASS THE BREAD, PLEASE,' AS POLITELY AS POSSIBLE."