entropy.go 934 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package gitleaks
  2. import (
  3. "math"
  4. )
  5. // getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
  6. func getShannonEntropy(data string) (entropy float64) {
  7. if data == "" {
  8. return 0
  9. }
  10. charCounts := make(map[rune]int)
  11. for _, char := range data {
  12. charCounts[char]++
  13. }
  14. invLength := 1.0 / float64(len(data))
  15. for _, count := range charCounts {
  16. freq := float64(count) * invLength
  17. entropy -= freq * math.Log2(freq)
  18. }
  19. return entropy
  20. }
  21. func entropyIsHighEnough(entropy float64) bool {
  22. if entropy >= opts.Entropy && len(config.Entropy.entropyRanges) == 0 {
  23. return true
  24. }
  25. for _, eR := range config.Entropy.entropyRanges {
  26. if entropy > eR.v1 && entropy < eR.v2 {
  27. return true
  28. }
  29. }
  30. return false
  31. }
  32. func highEntropyLineIsALeak(line string) bool {
  33. if !opts.NoiseReduction {
  34. return true
  35. }
  36. for _, re := range config.Entropy.regexes {
  37. if re.FindString(line) != "" {
  38. return true
  39. }
  40. }
  41. return false
  42. }