diff options
-rw-r--r-- | pkg/ext/auth.go | 26 |
1 files 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 } |