Class: Epics::MGF1

Inherits:
Object
  • Object
show all
Defined in:
lib/epics/mgf.rb

Instance Method Summary collapse

Constructor Details

#initialize(digest = OpenSSL::Digest::SHA256) ⇒ MGF1

Returns a new instance of MGF1.


2
3
4
5
# File 'lib/epics/mgf.rb', line 2

def initialize(digest = OpenSSL::Digest::SHA256)
  @digest = digest.new
  @hlen = 32
end

Instance Method Details

#divceil(a, b) ⇒ Object


25
26
27
# File 'lib/epics/mgf.rb', line 25

def divceil(a, b)
  (a + b - 1) / b
end

#generate(seed, masklen) ⇒ Object


7
8
9
10
11
12
13
14
15
16
# File 'lib/epics/mgf.rb', line 7

def generate(seed, masklen)
  if masklen > (2 << 31) * @hlen
    raise ArgumentError, "mask too long"
  end
  t = ""
  divceil(masklen, @hlen).times do |counter|
    t += @digest.digest(seed + i2osp(counter, 4))
  end
  t[0, masklen]
end

#i2osp(x, len) ⇒ Object


18
19
20
21
22
23
# File 'lib/epics/mgf.rb', line 18

def i2osp(x, len)
  if x >= 256 ** len
    raise ArgumentError, "integer too large"
  end
  [x].pack("N").gsub(/^\x00+/, '').rjust(len, "\x00")
end

#xor(a, b) ⇒ Object


29
30
31
32
33
34
35
36
37
38
39
# File 'lib/epics/mgf.rb', line 29

def xor(a, b)
  if a.size != b.size
    raise ArgumentError, "different length for a and b"
  end
  a = a.unpack('C*')
  b = b.unpack('C*')
  a.size.times do |idx|
    a[idx] ^= b[idx]
  end
  a.pack("C*")
end