Last active
August 31, 2022 19:47
-
-
Save subreme/d0702c028160a342c530d50f99c2d6e9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // This minified mess, although satisfyingly concise, is an unreadable mess so | |
| // let's beautify it in order to unwrap its contents. | |
| x="";for(i=0;i<128;i++){x+=String.fromCharCode(32+~~(window.crypto.getRandomValues(new Uint32Array(1))[0]/2**32*95))};console.log(x) | |
| // The lines from here on will be a piece-by-piece unpacking of the code above. | |
| // The empty string that will become the "password". | |
| let x = ""; | |
| // Since this loop will repeat 128 times, appending 1 character per iteration, | |
| // that will be the length of the final string. | |
| for (let i = 0; i < 128; i++) { | |
| // The added characters will be obtained by converting somewhat random | |
| // integers to their corresponding UTF-16 character. | |
| x += String.fromCharCode( | |
| // The range of these characters starts at 32, which is the character | |
| // for ' ' (the "space" sign). The double NOT bitwise operator '~~' | |
| // truncates the decimal value of floating point number, converting it | |
| // to an integer. | |
| 32 + ~~( | |
| // While `Math.random()` is not cryptographically secure, the method | |
| // below fills an empty `Uint32Array` with 32 bit integers generated | |
| // in a less predictable way. | |
| window.crypto.getRandomValues(new Uint32Array(1)) | |
| // By indexing the first (and only) element of the array, a decently | |
| // random integer between 0 and 2^32-1 is obtained. Dividing it by | |
| // 2^32 and multiplying by 95 returns a value which, summed with 32, | |
| // will be a pseudo-random float between 32 and 127 (exclusive). | |
| [0] / 2**32 * 95 | |
| ) | |
| // As a result, one of the characters on the line below will be added to | |
| // the string (with the extra indent being intentional due to the | |
| // inclusion of the "space character" ' '): | |
| // !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ | |
| ); | |
| }; | |
| // Finally, the output is printed. | |
| console.log(x); | |
| // Both the code itself and the excessive explanations were undoubtedly | |
| // unnecessary as there's no point in "reinventing the wheel", but I thought it | |
| // would be pretty cool to show how brief a "secure password generator", albeit | |
| // rudimental, could be while also showcasing some weird JavaScript quirks. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment