keygen.go 949 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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. keyDefaultStatus = "1"
  15. )
  16. // newKeyIden returns a UUIDv4 string without dashes.
  17. func newKeyIden() string {
  18. return strings.ReplaceAll(uuid.NewString(), "-", "")
  19. }
  20. // deriveKeyContent derives a 256-bit key with PBKDF2-HMAC-SHA256.
  21. // The password is a fresh random seed and iden is the salt, so every
  22. // key record gets an unpredictable content.
  23. func deriveKeyContent(iden string) (string, error) {
  24. seed := make([]byte, 32)
  25. if _, err := rand.Read(seed); err != nil {
  26. return "", fmt.Errorf("generate random seed: %w", err)
  27. }
  28. derived, err := pbkdf2.Key(sha256.New, string(seed), []byte(iden), keyKDFIterations, keyContentBytes)
  29. if err != nil {
  30. return "", fmt.Errorf("derive key content: %w", err)
  31. }
  32. return hex.EncodeToString(derived), nil
  33. }