4
0

crypto.go 919 B

1234567891011121314151617181920212223242526272829303132333435363738
  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. "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. }