Author: Pedro Lucas Porcellis <porcellis@eletrotupi.com>
keys: use generated fernet key to encrypt and decrypt messages Still needs to implement the decryption method which evaluates the expiration time of the fernet message, but let's deal with that later. By now, we have basically everything we need to deal with cookies/sessions in place, just needs to write a middleware for it.
cmd/server.go | 4 +++- keys/keys.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++
diff --git a/cmd/server.go b/cmd/server.go index 379653d1d022a7fb5c07c37bdf283f1909b3eb6c..851c9bb371249911957bc140cd7b56477117f818 100644 --- a/cmd/server.go +++ b/cmd/server.go @@ -13,6 +13,7 @@ goRedis "github.com/go-redis/redis/v8" "git.eletrotupi.com/git/dinheiro/config" "git.eletrotupi.com/git/dinheiro/redis" + "git.eletrotupi.com/git/dinheiro/keys" ) func FileServer(router chi.Router, path string, root http.FileSystem) { @@ -62,8 +63,9 @@ } func Server() { appConfig := config.LoadConfig() + router := chi.NewRouter() - router := chi.NewRouter() + keys.Prepare(appConfig) // XXX: We should probably have a struct holding all this together redisHost, ok := appConfig.Get("redis", "redis-host") diff --git a/keys/keys.go b/keys/keys.go new file mode 100644 index 0000000000000000000000000000000000000000..11fa176c34e6f6272823a52d58ffa487fd1408f8 --- /dev/null +++ b/keys/keys.go @@ -0,0 +1,47 @@ +package keys + +import ( + "log" + "time" + + "github.com/fernet/fernet-go" + "github.com/vaughan0/go-ini" +) + +var ( + fernetKey *fernet.Key +) + +func Prepare(config ini.File) { + var ( + err error + ) + + base64key, ok := config.Get("keys", "fernet") + + if !ok { + log.Fatal("Fernet key was not setted. Generate one using dinheiro keys") + } + + fernetKey, err = fernet.DecodeKey(base64key) + if err != nil { + log.Fatalf("There was some error when decoding the fernet key %v", err) + } +} + +func Encrypt(payload []byte) []byte { + msg, err := fernet.EncryptAndSign(payload, fernetKey) + + if err != nil { + log.Fatalf("Error encrypting payload: %v", err) + } + + return msg +} + +// TODO: Add a method to decrypt taking expiration time in account, which will +// be useful for dealing with cookies +func DecryptWithoutExpiration(payload []byte) []byte { + return fernet.VerifyAndDecrypt(payload, + time.Duration(0), []*fernet.Key{fernetKey}) +}