Class: Binenc::Ruby::SBLFactory

Inherits:
Object
  • Object
show all
Includes:
SBLDSL
Defined in:
lib/binenc/factory/sbl_factory/sbl_factory.rb

Overview

simple binary layout factory

Instance Method Summary collapse

Methods included from SBLDSL

#bin, #date, #int, #oid, #seq, #str

Instance Method Details

#define(&block) ⇒ Object



11
12
13
14
# File 'lib/binenc/factory/sbl_factory/sbl_factory.rb', line 11

def define(&block)
  instance_eval(&block) 
  self
end

#encodedObject



16
17
18
19
20
21
22
23
# File 'lib/binenc/factory/sbl_factory/sbl_factory.rb', line 16

def encoded
  res = []
  structure.each do |st|
    res << self.send("#{to_instance_method_name(st)}").encoded
  end

  ASN1Sequence.new(res).encoded
end

#from_bin(bin) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/binenc/factory/sbl_factory/sbl_factory.rb', line 25

def from_bin(bin)
  
  seq = ASN1Object.decode(bin).value

  if seq.length > structure.length
    logger.warn "Given binary has more field (#{seq.length}) than the defined specification (#{structure.length}). Different version of structure?"
  elsif structure.length > seq.length
    logger.warn "Defined specification has more field (#{structure.length}) than given binary (#{seq.length}). Different version of structure?"
  end

  structure.each_index do |i|
    name = structure[i]
    
    if seq[i].is_a?(String)
      # begin block is to cater sequence but tagged as binary field
      # Therefore during 1st decode, it will become an array with actual value, 
      # no longer a ASN1 encoded field.
      # Different if the field is tagged as sequence, then this will not happened
      begin
        val = ASN1Object.decode(seq[i]).value
      rescue OpenSSL::ASN1::ASN1Error
        val = seq[i]
      end
    else
      val = seq[i]
    end

    case val
    when OpenSSL::BN
      val = val.to_i
    end
    create_instance_method(name, val)
  end

  self

end

#value_from_bin_struct(bin, *fieldNo) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/binenc/factory/sbl_factory/sbl_factory.rb', line 63

def value_from_bin_struct(bin, *fieldNo)

  begin
    seq = ASN1Object.decode(bin).value

    ret = []
    fieldNo.each do |fn|
      raise BinencEngineException, "Given field no '#{fn}' to extract is larger than found fields (#{seq.length})" if fn > seq.length

      v = seq[fn]
      if v.is_a?(String)
        begin
          vv = ASN1Object.decode(v).value
        rescue OpenSSL::ASN1::ASN1Error
          vv = v
        end
      else
        vv = v
      end

      case vv
      when OpenSSL::BN
        ret << vv.to_i
      else
        ret << vv
      end
    end

    ret
  rescue OpenSSL::ASN1::ASN1Error => ex
    raise BinencDecodingError, ex
  end

end