Skip to content

Instantly share code, notes, and snippets.

@gkmuse
Created August 1, 2012 15:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gkmuse/3227586 to your computer and use it in GitHub Desktop.
Save gkmuse/3227586 to your computer and use it in GitHub Desktop.
Generate Random String of Arbitrary Length with Batch
@echo off
setlocal EnableDelayedExpansion
set char=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
set count=0
set salt=0
echo The maximum RC4 key length is 128 bits.
echo Default KEY length is 16 characters.
:Number
set /p salt=Enter a salt value(Integer):
if !salt! gtr 32752 goto Number
set /a length=15 + !salt!
:Loop
set /a count+=1
set /a rand=%Random%%%61
set buffer=!buffer!!char:~%rand%,1!
if !count! leq !length! goto Loop
echo KEY = !buffer!
set /a length+=1
echo The length of KEY is !length! characters.
echo !buffer! | clip
echo KEY had been saved in clipboard^^!
set /p question=Do you want to save KEY into KEY.txt? [Y/n]
if /i "!question!" == "n" goto EOF
if /i "!question!" == "N" goto EOF
if /i "!question!" == "no" goto EOF
if /i "!question!" == "No" goto EOF
if /i "!question!" == "NO" goto EOF
echo The length of KEY is !length! characters. > KEY.txt
echo KEY=!buffer! >> KEY.txt
:EOF
endlocal
@abdekker
Copy link

abdekker commented Apr 2, 2020

%char% is 62 characters long, so line 20 should probably be "set /a rand=%Random%%%62"

@Darthagnon
Copy link

Briliant Batch script! Thank you so much! I used it to generate registry keys in an installer script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment