Package spoon :: Package ber :: Module common
[hide private]
[frames] | no frames]

Source Code for Module spoon.ber.common

 1  # 
 2  # Copyright (C) 2003-2006, Robey Pointer <robey@lag.net> 
 3  # 
 4  # Permission is hereby granted, free of charge, to any person obtaining 
 5  # a copy of this software and associated documentation files (the 
 6  # "Software"), to deal in the Software without restriction, including 
 7  # without limitation the rights to use, copy, modify, merge, publish, 
 8  # distribute, sublicense, and/or sell copies of the Software, and to 
 9  # permit persons to whom the Software is furnished to do so, subject to 
10  # the following conditions: 
11  #  
12  # The above copyright notice and this permission notice shall be included 
13  # in all copies or substantial portions of the Software. 
14  #  
15  # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
16  # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
17  # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
18  # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
19  # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
20  # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
21  # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
22  # 
23   
24  import struct 
25   
26   
27  UNIVERSAL = 0 
28  APPLICATION = 1 
29  CONTEXT = 2 
30  PRIVATE = 3 
31       
32   
33 -class BERException (Exception):
34 pass
35 36
37 -def inflate_long(s, always_positive=False):
38 "turns a normalized byte string into a long-int (adapted from Crypto.Util.number)" 39 out = 0L 40 negative = 0 41 if not always_positive and (len(s) > 0) and (ord(s[0]) >= 0x80): 42 negative = 1 43 if len(s) % 4: 44 filler = '\x00' 45 if negative: 46 filler = '\xff' 47 s = filler * (4 - len(s) % 4) + s 48 for i in range(0, len(s), 4): 49 out = (out << 32) + struct.unpack('>I', s[i:i+4])[0] 50 if negative: 51 out -= (1L << (8 * len(s))) 52 return out
53 54
55 -def deflate_long(n, add_sign_padding=True):
56 "turns a long-int into a normalized byte string (adapted from Crypto.Util.number)" 57 # after much testing, this algorithm was deemed to be the fastest 58 s = '' 59 n = long(n) 60 while (n != 0) and (n != -1): 61 s = struct.pack('>I', n & 0xffffffffL) + s 62 n = n >> 32 63 # strip off leading zeros, FFs 64 for i in enumerate(s): 65 if (n == 0) and (i[1] != '\000'): 66 break 67 if (n == -1) and (i[1] != '\xff'): 68 break 69 else: 70 # degenerate case, n was either 0 or -1 71 i = (0,) 72 if n == 0: 73 s = '\000' 74 else: 75 s = '\xff' 76 s = s[i[0]:] 77 if add_sign_padding: 78 if (n == 0) and (ord(s[0]) >= 0x80): 79 s = '\x00' + s 80 if (n == -1) and (ord(s[0]) < 0x80): 81 s = '\xff' + s 82 return s
83