go-crypt/crypt/chachapoly/chachapoly.go
Snider 62482c7dc9
Some checks failed
Security Scan / security (pull_request) Failing after 9s
Test / test (pull_request) Failing after 8m29s
refactor: migrate imports to dappco.re/go/core/* paths
Update module path from forge.lthn.ai/core/go-crypt to
dappco.re/go/core/crypt. Migrate go-log, go-io, go-i18n imports to
their new dappco.re/go/core/* paths with updated versions (core v0.5.0,
log v0.1.0, io v0.2.0, i18n v0.2.0). Un-migrated modules (cli,
go-store, go-inference) remain at forge.lthn.ai paths.

Also fixes merge conflict marker and duplicate imports in
crypt/openpgp/service.go, and updates CLAUDE.md to reflect new paths.

Co-Authored-By: Virgil <virgil@lethean.io>
2026-03-22 01:43:27 +00:00

52 lines
1.2 KiB
Go

package chachapoly
import (
"crypto/rand"
"fmt"
"io"
coreerr "dappco.re/go/core/log"
"golang.org/x/crypto/chacha20poly1305"
)
// Encrypt encrypts data using ChaCha20-Poly1305.
func Encrypt(plaintext []byte, key []byte) ([]byte, error) {
aead, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, err
}
nonce := make([]byte, aead.NonceSize(), aead.NonceSize()+len(plaintext)+aead.Overhead())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return aead.Seal(nonce, nonce, plaintext, nil), nil
}
// Decrypt decrypts data using ChaCha20-Poly1305.
func Decrypt(ciphertext []byte, key []byte) ([]byte, error) {
aead, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, err
}
minLen := aead.NonceSize() + aead.Overhead()
if len(ciphertext) < minLen {
return nil, coreerr.E("chachapoly.Decrypt", fmt.Sprintf("ciphertext too short: got %d bytes, need at least %d bytes", len(ciphertext), minLen), nil)
}
nonce, ciphertext := ciphertext[:aead.NonceSize()], ciphertext[aead.NonceSize():]
decrypted, err := aead.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
if len(decrypted) == 0 {
return []byte{}, nil
}
return decrypted, nil
}