package cybersecurity import ( "crypto/rand" "fmt" "io" "golang.org/x/crypto/chacha20poly1305" ) // SealAEAD encrypts plaintext with ChaCha20-Poly1305, returning a random nonce and ciphertext. // key must be exactly 32 bytes. aad (additional authenticated data) may be nil. // The returned nonce must be stored alongside the ciphertext and passed to OpenAEAD. func SealAEAD(key, plaintext, aad []byte) (nonce, ciphertext []byte, err error) { if len(key) != chacha20poly1305.KeySize { return nil, nil, fmt.Errorf("seal_aead: key must be %d bytes, got %d", chacha20poly1305.KeySize, len(key)) } aead, err := chacha20poly1305.New(key) if err != nil { return nil, nil, fmt.Errorf("seal_aead: create cipher: %w", err) } nonce = make([]byte, aead.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { return nil, nil, fmt.Errorf("seal_aead: generate nonce: %w", err) } ciphertext = aead.Seal(nil, nonce, plaintext, aad) return nonce, ciphertext, nil }