crypto.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Copyright 2018 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package crypto // import "miniflux.app/crypto"
  5. import (
  6. "crypto/rand"
  7. "crypto/sha256"
  8. "encoding/base64"
  9. "encoding/hex"
  10. "fmt"
  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. }