changeset 317:5cb18bedb3a9

Simplified internal password generator.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Thu, 02 Aug 2018 10:18:25 +0200
parents 423d0f1d8ee0
children 1a2dfd9351e9
files controllers/pwreset.go
diffstat 1 files changed, 17 insertions(+), 24 deletions(-) [+]
line wrap: on
line diff
--- a/controllers/pwreset.go	Thu Aug 02 10:04:54 2018 +0200
+++ b/controllers/pwreset.go	Thu Aug 02 10:18:25 2018 +0200
@@ -2,6 +2,7 @@
 
 import (
 	"bytes"
+	"crypto/rand"
 	"database/sql"
 	"encoding/hex"
 	"log"
@@ -197,32 +198,24 @@
 	return hex.EncodeToString(auth.GenerateRandomKey(hashLength))
 }
 
-const (
-	base62alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
-	special        = ",.!;"
-)
+func randomString(n int) string {
 
-var (
-	zero  = big.NewInt(0)
-	div62 = big.NewInt(62)
-)
+	const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
+		"abcdefghijklmnopqrstuvwxyz" +
+		"0123456789" +
+		"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
 
-func encodeToString(src []byte, max int) string {
-	v := new(big.Int)
-	v.SetBytes(src[1:])
-	m := new(big.Int)
-	z := new(big.Int)
-	out := make([]byte, 0, max)
-	for {
-		z.DivMod(v, div62, m)
-		// reverse order but it doesnt matter.
-		out = append(out, base62alphabet[m.Int64()])
-		if len(out) == max-1 || z.Cmp(zero) == 0 {
-			break
+	max := big.NewInt(int64(len(alphabet)))
+	out := make([]byte, n)
+
+	for i := range out {
+		v, err := rand.Int(rand.Reader, max)
+		if err != nil {
+			log.Panicf("error: %v\n", err)
 		}
-		v, z = z, v
+		out[i] = alphabet[v.Int64()]
 	}
-	out = append(out, special[int(src[0])%len(special)])
+
 	return string(out)
 }
 
@@ -233,8 +226,8 @@
 		return strings.TrimSpace(string(out))
 	}
 
-	// Use internal base62 encoder.
-	return encodeToString(auth.GenerateRandomKey(20), 20)
+	// Use internal generator.
+	return randomString(20)
 
 }