Module: SecureKeys::Validation::Entropy

Defined in:
lib/validation/utils/entropy.rb

Class Method Summary collapse

Class Method Details

.calculate(string:) ⇒ Float

Calculate the Shannon entropy of a string

Parameters:

  • string (String)

    The string to analyze

Returns:

  • (Float)

    The Shannon entropy value (higher means more random)



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/validation/utils/entropy.rb', line 11

def calculate(string:)
  return 0.0 if string.empty?

  frequencies = Hash.new(0)
  string.each_char { |char| frequencies[char] += 1 }

  frequencies.each_value.sum do |count|
    frequency = count.to_f / string.length
    -frequency * Math.log2(frequency)
  end
end