Class: Kdbx::Header

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/kdbx/header.rb

Constant Summary collapse

FILEMAGIC =
"\x03\xD9\xA2\x9A\x67\xFB\x4B\xB5\x01\x00\x03\x00".b

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fields = {}) ⇒ Header

Returns a new instance of Header.



25
26
27
28
# File 'lib/kdbx/header.rb', line 25

def initialize(fields = {})
  @fields = fields
  validate
end

Class Method Details

.load(file) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/kdbx/header.rb', line 7

def self.load(file)
  if file.readpartial(12) != FILEMAGIC
    fail ParseError, "bad magic number"
  end
  fields = {}
  loop do
    (id, sz) = file.readpartial(3).unpack("CS<")
    fields[id] = file.readpartial sz
    break if id == 0
  end
  new fields
rescue TypeError, EOFError
  fail ParseError, "truncated header"
end

Instance Method Details

#dumpObject



30
31
32
33
34
35
36
37
38
39
# File 'lib/kdbx/header.rb', line 30

def dump
  merge_defaults and validate
  StringIO.new.binmode.tap do |io|
    io.write FILEMAGIC
    @fields.each do |k, v|
      io.write [k, v.bytesize].pack("CS<") + v if k != 0
    end
    io.write [0, @fields[0].bytesize].pack("CS<") + @fields[0]
  end.string
end

#validateObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/kdbx/header.rb', line 41

def validate
  @fields.each do |k, v|
    fail FormatError, "header #{k.inspect}: #{v}" unless k.is_a? Integer
    fail FormatError, "header #{k}: #{v.inspect}" unless v.is_a? String
    @fields[k] = v = v.b unless v.encoding == Encoding::ASCII_8BIT
    case k
    when 2
      if v != "\x31\xC1\xF2\xE6\xBF\x71\x43\x50\xBE\x58\x05\x21\x6A\xFC\x5A\xFF".b
        fail FormatError, "header #{k}: #{v.inspect}"
      end
    when 3
      if v.bytesize != 4 || !(0..1).include?(v.unpack("L").first)
        fail FormatError, "header #{k}: #{v.inspect}"
      end
    when 4, 5
      fail FormatError, "header #{k}: #{v.inspect}" if v.bytesize != 32
    when 6
      fail FormatError, "header #{k}: #{v.inspect}" if v.bytesize != 8
    when 7
      fail FormatError, "header #{k}: #{v.inspect}" if v.bytesize != 16
    when 8
      if @fields[10] == "\x02\x00\x00\x00".b && v.bytesize != 32
        fail FormatError, "header #{k}: #{v.inspect}"
      end
    when 10
      fail FormatError, "header #{k}: #{v.inspect}" if v.bytesize != 4
      if (n = v.unpack("L<").first) != 0 && n != 2
        fail FormatError, "header #{k}: #{v.inspect}"
      end
    end
  end
end