Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

windows - How do I get truly random numbers in batch?

Everyone uses random numbers at one point or another. So, I need some truly random numbers (not pseudo-random*) generated from the command prompt, I also want a system that generates letters in a code line the size of: set RANDOM=%random% %%2 +1. And am I just trying to catch a non-existent butterfly? *pseudo-random is random that relies on outside info like time, batch's random generator is pseudo-random based on time, to test this open 2 new notepad .bat and name this file 1.bat
1.bat

start 2.bat
@echo off
cls
echo %random%
pause

2.bat

@echo off
cls
echo %random%
pause

What's happening?!? Well this is pseudo-random, as long as there is NO delay between the opening of the batch files, the batch file's numbers will be the same.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're basically asking for entropy pool, and your platform is Windows, right?

Best bet is to use CryptGenRandom() function, see https://msdn.microsoft.com/en-us/library/windows/desktop/aa379942(v=vs.85).aspx. You could probably call it from Powershell

UPDATE

Apparently, there is a .NET wrapper for crypto, so you could use it from Powershell

[System.Security.Cryptography.RNGCryptoServiceProvider] $rng = New-Object System.Security.Cryptography.RNGCryptoServiceProvider

$rndnum = New-Object byte[] 4
# Generate random sequence of bytes 
$rng.GetBytes($rndnum)

# rndnum is filled with random bits
....

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...