-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdbcrypt.go
More file actions
153 lines (129 loc) · 3.83 KB
/
dbcrypt.go
File metadata and controls
153 lines (129 loc) · 3.83 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
// SPDX-FileCopyrightText: 2024 Greenbone AG <https://greenbone.net>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
package dbcrypt
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"reflect"
"sync/atomic"
"github.com/rs/zerolog/log"
"github.com/greenbone/opensight-golang-libraries/pkg/dbcrypt/config"
)
const (
prefix = "ENC:"
prefixLen = len(prefix)
)
type DBCrypt[T any] struct {
config atomic.Pointer[config.CryptoConfig]
}
// New creates a new instance of DBCrypt that will perform cryptographic operations based on the provided CryptoConfig.
func New[T any](config config.CryptoConfig) *DBCrypt[T] {
d := &DBCrypt[T]{}
d.config.Store(&config)
return d
}
func (d *DBCrypt[T]) loadKey() []byte {
configPtr := d.config.Load()
if configPtr == nil {
conf, err := config.Read()
if err != nil {
log.Fatal().Err(err).Msg("crypto config is invalid")
}
d.config.CompareAndSwap(nil, &conf)
configPtr = d.config.Load()
}
// TODO: Use proper KDF instead of truncating the password (to maintain backward compatibility use encrypted values prefixes to determine the method)
key := []byte(configPtr.ReportEncryptionV1Password + configPtr.ReportEncryptionV1Salt)[:32] // Truncate key to 32 bytes
return key
}
// EncryptStruct encrypts all fields of a struct that are tagged with `encrypt:"true"`
func (d *DBCrypt[T]) EncryptStruct(data *T) error {
key := d.loadKey()
value := reflect.ValueOf(data).Elem()
valueType := value.Type()
for i := 0; i < value.NumField(); i++ {
field := value.Field(i)
fieldType := valueType.Field(i)
if encrypt, ok := fieldType.Tag.Lookup("encrypt"); ok && encrypt == "true" {
plaintext := fmt.Sprintf("%v", field.Interface())
if len(plaintext) > prefixLen && plaintext[:prefixLen] == prefix {
// already encrypted goto next field
continue
}
ciphertext, err := Encrypt(plaintext, key)
if err != nil {
return err
}
field.SetString(ciphertext)
}
}
return nil
}
// DecryptStruct decrypts all fields of a struct that are tagged with `encrypt:"true"`
func (d *DBCrypt[T]) DecryptStruct(data *T) error {
key := d.loadKey()
value := reflect.ValueOf(data).Elem()
valueType := value.Type()
for i := 0; i < value.NumField(); i++ {
field := value.Field(i)
fieldType := valueType.Field(i)
if encrypt, ok := fieldType.Tag.Lookup("encrypt"); ok && encrypt == "true" {
plaintext, err := Decrypt(field.String(), key)
if err != nil {
return err
}
field.SetString(plaintext)
}
}
return nil
}
func Encrypt(plaintext string, key []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
iv := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
ciphertext := gcm.Seal(nil, iv, []byte(plaintext), nil)
encoded := hex.EncodeToString(append(iv, ciphertext...))
return prefix + encoded, nil
}
func Decrypt(encrypted string, key []byte) (string, error) {
if len(encrypted) <= prefixLen || encrypted[:prefixLen] != prefix {
return "", fmt.Errorf("invalid encrypted value format")
}
encodedCiphertext := encrypted[4:]
ciphertext, err := hex.DecodeString(encodedCiphertext)
if err != nil {
return "", fmt.Errorf("error decoding ciphertext: %w", err)
}
if len(ciphertext) < aes.BlockSize+1 {
return "", fmt.Errorf("ciphertext too short")
}
block, err := aes.NewCipher(key)
if err != nil {
return "", fmt.Errorf("error creating AES cipher: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
iv := ciphertext[:gcm.NonceSize()]
ciphertext = ciphertext[gcm.NonceSize():]
plaintext, err := gcm.Open(nil, iv, ciphertext, nil)
if err != nil {
return "", fmt.Errorf("error decrypting ciphertext: %w", err)
}
return string(plaintext), nil
}