crypto.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package crypto // import "miniflux.app/v2/internal/crypto"
  4. import (
  5. "crypto/hmac"
  6. "crypto/rand"
  7. "crypto/sha256"
  8. "crypto/subtle"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "fmt"
  12. "golang.org/x/crypto/bcrypt"
  13. )
  14. // HashFromBytes returns a SHA-256 checksum of the input.
  15. func HashFromBytes(value []byte) string {
  16. return fmt.Sprintf("%x", sha256.Sum256(value))
  17. }
  18. // Hash returns a SHA-256 checksum of a string.
  19. func Hash(value string) string {
  20. return HashFromBytes([]byte(value))
  21. }
  22. // GenerateRandomBytes returns random bytes.
  23. func GenerateRandomBytes(size int) []byte {
  24. b := make([]byte, size)
  25. if _, err := rand.Read(b); err != nil {
  26. panic(err)
  27. }
  28. return b
  29. }
  30. // GenerateRandomString returns a random string.
  31. func GenerateRandomString(size int) string {
  32. return base64.URLEncoding.EncodeToString(GenerateRandomBytes(size))
  33. }
  34. // GenerateRandomStringHex returns a random hexadecimal string.
  35. func GenerateRandomStringHex(size int) string {
  36. return hex.EncodeToString(GenerateRandomBytes(size))
  37. }
  38. func HashPassword(password string) (string, error) {
  39. bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  40. return string(bytes), err
  41. }
  42. func GenerateSHA256Hmac(secret string, data []byte) string {
  43. h := hmac.New(sha256.New, []byte(secret))
  44. h.Write(data)
  45. return hex.EncodeToString(h.Sum(nil))
  46. }
  47. func GenerateUUID() string {
  48. b := GenerateRandomBytes(16)
  49. return fmt.Sprintf("%X-%X-%X-%X-%X", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
  50. }
  51. func ConstantTimeCmp(a, b string) bool {
  52. return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
  53. }