-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto_math.rb
48 lines (42 loc) · 1.02 KB
/
crypto_math.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
module CryptoMath
refine Fixnum do
def factorial
(1..self).reduce(:*) || 1
end
end
refine String do
def binary_op(other)
throw :mismatchedStringLengths unless self.length == other.length
other_a = other.unpack("U*")
self.unpack("U*").map.with_index do |s, i|
yield s, other_a[i]
end.pack("U*")
end
def ^(other)
binary_op(other) {|a, b| a^b}
end
def &(other)
binary_op(other) {|a, b| a&b}
end
def |(other)
binary_op(other) {|a, b| a|b}
end
# Returns string as an array of ascii numbers in binary
def to_bi_a
self.chars.map {|c| c.ord.to_s(2)}
end
# copied from: https://github.com/emonti/rbkb/blob/a6d35c0fd785bae135034502b1d07ed626aebde5/lib/rbkb/extends/string.rb#L163
def entropy
e = 0
sz = self.bytesize.to_f
b = self.bytes
0.upto(255) do |i|
x = b.count(i)/sz
if x > 0
e += - x * (Math.log(x)/Math.log(2))
end
end
e
end
end
end