jwt.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // provides jwt encode and decode functions
  2. package jwt
  3. import (
  4. "crypto/hmac"
  5. "crypto/sha256"
  6. "errors"
  7. "fmt"
  8. "strings"
  9. "git.clearsky.net.au/cody/gex.git/sec/base64"
  10. )
  11. // encode json bytes to a jwt token string
  12. func Encode(jsonStr []byte, secret string) (string, error) {
  13. header := base64.EncodeURL([]byte("{\"alg\":\"HS256\",\"typ\":\"JWT\"}"))
  14. payload := base64.EncodeURL(jsonStr)
  15. mac := hmac.New(sha256.New, []byte(secret))
  16. mac.Write([]byte(header + "." + payload))
  17. sig := base64.EncodeURL(mac.Sum(nil))
  18. return header + "." + payload + "." + sig, nil
  19. }
  20. // decode a jwt token string to a json string to be processed
  21. func Decode(tokenStr string, secret string) ([]byte, error) {
  22. parts := strings.Split(tokenStr, ".")
  23. header := parts[0]
  24. payload := parts[1]
  25. sig, err := base64.DecodeURL(parts[2])
  26. if err != nil {
  27. fmt.Printf("ERROR: %s", err)
  28. return []byte(""), err
  29. }
  30. mac := hmac.New(sha256.New, []byte(secret))
  31. mac.Write([]byte(header + "." + payload))
  32. expectedSig := mac.Sum(nil)
  33. if !hmac.Equal([]byte(sig), expectedSig) {
  34. return []byte(""), errors.New("signature don't match")
  35. }
  36. jsonStr, err := base64.DecodeURL(payload)
  37. if err != nil {
  38. fmt.Printf("ERROR: %s", err)
  39. return []byte(""), err
  40. }
  41. return jsonStr, nil
  42. }