2020-03-23 07:06:44 +01:00
|
|
|
package crypto
|
|
|
|
|
|
|
|
import (
|
2022-03-14 07:55:09 +01:00
|
|
|
"crypto/rand"
|
2020-03-23 07:06:44 +01:00
|
|
|
|
2022-04-27 01:01:45 +02:00
|
|
|
"github.com/zitadel/logging"
|
2020-03-23 07:06:44 +01:00
|
|
|
|
2022-04-27 01:01:45 +02:00
|
|
|
"github.com/zitadel/zitadel/internal/errors"
|
2020-03-23 07:06:44 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type KeyConfig struct {
|
|
|
|
EncryptionKeyID string
|
|
|
|
DecryptionKeyIDs []string
|
|
|
|
}
|
|
|
|
|
|
|
|
type Keys map[string]string
|
|
|
|
|
2022-03-14 07:55:09 +01:00
|
|
|
type Key struct {
|
|
|
|
ID string
|
|
|
|
Value string
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewKey(id string) (*Key, error) {
|
|
|
|
randBytes := make([]byte, 32)
|
|
|
|
if _, err := rand.Read(randBytes); err != nil {
|
|
|
|
return nil, err
|
2020-03-23 07:06:44 +01:00
|
|
|
}
|
2022-03-14 07:55:09 +01:00
|
|
|
return &Key{
|
|
|
|
ID: id,
|
|
|
|
Value: string(randBytes),
|
|
|
|
}, nil
|
2020-03-23 07:06:44 +01:00
|
|
|
}
|
|
|
|
|
2022-03-14 07:55:09 +01:00
|
|
|
func LoadKey(id string, keyStorage KeyStorage) (string, error) {
|
|
|
|
key, err := keyStorage.ReadKey(id)
|
2020-06-17 08:06:40 +02:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2022-03-14 07:55:09 +01:00
|
|
|
return key.Value, nil
|
2020-06-17 08:06:40 +02:00
|
|
|
}
|
|
|
|
|
2022-04-12 16:20:17 +02:00
|
|
|
func LoadKeys(config *KeyConfig, keyStorage KeyStorage) (Keys, []string, error) {
|
2020-03-23 07:06:44 +01:00
|
|
|
if config == nil {
|
|
|
|
return nil, nil, errors.ThrowInvalidArgument(nil, "CRYPT-dJK8s", "config must not be nil")
|
|
|
|
}
|
2022-03-14 07:55:09 +01:00
|
|
|
readKeys, err := keyStorage.ReadKeys()
|
2020-03-23 07:06:44 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
2022-04-12 16:20:17 +02:00
|
|
|
keys := make(Keys)
|
2020-03-23 07:06:44 +01:00
|
|
|
ids := make([]string, 0, len(config.DecryptionKeyIDs)+1)
|
|
|
|
if config.EncryptionKeyID != "" {
|
|
|
|
key, ok := readKeys[config.EncryptionKeyID]
|
|
|
|
if !ok {
|
2022-03-14 07:55:09 +01:00
|
|
|
return nil, nil, errors.ThrowInternalf(nil, "CRYPT-v2Kas", "encryption key %s not found", config.EncryptionKeyID)
|
2020-03-23 07:06:44 +01:00
|
|
|
}
|
|
|
|
keys[config.EncryptionKeyID] = key
|
|
|
|
ids = append(ids, config.EncryptionKeyID)
|
|
|
|
}
|
|
|
|
for _, id := range config.DecryptionKeyIDs {
|
|
|
|
key, ok := readKeys[id]
|
|
|
|
if !ok {
|
2022-03-14 07:55:09 +01:00
|
|
|
logging.Errorf("description key %s not found", id)
|
2020-03-23 07:06:44 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
keys[id] = key
|
|
|
|
ids = append(ids, id)
|
|
|
|
}
|
|
|
|
return keys, ids, nil
|
|
|
|
}
|