...
1 package crypto
2
3 import (
4 "bytes"
5 "encoding/gob"
6 "encoding/hex"
7
8 "edge-infra.dev/pkg/lib/crypto/encodings"
9 )
10
11 type Secret struct {
12 Principal string
13 Iterations int
14 Salt string
15 Hash string
16 Function string
17 HashType string
18 Generation int
19 Rotation bool
20 }
21
22 func NewSecret(hash, salt []byte, principal, function, hashType string, iterations, generation int, rotation bool) *Secret {
23 return &Secret{
24 Principal: principal,
25 Iterations: iterations,
26 Function: function,
27 HashType: hashType,
28 Generation: generation,
29 Hash: hex.EncodeToString(hash),
30 Salt: hex.EncodeToString(salt),
31 Rotation: rotation,
32 }
33 }
34
35 func NewSecretFromString(secret string) (Secret, error) {
36 secretString, err := encodings.Base64Decode(secret)
37 if err != nil {
38 return Secret{}, err
39 }
40 return deserializeSecret(secretString)
41 }
42
43 func (secret *Secret) SerializeAndBase64Encode() (string, error) {
44 secretBytes, err := serializeSecret(*secret)
45 if err != nil {
46 return "", err
47 }
48 return encodings.Base64Encode(string(secretBytes)), nil
49 }
50
51 func (secret *Secret) DecodedHash() ([]byte, error) {
52 return hex.DecodeString(secret.Hash)
53 }
54
55 func (secret *Secret) DecodedSalt() ([]byte, error) {
56 return hex.DecodeString(secret.Salt)
57 }
58
59 func deserializeSecret(secret string) (Secret, error) {
60 decodedSecret := Secret{}
61 decode := gob.NewDecoder(bytes.NewBuffer([]byte(secret)))
62 if err := decode.Decode(&decodedSecret); err != nil {
63 return decodedSecret, err
64 }
65 return decodedSecret, nil
66 }
67
68 func serializeSecret(secret Secret) ([]byte, error) {
69 var data bytes.Buffer
70 encoder := gob.NewEncoder(&data)
71 if err := encoder.Encode(secret); err != nil {
72 return data.Bytes(), err
73 }
74 return data.Bytes(), nil
75 }
76
View as plain text