-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.go
49 lines (40 loc) · 918 Bytes
/
generator.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
47
48
49
package krot
import (
"crypto/rand"
"encoding/hex"
)
type KeySize int
const (
KeySize32 KeySize = 4
KeySize64 KeySize = 8
KeySize128 KeySize = 16
KeySize192 KeySize = 24
KeySize256 KeySize = 32
KeySize512 KeySize = 64
)
// KeyGenerator defines the interface for generating keys. It provides a method
// for generating a key.
type KeyGenerator interface {
// Generate creates a new key. If the key cannot be generated, it returns an error.
//
// key, err := generator.Generate()
// if err != nil {
// log.Fatal(err)
// }
Generate() (any, error)
}
type keyGenerator struct {
keySize int
}
func NewKeyGenerator(size KeySize) KeyGenerator {
return &keyGenerator{
keySize: int(size),
}
}
func (g *keyGenerator) Generate() (any, error) {
key := make([]byte, g.keySize)
if _, err := rand.Read(key); err != nil {
return nil, err
}
return hex.EncodeToString(key), nil
}