Improve MongoDB compatibility and connection diagnostics; unify asset dialogs and sidebar navigation; support visible multi-account target links and mapped connection tests. Include regression tests and validation documentation.
50 lines
1.2 KiB
Go
50 lines
1.2 KiB
Go
package security
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"errors"
|
|
"io"
|
|
)
|
|
|
|
type Vault struct{ aead cipher.AEAD }
|
|
|
|
func NewVault(key string) (*Vault, error) {
|
|
b, err := base64.StdEncoding.DecodeString(key)
|
|
if err != nil || len(b) != 32 {
|
|
return nil, errors.New("invalid master key: expected base64 encoding of 32 random bytes")
|
|
}
|
|
block, err := aes.NewCipher(b)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
aead, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Vault{aead}, nil
|
|
}
|
|
func (v *Vault) Seal(data []byte, purpose string) ([]byte, error) {
|
|
nonce := make([]byte, v.aead.NonceSize())
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return nil, err
|
|
}
|
|
return v.aead.Seal(nonce, nonce, data, []byte(purpose)), nil
|
|
}
|
|
func (v *Vault) Open(data []byte, purpose string) ([]byte, error) {
|
|
n := v.aead.NonceSize()
|
|
if len(data) < n {
|
|
return nil, errors.New("invalid encrypted data")
|
|
}
|
|
return v.aead.Open(nil, data[:n], data[n:], []byte(purpose))
|
|
}
|
|
func Token() string {
|
|
b := make([]byte, 32)
|
|
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
|
panic(err)
|
|
}
|
|
return base64.RawURLEncoding.EncodeToString(b)
|
|
}
|