Debian Codegraph @

pkg/op/crypto.go

raw
1 package op
2
3 import (
4 "errors"
5 "fmt"
6
7 "github.com/go-jose/go-jose/v4"
8 "github.com/zitadel/oidc/v3/pkg/crypto"
9 )
10
11 type Encrypter interface {
12 Encrypt(string) (string, error)
13 }
14 type Decrypter interface {
15 Decrypt(string) (string, error)
16 }
17
18 type Crypto interface {
19 Encrypt(string) (string, error)
20 Decrypt(string) (string, error)
21 }
22
23 type aesCrypto struct {
24 key string
25 }
26
27 func NewAESCrypto(key [32]byte) Crypto {
28 return &aesCrypto{key: string(key[:32])}
29 }
30
31 func (c *aesCrypto) Encrypt(s string) (string, error) {
32 return crypto.EncryptAES(s, c.key)
33 }
34
35 func (c *aesCrypto) Decrypt(s string) (string, error) {
36 return crypto.DecryptAES(s, c.key)
37 }
38
39 type aes256GCMCrypto struct {
40 key []byte
41 keyId string
42 }
43
44 func NewAES256GCMCrypto(key [32]byte, keyId string) Crypto {
45 return &aes256GCMCrypto{
46 key: key[:],
47 keyId: keyId,
48 }
49 }
50
51 func (c *aes256GCMCrypto) Encrypt(s string) (string, error) {
52 encrypter, err := jose.NewEncrypter(jose.A256GCM, jose.Recipient{
53 Algorithm: jose.A256GCMKW,
54 Key: c.key,
55 KeyID: c.keyId,
56 }, nil)
57 if err != nil {
58 return "", fmt.Errorf("failed to create encrypter: %v", err)
59 }
60
61 encrypted, err := encrypter.Encrypt([]byte(s))
62 if err != nil {
63 return "", fmt.Errorf("failed to encrypt: %v", err)
64 }
65
66 serialized, err := encrypted.CompactSerialize()
67 if err != nil {
68 return "", fmt.Errorf("failed to serialize encrypted value: %v", err)
69 }
70
71 return serialized, nil
72 }
73
74 func (c *aes256GCMCrypto) Decrypt(s string) (string, error) {
75 jwe, err := jose.ParseEncrypted(s, []jose.KeyAlgorithm{jose.A256GCMKW}, []jose.ContentEncryption{jose.A256GCM})
76 if err != nil {
77 return "", fmt.Errorf("failed to create jwe: %v", err)
78 }
79 decrypted, err := jwe.Decrypt(c.key)
80 if err != nil {
81 return "", fmt.Errorf("failed to decrypt value: %v", err)
82 }
83 return string(decrypted), nil
84 }
85
86 type CompositeCrypto struct {
87 encrypter Encrypter
88 // decrypters is a list so that older encrypted values can stil be decrypted.
89 decrypters []Decrypter
90 }
91
92 func NewCompositeCrypto(encrypter Encrypter, decrypters []Decrypter) Crypto {
93 return &CompositeCrypto{
94 encrypter: encrypter,
95 decrypters: decrypters,
96 }
97 }
98
99 func (cc CompositeCrypto) Encrypt(s string) (string, error) {
100 return cc.encrypter.Encrypt(s)
101 }
102
103 func (cc CompositeCrypto) Decrypt(s string) (string, error) {
104 for _, d := range cc.decrypters {
105 decrypted, err := d.Decrypt(s)
106 if err != nil {
107 continue
108 }
109 return decrypted, nil
110 }
111 return "", errors.New("failed to decrypt value")
112 }