beef up password generation

This commit is contained in:
Your Name 2023-10-07 09:22:30 -04:00
parent 8ba92bd5b6
commit a5f752f450
3 changed files with 83 additions and 13 deletions

View File

@ -2,8 +2,6 @@ package scsusers
import ( import (
"bytes" "bytes"
"crypto/rand"
"encoding/base32"
"fmt" "fmt"
"log" "log"
"net/smtp" "net/smtp"
@ -16,7 +14,7 @@ func RecoverByEmail(email string) {
if !ok { if !ok {
return return
} }
recoverycode := randBytes(16) recoverycode := generatePassword(16)
u.Delete("recoverykey") u.Delete("recoverykey")
u.Delete("recoverytime") u.Delete("recoverytime")
@ -26,15 +24,6 @@ func RecoverByEmail(email string) {
SendRecoveryEmail(email, email, string(recoverycode)) SendRecoveryEmail(email, email, string(recoverycode))
} }
func randBytes(n int) []byte {
randomBytes := make([]byte, 32)
_, err := rand.Read(randomBytes)
if err != nil {
panic(err)
}
return []byte(base32.StdEncoding.EncodeToString(randomBytes)[:n])
}
func SendRegistrationEmail(recipient, username, password string) bool { func SendRegistrationEmail(recipient, username, password string) bool {
data := struct { data := struct {
SiteName string SiteName string

View File

@ -84,7 +84,7 @@ func Register(username, email, ip string) bool {
} }
username = strings.ToLower(username) username = strings.ToLower(username)
pass := randBytes(16) pass := generatePassword(16)
crypt, err := bcrypt.GenerateFromPassword(pass, 10) crypt, err := bcrypt.GenerateFromPassword(pass, 10)
if err != nil { if err != nil {
log.Printf("scsusers.Register: Bcrypt GenerateFromPassword failed? Pass is %s and error is %s\n", pass, err.Error()) log.Printf("scsusers.Register: Bcrypt GenerateFromPassword failed? Pass is %s and error is %s\n", pass, err.Error())

81
password.go Normal file
View File

@ -0,0 +1,81 @@
package scsusers
import (
"crypto/rand"
"encoding/base32"
"unicode"
)
func flipCoin() bool {
x := make([]byte, 1)
_, err := rand.Read(x)
if err != nil {
return true
}
if uint8(x[0]) % 2==0 {
return true
}
return false
}
func scrambleCase(in []byte) []byte {
var out []byte
for _, x := range string(in) {
if unicode.IsUpper(x) {
if flipCoin() {
out = append(out, byte(x))
} else {
out = append(out, byte(unicode.ToLower(x)))
}
}
}
return out
}
func randBytes(n int) []byte {
randomBytes := make([]byte, 32)
_, err := rand.Read(randomBytes)
if err != nil {
panic(err)
}
return []byte(base32.StdEncoding.EncodeToString(randomBytes)[:n])
}
func generatePassword(n int) []byte {
for {
p := scrambleCase(randBytes(16))
if hasDigit(p) && hasUppercase(p) && hasLowercase(p) {
return p
}
}
}
func hasDigit(in []byte) bool {
for _,x := range string(in) {
if unicode.IsDigit(x) {
return true
}
}
return false
}
func hasUppercase(in []byte) bool {
for _,x:= range string(in) {
if unicode.IsUpper(x) {
return true
}
}
return false
}
func hasLowercase(in []byte) bool {
for _,x := range string(in) {
if unicode.IsLower(x) {
return true
}
}
return false
}