From 7dd8040d6d948d41f4e3cf632e868c640f09dd5b Mon Sep 17 00:00:00 2001 From: Gabriel Arakaki Giovanini Date: Sun, 18 Jun 2023 17:02:21 +0200 Subject: fix: Fix having to login every server reload --- pkg/ext/auth.go | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/pkg/ext/auth.go b/pkg/ext/auth.go index d9fbfba..ed122bb 100644 --- a/pkg/ext/auth.go +++ b/pkg/ext/auth.go @@ -6,7 +6,7 @@ import ( "crypto/cipher" "crypto/rand" "encoding/gob" - "fmt" + "errors" "io" ) @@ -15,16 +15,6 @@ type Token struct { Username string } -var nonce []byte - -func init() { - nonce = make([]byte, 12) - if _, err := io.ReadFull(rand.Reader, nonce); err != nil { - fmt.Println("Erro while generating nonce " + err.Error()) - panic(1) - } -} - func ReadToken(data []byte, key []byte) (*Token, error) { block, err := aes.NewCipher(key) if err != nil { @@ -36,7 +26,13 @@ func ReadToken(data []byte, key []byte) (*Token, error) { panic(err.Error()) } - plaintext, err := aesgcm.Open(nil, nonce, data, nil) + nonceSize := aesgcm.NonceSize() + if len(data) < nonceSize { + return nil, errors.New("nonce size greater than data's size") + } + + nonce, ciphertext := data[:nonceSize], data[nonceSize:] + plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil) if err != nil { return nil, err } @@ -66,7 +62,11 @@ func WriteToken(token *Token, key []byte) ([]byte, error) { if err := enc.Encode(token); err != nil { return nil, err } + nonce := make([]byte, aesgcm.NonceSize()) + if _, err = io.ReadFull(rand.Reader, nonce); err != nil { + return nil, err + } - ciphertext := aesgcm.Seal(nil, nonce, buffer.Bytes(), nil) + ciphertext := aesgcm.Seal(nonce, nonce, buffer.Bytes(), nil) return ciphertext, nil } -- cgit v1.2.3