crypto.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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/rand"
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "fmt"
  10. "golang.org/x/crypto/bcrypt"
  11. )
  12. // HashFromBytes returns a SHA-256 checksum of the input.
  13. func HashFromBytes(value []byte) string {
  14. sum := sha256.Sum256(value)
  15. return fmt.Sprintf("%x", sum)
  16. }
  17. // Hash returns a SHA-256 checksum of a string.
  18. func Hash(value string) string {
  19. return HashFromBytes([]byte(value))
  20. }
  21. // GenerateRandomBytes returns random bytes.
  22. func GenerateRandomBytes(size int) []byte {
  23. b := make([]byte, size)
  24. if _, err := rand.Read(b); err != nil {
  25. panic(err)
  26. }
  27. return b
  28. }
  29. // GenerateRandomString returns a random string.
  30. func GenerateRandomString(size int) string {
  31. return base64.URLEncoding.EncodeToString(GenerateRandomBytes(size))
  32. }
  33. // GenerateRandomStringHex returns a random hexadecimal string.
  34. func GenerateRandomStringHex(size int) string {
  35. return hex.EncodeToString(GenerateRandomBytes(size))
  36. }
  37. func HashPassword(password string) (string, error) {
  38. bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  39. return string(bytes), err
  40. }