crypto.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. sum := sha256.Sum256(value)
  17. return fmt.Sprintf("%x", sum)
  18. }
  19. // Hash returns a SHA-256 checksum of a string.
  20. func Hash(value string) string {
  21. return HashFromBytes([]byte(value))
  22. }
  23. // GenerateRandomBytes returns random bytes.
  24. func GenerateRandomBytes(size int) []byte {
  25. b := make([]byte, size)
  26. if _, err := rand.Read(b); err != nil {
  27. panic(err)
  28. }
  29. return b
  30. }
  31. // GenerateRandomString returns a random string.
  32. func GenerateRandomString(size int) string {
  33. return base64.URLEncoding.EncodeToString(GenerateRandomBytes(size))
  34. }
  35. // GenerateRandomStringHex returns a random hexadecimal string.
  36. func GenerateRandomStringHex(size int) string {
  37. return hex.EncodeToString(GenerateRandomBytes(size))
  38. }
  39. func HashPassword(password string) (string, error) {
  40. bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  41. return string(bytes), err
  42. }
  43. func GenerateSHA256Hmac(secret string, data []byte) string {
  44. h := hmac.New(sha256.New, []byte(secret))
  45. h.Write(data)
  46. return hex.EncodeToString(h.Sum(nil))
  47. }
  48. func GenerateUUID() string {
  49. b := GenerateRandomBytes(16)
  50. return fmt.Sprintf("%X-%X-%X-%X-%X", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
  51. }
  52. func ConstantTimeCmp(a, b string) bool {
  53. return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
  54. }