crypto.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package sprig
  2. import (
  3. "crypto/sha1"
  4. "crypto/sha256"
  5. "crypto/sha512"
  6. "encoding/hex"
  7. "fmt"
  8. "hash/adler32"
  9. )
  10. // sha512sum computes the SHA-512 hash of the input string and returns it as a hex-encoded string.
  11. // This function can be used in templates to generate secure hashes of sensitive data.
  12. //
  13. // Example usage in templates: {{ "hello world" | sha512sum }}
  14. func sha512sum(input string) string {
  15. hash := sha512.Sum512([]byte(input))
  16. return hex.EncodeToString(hash[:])
  17. }
  18. // sha256sum computes the SHA-256 hash of the input string and returns it as a hex-encoded string.
  19. // This is a commonly used cryptographic hash function that produces a 256-bit (32-byte) hash value.
  20. //
  21. // Example usage in templates: {{ "hello world" | sha256sum }}
  22. func sha256sum(input string) string {
  23. hash := sha256.Sum256([]byte(input))
  24. return hex.EncodeToString(hash[:])
  25. }
  26. // sha1sum computes the SHA-1 hash of the input string and returns it as a hex-encoded string.
  27. // Note: SHA-1 is no longer considered secure against well-funded attackers for cryptographic purposes.
  28. // Consider using sha256sum or sha512sum for security-critical applications.
  29. //
  30. // Example usage in templates: {{ "hello world" | sha1sum }}
  31. func sha1sum(input string) string {
  32. hash := sha1.Sum([]byte(input))
  33. return hex.EncodeToString(hash[:])
  34. }
  35. // adler32sum computes the Adler-32 checksum of the input string and returns it as a decimal string.
  36. // This is a non-cryptographic hash function primarily used for error detection.
  37. //
  38. // Example usage in templates: {{ "hello world" | adler32sum }}
  39. func adler32sum(input string) string {
  40. hash := adler32.Checksum([]byte(input))
  41. return fmt.Sprintf("%d", hash)
  42. }