TheDcoder

A simple random number generator based on "Middle Square" method.

5 posts in this topic

#1 ·  Posted (edited)

Hello! :bye:

After watching a whole day of "Journey into cryptography" at Khan Academy, I have got to know the secrets behind some sneaky things! :P. This is one of em', A PRNG (Pseudo Random Number Generator). Its features (atleast what I believe) are:

  1. Simple, short and crappy.
  2. Great for beginners who are baffled by the mechanics of random number generation in computers!
  3. Support for custom seeds! :P
  4. EIGHT DIGITS OF RANDOMNESS!!! :shocked:
  5. Unlike all other PRNGs, This one is predictable :sorcerer:
  6. 1000 possible PRNs when using @MSEC as the seed.
  7. No option for min or max, the min is 10000000 and the max is 99999999.
  8. The Unlicensed 196px-PD-icon.svg.png.
#cs LICENSE
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>
#ce LICENSE

; #FUNCTION# ====================================================================================================================
; Name ..........: MiddleSquareRandom
; Description ...: Pseudo-random number generator based on the infamous "Middle Sqaure" method.
; Syntax ........: MiddleSquareRandom([$iSeed = @MSEC])
; Parameters ....: $iSeed               - [optional] A seed for generation of the random number. Default is @MSEC.
; Return values .: A pseudorandom 8 digit integer.
; Author ........: John von Neumann
; Modified ......: Damon Harris (TheDcoder) - Conversion into AutoIt and simplification + further crappification.
; Remarks .......: Fun Fact - The output is based on the $iSeed passed, Same $iSeed = Same pseudo-random number.
; Related .......: Random()
; Link ..........: https://en.wikipedia.org/wiki/Middle-square_method
; Example .......: ConsoleWrite(MiddleSquareRandom() & @CRLF)
; ===============================================================================================================================
Func MiddleSquareRandom($iSeed = @MSEC)
    Local Const $TURNS = 8
    Local $sRandomNumber, $sSeed
    For $iTurn = 1 To $TURNS
        $iSeed = $iSeed * 2
        $sSeed = String($iSeed)
        $sRandomNumber &= StringMid($sSeed, Ceiling(StringLen($iSeed) / 2), 1)
    Next
    Return Int($sRandomNumber)
EndFunc

 

Enjoy your numbers, TD ;).

P.S NEVER USE THIS FUNCTION IN A REAL WORLD IMPLEMENTATION OF SOMETHING WHICH USES RANDOM NUMBERS!!! THIS ONE IS VERY UNSUITABLE FOR THAT PURPOSE! READ THE POSTS BELOW FOR MORE INFORMATION.

Edited by TheDcoder
Added P.S
1 person likes this

AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

That is flawed and terribly weak. Your algorithm isn't even midddle square but middle n*256.

Read up this botleg extract from TAOCP about PRNGs: https://vk.com/doc10903696_194276164?hash=1fc65ed563521b76e6&dl=ebca64d98d089930e0

BTW all serious PRNG are predictable in that there is nothing random in their code. This is even a requirement to assess anything about the algorithm. You'd have a fairly hard time to prove its pseudo-randomness usefulness: when you say it produces 8 random digits (here you mean pseudo-...) at each invokation, realize that this is a bold statement you just can't prove anyhow. Assertion #7 is also plain wrong.

#include <Array.au3>

Local $a[100]
For $i = 0 To UBound($a) - 1
    $a[$i] = MiddleSquareRandom($i)
Next
_ArrayDisplay(_Array1DToHistogram($a))

Func MiddleSquareRandom($iSeed = @MSEC)
    Local Const $TURNS = 8
    Local $sRandomNumber, $sSeed
    For $iTurn = 1 To $TURNS
        $iSeed = $iSeed * 2
        $sSeed = String($iSeed)
        $sRandomNumber &= StringMid($sSeed, Ceiling(StringLen($sSeed) / 2), 1)
    Next
    Return Int($sRandomNumber)
EndFunc

 

Edited by jchd
3 people like this

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

Hmm... Yes, you are correct. That code is flawed and is not even middle square method... As I have expected, I am not good at this!

