-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkey_simple.go
51 lines (42 loc) · 1.21 KB
/
key_simple.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
50
51
package cryptography
import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
)
// SimpleLength defines the length of the key in bytes.
type SimpleLength int
// Predefined key lengths for convenience.
const (
Simple16 SimpleLength = 16 // 128-bit key
Simple24 SimpleLength = 24 // 192-bit key
Simple32 SimpleLength = 32 // 256-bit key
)
// SimpleKey represents a cryptographic key as a byte slice.
type SimpleKey []byte
// NewSimpleKey generates a new random key of the specified length.
// Returns an error if the random number generation fails.
func NewSimpleKey(length SimpleLength) (SimpleKey, error) {
key := make(SimpleKey, length)
if _, err := rand.Read(key); err != nil {
return nil, err
}
return key, nil
}
// Bytes returns the key as a byte slice.
func (k SimpleKey) Bytes() []byte {
return k
}
// Hex returns the key as a hexadecimal string.
func (k SimpleKey) Hex() string {
return hex.EncodeToString(k)
}
// Base64 returns the key as a Base64-encoded string.
func (k SimpleKey) Base64() string {
return base64.StdEncoding.EncodeToString(k)
}
// String implements the fmt.Stringer interface.
// By default, it returns the key as a hexadecimal string.
func (k SimpleKey) String() string {
return k.Hex()
}