1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 import util
21
22
25
26
28 """
29 Robey's tiny little attempt at a BER decoder.
30 """
31
33 self.content = content
34 self.idx = 0
35
38
40 return 'BER(\'' + repr(self.content) + '\')'
41
44
46 if self.idx >= len(self.content):
47 return None
48 ident = ord(self.content[self.idx])
49 self.idx += 1
50 if (ident & 31) == 31:
51
52 ident = 0
53 while self.idx < len(self.content):
54 t = ord(self.content[self.idx])
55 self.idx += 1
56 ident = (ident << 7) | (t & 0x7f)
57 if not (t & 0x80):
58 break
59 if self.idx >= len(self.content):
60 return None
61
62 size = ord(self.content[self.idx])
63 self.idx += 1
64 if size & 0x80:
65
66
67 t = size & 0x7f
68 if self.idx + t > len(self.content):
69 return None
70 size = util.inflate_long(self.content[self.idx : self.idx + t], True)
71 self.idx += t
72 if self.idx + size > len(self.content):
73
74 return None
75 data = self.content[self.idx : self.idx + size]
76 self.idx += size
77
78 if ident == 0x30:
79
80 return self.decode_sequence(data)
81 elif ident == 2:
82
83 return util.inflate_long(data)
84 else:
85
86 raise BERException('Unknown ber encoding type %d (robey is lazy)' % ident)
87
89 out = []
90 b = BER(data)
91 while True:
92 x = b.decode_next()
93 if x is None:
94 break
95 out.append(x)
96 return out
97 decode_sequence = staticmethod(decode_sequence)
98
100
101 self.content += chr(ident)
102 if len(val) > 0x7f:
103 lenstr = util.deflate_long(len(val))
104 self.content += chr(0x80 + len(lenstr)) + lenstr
105 else:
106 self.content += chr(len(val))
107 self.content += val
108
123
125 b = BER()
126 for item in data:
127 b.encode(item)
128 return str(b)
129 encode_sequence = staticmethod(encode_sequence)
130