secure key generation
parent
cc6652c8a0
commit
eb01267643
24
auth.go
24
auth.go
|
@ -1,8 +1,8 @@
|
||||||
package filemanager
|
package filemanager
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/rand"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"math/rand"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
@ -147,15 +147,17 @@ func checkPasswordHash(password, hash string) bool {
|
||||||
return err == nil
|
return err == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
// generateRandomBytes returns securely generated random bytes.
|
||||||
|
// It will return an error if the system's secure random
|
||||||
// randomString creates a string with a defined length using the above charset.
|
// number generator fails to function correctly, in which
|
||||||
func randomString(length int) string {
|
// case the caller should not continue.
|
||||||
seededRand := rand.New(rand.NewSource(time.Now().UnixNano()))
|
func generateRandomBytes(n int) ([]byte, error) {
|
||||||
|
b := make([]byte, n)
|
||||||
b := make([]byte, length)
|
_, err := rand.Read(b)
|
||||||
for i := range b {
|
// Note that err == nil only if we read len(b) bytes.
|
||||||
b[i] = charset[seededRand.Intn(len(charset))]
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
return string(b)
|
|
||||||
|
return b, nil
|
||||||
}
|
}
|
||||||
|
|
|
@ -163,7 +163,13 @@ func New(database string, base User) (*FileManager, error) {
|
||||||
// If it doesn't exist, create a new one of 256 bits.
|
// If it doesn't exist, create a new one of 256 bits.
|
||||||
err = db.Get("config", "key", &m.key)
|
err = db.Get("config", "key", &m.key)
|
||||||
if err != nil && err == storm.ErrNotFound {
|
if err != nil && err == storm.ErrNotFound {
|
||||||
m.key = []byte(randomString(64))
|
var bytes []byte
|
||||||
|
bytes, err = generateRandomBytes(64)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
m.key = bytes
|
||||||
err = db.Set("config", "key", m.key)
|
err = db.Set("config", "key", m.key)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue