keygen.go 1014 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package logic
  2. import (
  3. "crypto/pbkdf2"
  4. "crypto/rand"
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "fmt"
  8. "strings"
  9. "github.com/google/uuid"
  10. )
  11. const (
  12. keyKDFIterations = 100_000
  13. keyContentBytes = 32
  14. keyStatusEnabled = "1"
  15. keyStatusDisabled = "2"
  16. keyDefaultStatus = keyStatusEnabled
  17. )
  18. // newKeyIden returns a UUIDv4 string without dashes.
  19. func newKeyIden() string {
  20. return strings.ReplaceAll(uuid.NewString(), "-", "")
  21. }
  22. // deriveKeyContent derives a 256-bit key with PBKDF2-HMAC-SHA256.
  23. // The password is a fresh random seed and iden is the salt, so every
  24. // key record gets an unpredictable content.
  25. func deriveKeyContent(iden string) (string, error) {
  26. seed := make([]byte, 32)
  27. if _, err := rand.Read(seed); err != nil {
  28. return "", fmt.Errorf("generate random seed: %w", err)
  29. }
  30. derived, err := pbkdf2.Key(sha256.New, string(seed), []byte(iden), keyKDFIterations, keyContentBytes)
  31. if err != nil {
  32. return "", fmt.Errorf("derive key content: %w", err)
  33. }
  34. return hex.EncodeToString(derived), nil
  35. }