Random-Passwort in Javascript mit sicherer Zufallszahlenfunktion erstellen
Hanno Böck

Hanno Böck commited on 2023-12-17 15:53:18
Zeige 2 geänderte Dateien mit 20 Einfügungen und 10 Löschungen.

... ...
@@ -31,11 +31,16 @@ html_header('
31 31
 <script>
32 32
 
33 33
   function makePasswd() {
34
-    var passwd = \'\';
35
-    var chars = \'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\';
36
-    for (i=0; i<15; i++) {
37
-      var c = Math.floor(Math.random()*chars.length + 1);
38
-      passwd += chars.charAt(c)
34
+    const pwchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
35
+    const limit = 256 - (256 % pwchars.length);
36
+
37
+    let passwd = "";
38
+    let randval;
39
+    for (let i = 0; i < 15; i++) {
40
+      do {
41
+        randval = window.crypto.getRandomValues(new Uint8Array(1))[0];
42
+      } while (randval >= limit);
43
+      passwd += pwchars[randval % pwchars.length];
39 44
     }
40 45
     return passwd;
41 46
   }
... ...
@@ -30,11 +30,16 @@ html_header('
30 30
 <script>
31 31
 
32 32
   function makePasswd() {
33
-    var passwd = \'\';
34
-    var chars = \'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\';
35
-    for (i=0; i<15; i++) {
36
-      var c = Math.floor(Math.random()*chars.length + 1);
37
-      passwd += chars.charAt(c)
33
+    const pwchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
34
+    const limit = 256 - (256 % pwchars.length);
35
+
36
+    let passwd = "";
37
+    let randval;
38
+    for (let i = 0; i < 15; i++) {
39
+      do {
40
+        randval = window.crypto.getRandomValues(new Uint8Array(1))[0];
41
+      } while (randval >= limit);
42
+      passwd += pwchars[randval % pwchars.length];
38 43
     }
39 44
     return passwd;
40 45
   }
41 46