entropy.go (868B)
1 package passwordvalidator 2 3 import ( 4 "math" 5 ) 6 7 // GetEntropy returns the entropy in bits for the given password 8 // See the ReadMe for more information 9 func GetEntropy(password string) float64 { 10 return getEntropy(password) 11 } 12 13 func getEntropy(password string) float64 { 14 base := getBase(password) 15 length := getLength(password) 16 17 // calculate log2(base^length) 18 return logPow(float64(base), length, 2) 19 } 20 21 func logX(base, n float64) float64 { 22 if base == 0 { 23 return 0 24 } 25 // change of base formulae 26 return math.Log2(n) / math.Log2(base) 27 } 28 29 // logPow calculates log_base(x^y) 30 // without leaving logspace for each multiplication step 31 // this makes it take less space in memory 32 func logPow(expBase float64, pow int, logBase float64) float64 { 33 // logb (MN) = logb M + logb N 34 total := 0.0 35 for i := 0; i < pow; i++ { 36 total += logX(logBase, expBase) 37 } 38 return total 39 }