refactor(crypto): fix linter issues in chacha.go

This commit is contained in:
zarazaex69
2026-04-12 23:23:38 +03:00
parent 4fa4197184
commit 9c1df94413

View File

@@ -3,46 +3,55 @@ package crypto
import (
"crypto/cipher"
"crypto/rand"
"errors"
"fmt"
"golang.org/x/crypto/chacha20poly1305"
)
type Cipher struct {
var (
ErrInvalidKeySize = fmt.Errorf("invalid key size")
ErrCiphertextTooShort = fmt.Errorf("ciphertext too short")
)
type Cipher struct { //nolint:revive
aead cipher.AEAD
}
func NewCipher(keyStr string) (*Cipher, error) {
func NewCipher(keyStr string) (*Cipher, error) { //nolint:revive
key := []byte(keyStr)
if len(key) != chacha20poly1305.KeySize {
return nil, errors.New("invalid key size")
return nil, ErrInvalidKeySize
}
aead, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to create aead: %w", err)
}
return &Cipher{aead: aead}, nil
}
func (c *Cipher) Encrypt(plaintext []byte) ([]byte, error) {
func (c *Cipher) Encrypt(plaintext []byte) ([]byte, error) { //nolint:revive
nonce := make([]byte, c.aead.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return nil, err
return nil, fmt.Errorf("failed to read nonce: %w", err)
}
ciphertext := c.aead.Seal(nonce, nonce, plaintext, nil)
return ciphertext, nil
}
func (c *Cipher) Decrypt(ciphertext []byte) ([]byte, error) {
func (c *Cipher) Decrypt(ciphertext []byte) ([]byte, error) { //nolint:revive
if len(ciphertext) < c.aead.NonceSize() {
return nil, errors.New("ciphertext too short")
return nil, ErrCiphertextTooShort
}
nonce := ciphertext[:c.aead.NonceSize()]
encrypted := ciphertext[c.aead.NonceSize():]
return c.aead.Open(nil, nonce, encrypted, nil)
res, err := c.aead.Open(nil, nonce, encrypted, nil)
if err != nil {
return nil, fmt.Errorf("failed to decrypt: %w", err)
}
return res, nil
}