73 lines
1.5 KiB
Go
73 lines
1.5 KiB
Go
// ©AngelaMos | 2026
|
|
// crypto.go
|
|
|
|
package notifications
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"io"
|
|
)
|
|
|
|
type Encryptor struct {
|
|
key []byte
|
|
}
|
|
|
|
func NewEncryptor(b64Key string) (*Encryptor, error) {
|
|
key, err := base64.StdEncoding.DecodeString(b64Key)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("decode encryption key: %w", err)
|
|
}
|
|
if len(key) != 32 {
|
|
return nil, fmt.Errorf(
|
|
"encryption key must be 32 bytes, got %d",
|
|
len(key),
|
|
)
|
|
}
|
|
return &Encryptor{key: key}, nil
|
|
}
|
|
|
|
func (e *Encryptor) Encrypt(
|
|
plaintext []byte,
|
|
) (ciphertext, nonce []byte, err error) {
|
|
block, err := aes.NewCipher(e.key)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("create cipher: %w", err)
|
|
}
|
|
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("create GCM: %w", err)
|
|
}
|
|
|
|
nonce = make([]byte, gcm.NonceSize())
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return nil, nil, fmt.Errorf("generate nonce: %w", err)
|
|
}
|
|
|
|
ciphertext = gcm.Seal(nil, nonce, plaintext, nil)
|
|
return ciphertext, nonce, nil
|
|
}
|
|
|
|
func (e *Encryptor) Decrypt(ciphertext, nonce []byte) ([]byte, error) {
|
|
block, err := aes.NewCipher(e.key)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create cipher: %w", err)
|
|
}
|
|
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create GCM: %w", err)
|
|
}
|
|
|
|
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("decrypt: %w", err)
|
|
}
|
|
|
|
return plaintext, nil
|
|
}
|