forked from mancabizjak/emmy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.go
46 lines (38 loc) · 1.27 KB
/
session.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package server
import (
"crypto/rand"
"encoding/base64"
"fmt"
)
// Minimal allowed length of the session key, in bytes
// This is to prevent possible mistakes security reasons.
const MIN_SESSION_KEY_BYTE_LEN = 24
type SessionManager struct {
sessionKeyByteLen int
}
func newSessionManager(n int) (*SessionManager, error) {
var err error
if n < MIN_SESSION_KEY_BYTE_LEN {
err = fmt.Errorf("desired length of the session key (%d B) is too short, falling back to %d B",
n, MIN_SESSION_KEY_BYTE_LEN)
n = MIN_SESSION_KEY_BYTE_LEN
}
return &SessionManager{
sessionKeyByteLen: n,
}, err
}
// generateSessionKey produces a secure random n-byte session key and returns its
// base64-encoded representation that is URL-safe.
// It reports an error if n is less than MIN_SESSION_KEY_BYTE_LEN.
func (m *SessionManager) generateSessionKey() (*string, error) {
randBytes := make([]byte, m.sessionKeyByteLen)
// reads m.sessionKeyByteLen random bytes (e.g. len(randBytes)) to randBytes array
_, err := rand.Read(randBytes)
// an error may occur if the system's secure RNG doesn't function properly, in which case
// we can't generate a secure session key
if err != nil {
return nil, err
}
sessionKey := base64.URLEncoding.EncodeToString(randBytes)
return &sessionKey, nil
}