crypto.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package crypto // import "miniflux.app/crypto"
  4. import (
  5. "crypto/rand"
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "fmt"
  10. )
  11. // HashFromBytes returns a SHA-256 checksum of the input.
  12. func HashFromBytes(value []byte) string {
  13. sum := sha256.Sum256(value)
  14. return fmt.Sprintf("%x", sum)
  15. }
  16. // Hash returns a SHA-256 checksum of a string.
  17. func Hash(value string) string {
  18. return HashFromBytes([]byte(value))
  19. }
  20. // GenerateRandomBytes returns random bytes.
  21. func GenerateRandomBytes(size int) []byte {
  22. b := make([]byte, size)
  23. if _, err := rand.Read(b); err != nil {
  24. panic(err)
  25. }
  26. return b
  27. }
  28. // GenerateRandomString returns a random string.
  29. func GenerateRandomString(size int) string {
  30. return base64.URLEncoding.EncodeToString(GenerateRandomBytes(size))
  31. }
  32. // GenerateRandomStringHex returns a random hexadecimal string.
  33. func GenerateRandomStringHex(size int) string {
  34. return hex.EncodeToString(GenerateRandomBytes(size))
  35. }