crypto.go 1.7 KB

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