ficha/crypto.go
2026-04-29 01:28:05 +00:00

56 lines
1.5 KiB
Go

package ficha
import (
"crypto/rand"
"errors"
"fmt"
"golang.org/x/crypto/chacha20poly1305"
)
const (
keySize = chacha20poly1305.KeySize
nonceSize = chacha20poly1305.NonceSizeX
)
// encrypt seals plaintext under key. aad is authenticated but not encrypted.
// A fresh random nonce is generated per call; with a 24-byte nonce, random generation is collision-safe.
func encrypt(key, plaintext, aad []byte) (nonce, ciphertext []byte, err error) {
if len(key) != keySize {
return nil, nil, fmt.Errorf("ficha: key must be %d bytes, got %d", keySize, len(key))
}
aead, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, nil, fmt.Errorf("ficha: init aead: %w", err)
}
nonce = make([]byte, nonceSize)
if _, err := rand.Read(nonce); err != nil {
return nil, nil, fmt.Errorf("ficha: read random nonce: %w", err)
}
ciphertext = aead.Seal(nil, nonce, plaintext, aad)
return nonce, ciphertext, nil
}
// decrypt verifies and opens ciphertext. Any auth failure returns ErrInvalidToken
func decrypt(key, nonce, ciphertext, aad []byte) ([]byte, error) {
if len(key) != keySize {
return nil, fmt.Errorf("ficha: key must be %d bytes, got %d", keySize, len(key))
}
if len(nonce) != nonceSize {
return nil, errors.New("ficha: invalid nonce size")
}
aead, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, fmt.Errorf("ficha: init aead: %w", err)
}
plaintext, err := aead.Open(nil, nonce, ciphertext, aad)
if err != nil {
return nil, ErrInvalidToken
}
return plaintext, nil
}