lens @ 9ba05d26ee2382f3191e25ae7af5d462ba2a35e4

 1package ext
 2
 3import (
 4	"bytes"
 5	"crypto/aes"
 6	"crypto/cipher"
 7	"crypto/rand"
 8	"encoding/gob"
 9	"fmt"
10	"io"
11)
12
13type Token struct {
14	UserID   uint
15	Username string
16}
17
18var nonce []byte
19
20func init() {
21	nonce = make([]byte, 12)
22	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
23		fmt.Println("Erro while generating nonce " + err.Error())
24		panic(1)
25	}
26}
27
28func ReadToken(data []byte, key []byte) (*Token, error) {
29	block, err := aes.NewCipher(key)
30	if err != nil {
31		return nil, err
32	}
33
34	aesgcm, err := cipher.NewGCM(block)
35	if err != nil {
36		panic(err.Error())
37	}
38
39	plaintext, err := aesgcm.Open(nil, nonce, data, nil)
40	if err != nil {
41		return nil, err
42	}
43
44	r := bytes.NewReader(plaintext)
45	var token Token
46	dec := gob.NewDecoder(r)
47	if err = dec.Decode(&token); err != nil {
48		return nil, err
49	}
50	return &token, nil
51}
52
53func WriteToken(token *Token, key []byte) ([]byte, error) {
54	block, err := aes.NewCipher(key)
55	if err != nil {
56		return nil, err
57	}
58
59	aesgcm, err := cipher.NewGCM(block)
60	if err != nil {
61		return nil, err
62	}
63
64	var buffer bytes.Buffer
65	enc := gob.NewEncoder(&buffer)
66	if err := enc.Encode(token); err != nil {
67		return nil, err
68	}
69
70	ciphertext := aesgcm.Seal(nil, nonce, buffer.Bytes(), nil)
71	return ciphertext, nil
72}