Method: Binenc::Ruby::SBLFactory#from_bin

Defined in:
lib/binenc/factory/sbl_factory/sbl_factory.rb

#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