Search code examples
windowsbatch-fileencryptionfilenamesbatch-rename

Windows batch scramble/unscramble filenames


I'm looking for a way to scramble/unscramble (encrypt/decrypt) the filenames of every file in a directory via batch script. One .bat file would encrypt the filenames in the current directory, and another would decrypt them.

I have an idea as to how this might work, but lack the batch file skills/experience to make it happen on my own: Have the encryption script find the ASCII value of each character in each filename, increment each character by a certain amount, and then rename each file accordingly. The decryption script would function in a similar but opposite manner. Just an idea - as long as the filename gets fully scrambled and unscrambled, I will be happy.

Any batch file wizards out there willing to lend a hand? Thanks in advance!


Solution

  • Here is a solution that utilizes JREPL.BAT - a regular expression find/replace utility. JREPL is pure script (hybrid JScript/batch) that runs natively on any windows machine from XP onward - no 3rd party exe required.

    I used the simple ROT13 substitution cipher Running the script once encrypts the names. Running a second time restores the names to the original values. I chose to encrypt only the file name, not the extension. It would be easy to modify to encrypt the extension as well.

    encryptNames.bat

    @echo off
    pushd %1 .
    call :sub
    popd
    exit /b
    
    :sub  Subroutine needed to guarantee %-f0 gives the correct value
    setlocal
    set "find=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    set "repl=NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
    set "p=/(.*)/"
    set "prepl={$1}"
    for /f "delims=" %%C in (
      'cmd /c "for %%F in (*) do @if "%%~fF" neq "%~f0" echo ren "%%F" "/%%~nF/%%~xF""^|jrepl find repl /t "" /p p /prepl "{$1}" /v'
    ) do echo %%C&%%C
    

    Calling encryptNames.bat without any argument will encrypt all files in the current directory (except for the encryptNames.bat file itself)

    You can encrypt the names in any folder by passing the folder path as an argument. For example:

    encryptNames c:\my\folder\to\be\encrypted
    

    Note that encryptNames.bat assumes JREPL.BAT is in a folder that is listed within your PATH environment variable. If you put JREPL.BAT in the same folder as encryptNames.bat, and then encrypt the files in that folder, then JREPL.BAT will be encrypted, and you will no longer be able to run encryptNames.bat!