I will try to wrap my brain around this again, so expect a retouch to the code soon...


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites

Please don't take this bad: I aint bashing you personally, just trying to put facts straight. Take the time to read from the link provided, you'll learn a lot!

Coming up with a robust PRNG is very hard and even brilliant professionnals have been bitten by their invention. Analyzing a PRNG for plausible randomness requires a very strong background in number theory and analysis. Proving anything in this area is utterly difficult and subtle. Cryptographically secure PRNGs are few and the exclusive domain of seasonned specialists.

My best advice is too rely only on methods proven correct (so far) by a large community of mathematicians, just like the implementation of Random() that AutoIt offers. I'm not saying that nobody is entitled to experiment new things, but please don't publish raw code as Example, along with bold, unproven or false statements. And submit your homebrew PRNG to a decent series of standard randomness tests before believing/claiming anything.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites
1 minute ago, jchd said:

Please don't take this bad: I aint bashing you personally, just trying to put facts straight.

No worries :D, I always appreciate input no matter how its presented to me :).

3 minutes ago, jchd said:

Take the time to read from the link provided, you'll learn a lot!

Thanks for the link! but I am not really very serious about this implementation of a PRNG :(, I only did this as an exercise...

I know that this PRNG is highly unsuitable for any real world use... and I am not planning to make it a PRNG which can be used in Cryptographic operations!! I know that its VERY HARD :shocked:. I just submitted this piece of code for someone who is looking to get started.

I have decided to add a big red WARNING message near the code :).


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Similar Content

    • JustinZandee
      By JustinZandee
      I need a random string generator which creates 15 letters/numbers.
      How can I make that?
    • Anas
      By Anas
      Hi,
      I've this script (removed unrelated parts) that generate a set of random chars for a password. It gets launched from a network share by Task Scheduler at a specific time for all PC's, then it relaunches itself from the local drive.
       
      Global $LocalToolsDir = @ProgramFilesDir & '\Tools' Start() Func Start() If Not StringInStr(@ScriptFullPath, $LocalToolsDir, 2) Then Exit RunLocaly() Sleep(Random(1, 1800, 1) * 1000) $NewPass = GeneratePass() EndFunc Func GeneratePass() Local $Pass For $i = 1 to 8 $R = Random(0,1.5) If $R > 1 Then $Chr = Random(0,9,1) ElseIf $R < 0.5 Then $Chr = Chr(Random(Asc("A"), Asc("Z"), 1)) Else $Chr = Chr(Random(Asc("a"), Asc("z"), 1)) Endif $Pass &= $Chr Next Return $Pass EndFunc Func RunLocaly() Local $Run = 1, $LocalApp = $LocalToolsDir & '\' & @ScriptName If Not FileExists($LocalApp) Then $Run = FileCopy(@ScriptFullPath, $LocalToolsDir, 1 + 8) If $Run Then Run($LocalApp, $LocalToolsDir) EndFunc  
      The problem is that many PC's ends up with the same password(s).
      e.g. 10 PC's have (abc123) as a Password, and another 10 have this (def456)
      Any idea why?
    • Dequality
      By Dequality
      Got a simple question is it possible to have lets say 10 functions and use the random function to randomly pick one of them? If so could anyone please make a tiny example?
       
      Tyvm in advance 
      -Dequality
    • CarlD
      By CarlD
      I'm a command-line kind of guy, and I write scripts primarily for myself.  Since many websites nowadays require strong passwords, I thought I'd write a simple password generator in AutoIt. I know that AutoIt mavens have written more elaborate pw generators; I offer mine for what it's worth. The compiled script, GenPass.exe, can be downloaded here. See below for Help text and source. Enjoy!
      Updates:
      2017-05-06: Default password changed to variable length of 13-22 characters; argument "1" no longer supported
                            When compiled as GenPW.exe, password is sent directly to the clipboard, no message box unless password generation fails.
      2017-05-05: Correction to bypass password generation if argument is ?|H|h
      2017-05-03: Added special argument 1 to generate a password of variable length (10-18 characters) including two (2) separator characters
      2017-05-02: Added option /S to set a (persistent) randomization seed
      Help:
      GenPass.exe|GenPW.exe -- CLD rev. 2017-05-06
      Generate a strong password and save it to the Windows clipboard
      Note: GenPW.exe has the same functionality as GenPass.exe, but
            sends the generated password directly to the clipboard.
            No message box is displayed (unless password generation fails).
        
      "Strong" means that the password contains random combinations of
      alphnumeric characters, including at least one uppercase letter
      (A-N,P-Z), one lowercase letter (a-k,m-z), and one number (0-9).
      (Generated passwords do not use uppercase O or lowercase l as
      these characters are easily confused with the numbers 0 and 1.)
      The length of the password is up to you (see Usage, below),
      but needless to say, the longer, the stronger.
      By default, GenPass generates a strong password of between 13
      and 22 characters that includes two of the following separator
      characters: $%&()*+,-./:;@[]_. Alternatively, you can supply a
      command-line argument in which any number n from 1 to 9 stands
      for a random sequence of alphanumeric characters of length
      n, and any other character stands for itself. Thus, you can
      include fixed words and other characters, such as separators,
      in the generated password. Spaces in the argument are converted
      to underscores. Here are some examples:
      Usage             Sample output
      -----             -------------
      GenPass           MqU26A*6dS-53r8
      GenPass 9         frdhPYDs9
      GenPass 58        weoXYHKxDI1uQ
      GenPass 5.5       UfA6j.43VBB
      GenPass 3-4-3     0I0-6gq4-njc
      GenPass 5,3.7     I2FSR,tRZ.fjeIsFy
      GenPass 3)5(3     UMf)m8513(CBq
      GenPass 3[haha]3  yLa[haha]P3y
      GenPass Yes way5  Yes_way1BsUh
      Seed Option (/S)
      ----------------
      Adding switch /S to the command-line argument causes GenPass to
      set a seed for the random generation of password characters. A
      bare /S sets a randomized seed which is written to disk in a file
      named GenPass.rnd; this seed is used for all subsequent launches
      of GenPass with the bare /S option. Alternatively, you can specify
      a seed (range -2^31 to 2^31-1) on the command line with /S [seed].
      Here are some examples:
      GenPass /S
      GenPass /S 33.3333
      GenPass 5,5,5 /S
      GenPass 5,5,5 /S 33.3333
      Note that any subsequent launch of GenPass without the /S option
      will cause GenPass.rnd to be deleted.
      Source:
      #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Outfile=GenPass.exe #AutoIt3Wrapper_UseUpx=y #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #cs GENPASS.AU3 -- AutoIt v3 CLD rev.2017-05-05 ------------------ Generate a strong password and save it to the clipboard >> Command GenPass ? for detailed help << ------------------------------------------------------- #ce #include <Clipboard.au3> #include <FileConstants.au3> #include <MsgBoxConstants.au3> #include <StringConstants.au3> AutoItSetOption("WinTitleMatchMode", -4) FileInstall ("d:\path\GenPass.htm", @ScriptDir & "\GenPass.htm", $FC_OVERWRITE) ; Template/Seed Local $sTemp = "" Local $bSeed = False, $fSeed=False If $CmdLine[0] Then $sTemp = $CmdLineRaw If $CmdLine[$CmdLine[0]] = "/s" Then $bSeed = True $sTemp = StringTrimRight($sTemp, 2) $sTemp = StringStripWS($sTemp, $STR_STRIPTRAILING) EndIf If $CmdLine[$CmdLine[0] - 1] = "/s" Then $bSeed = True $fSeed = $CmdLine[$CmdLine[0]] $sTemp = StringTrimRight($sTemp, 3 + StringLen($fSeed)) $sTemp = StringStripWS($sTemp, $STR_STRIPTRAILING) EndIf EndIf If Not $sTemp Then $sTemp = "8" If $sTemp = "1" Then $aSeps = StringSplit("#$%&()*+,-./:;@[]_", "") $sTemp = String(Random(3,6,1)) & $aSeps[Random(1,$aSeps[0],1)] & _ String(Random(2,4,1)) & $aSeps[Random(1,$aSeps[0],1)] & _ String(Random(3,6,1)) EndIf $sFn = @ScriptDir&"\GenPass.rnd" If $bSeed Then If Not $fSeed Then If Not FileExists($sFn) Then $fSeed = Random(-1.999^31,1.999^31,0) $h=FileOpen($sFn,2) If $h > -1 Then FileWrite($h,$fSeed) FileClose($h) Else Exit MsgBox($MB_ICONWARNING, @ScriptName, "Error opening " & $sFn) EndIf Else $h=FileOpen($sFn) If $h > -1 Then $fSeed=FileRead($h) FileClose($h) Else Exit MsgBox($MB_ICONWARNING, @ScriptName, "Error opening " & $sFn) EndIf EndIf EndIf SRandom($fSeed) Else If FileExists($sFn) Then FileDelete($sFn) EndIf ; Show help If StringInStr("?Hh", $sTemp) Then If WinExists("[REGEXPTITLE:GenPass.exe:.*]") Then WinActivate("[REGEXPTITLE:GenPass.exe:.*]") Else ShellExecute(@ScriptDir & "\GenPass.htm") EndIf Exit EndIf ; Main $sTemp = StringReplace($sTemp, " ", "_") $iC = 1 While $iC < 10001 $sPW = GenPW($sTemp) If $sPW Then ClipPut($sPW) If Not StringInStr (@ScriptName, "GenPW") Then _ MsgBox($MB_ICONINFORMATION, @ScriptName, $sPW & _ " saved to clipboard" & @CRLF & @CRLF & _ @ScriptName & " ? shows detailed help") Exit Else $iC += 1 EndIf WEnd Exit MsgBox($MB_ICONWARNING, @ScriptName, "Password generation failed!") ;------------------------------- Func GenPw($sTemplate) Local $aIn = StringSplit($sTemplate,"") Local $sOut = "" Local $sABC = _ "0123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789" Local $aAB = StringSplit($sABC, "") Local $bUC = 0, $bLC = 0, $bNR = 0 For $i = 1 To $aIn[0] If Int($aIn[$i]) Then $iK = $aIn[$i] For $j = 1 To $iK $iR = Random(1, $aAB[0],1) Select Case StringInStr("0123456789", $aAB[$iR]) $bNR = 1 Case StringInStr("ABCDEFGHIJKLMNPQRSTUVWXYZ", _ $aAB[$iR], $STR_CASESENSE) $bUC = 1 Case StringInStr("abcdefghijklmnpqrstuvwxyz", _ $aAB[$iR], $STR_CASESENSE) $bLC = 1 EndSelect $sOut &= $aAB[$iR] Next Else $sOut &= $aIn[$i] EndIf Next If ($bUC And $bLC And $bNR) Then Return $sOut Else Return 0 EndIf EndFunc  
    • triodz
      By triodz
      I want the number in a file to be overwritten with the next number up each time a button is pressed. 
      So it is pressed once, the number '1' is written to the file. It is pressed again and the number '2' overwrites the first number.
      At the moment I get the number 1 written, but can't get it to overwrite. What I have so far:
      #include <ButtonConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #include <FileConstants.au3> #include <MsgBoxConstants.au3> #include <WinAPIFiles.au3> #Region ### START Koda GUI section ### Form=C:\Users\soulf\Desktop\CalcGui\RLCalc.kxf $Form1 = GUICreate("Form1", 615, 437, 426, 141) $One = GUICtrlCreateButton("1", 32, 72, 25, 25) GUICtrlSetBkColor(-1, 0xFF0000) GUISetState(@SW_SHOW) #EndRegion ### END Koda GUI section ### Func First ()     $fPath = "C:\temp\First.txt"     $fOpen = FileOpen ($fPath, 2)     $Counter = FileReadLine ($fpath)     $counter = $counter + 1     $fWrite = filewriteline ($fPath, $counter)     FileClose ($fpath) EndFunc While 1     $nMsg = GUIGetMsg()     Switch $nMsg         Case $GUI_EVENT_CLOSE             Exit         Case $One             Call ("First")     EndSwitch WEnd I tried a Do Until statement, but that just puts the numbers 1 to 5 in the file.
      Any help would be greatly appreciated!