add token framing, crypto and errors
This commit is contained in:
parent
71483982ca
commit
a6aad1a1d6
5 changed files with 448 additions and 0 deletions
56
crypto.go
Normal file
56
crypto.go
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
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
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue