generator.go 934 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package httpsession
  2. import (
  3. "crypto/hmac"
  4. "crypto/rand"
  5. "crypto/sha1"
  6. "encoding/hex"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "time"
  11. )
  12. type IdGenerator interface {
  13. Gen(req *http.Request) Id
  14. IsValid(id Id) bool
  15. }
  16. type Sha1Generator struct {
  17. hashKey string
  18. }
  19. func NewSha1Generator(hashKey string) *Sha1Generator {
  20. return &Sha1Generator{hashKey}
  21. }
  22. var _ IdGenerator = NewSha1Generator("test")
  23. func GenRandKey(strength int) []byte {
  24. k := make([]byte, strength)
  25. if _, err := io.ReadFull(rand.Reader, k); err != nil {
  26. return nil
  27. }
  28. return k
  29. }
  30. func (gen *Sha1Generator) Gen(req *http.Request) Id {
  31. bs := GenRandKey(24)
  32. if len(bs) == 0 {
  33. return Id("")
  34. }
  35. sig := fmt.Sprintf("%s%d%s", req.RemoteAddr, time.Now().UnixNano(), string(bs))
  36. h := hmac.New(sha1.New, []byte(gen.hashKey))
  37. fmt.Fprintf(h, "%s", sig)
  38. return Id(hex.EncodeToString(h.Sum(nil)))
  39. }
  40. func (gen *Sha1Generator) IsValid(id Id) bool {
  41. return string(id) != ""
  42. }