crypto.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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/hex"
  10. "fmt"
  11. "hash/fnv"
  12. "golang.org/x/crypto/bcrypt"
  13. )
  14. // HashFromBytes returns a non-cryptographic checksum of the input.
  15. func HashFromBytes(value []byte) string {
  16. h := fnv.New128a()
  17. h.Write(value)
  18. return hex.EncodeToString(h.Sum(nil))
  19. }
  20. // SHA256 returns a SHA-256 checksum of a string.
  21. func SHA256(value string) string {
  22. h := sha256.Sum256([]byte(value))
  23. return hex.EncodeToString(h[:])
  24. }
  25. // GenerateRandomBytes returns random bytes.
  26. func GenerateRandomBytes(size int) []byte {
  27. b := make([]byte, size)
  28. rand.Read(b)
  29. return b
  30. }
  31. // GenerateRandomStringHex returns a random hexadecimal string.
  32. func GenerateRandomStringHex(size int) string {
  33. return hex.EncodeToString(GenerateRandomBytes(size))
  34. }
  35. func HashPassword(password string) (string, error) {
  36. bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  37. return string(bytes), err
  38. }
  39. func GenerateSHA256Hmac(secret string, data []byte) string {
  40. h := hmac.New(sha256.New, []byte(secret))
  41. h.Write(data)
  42. return hex.EncodeToString(h.Sum(nil))
  43. }
  44. func GenerateUUID() string {
  45. b := GenerateRandomBytes(16)
  46. return fmt.Sprintf("%X-%X-%X-%X-%X", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
  47. }
  48. func ConstantTimeCmp(a, b string) bool {
  49. return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
  50. }