/usr/share/pyshared/Crypto/Util/asn1.py is in python-crypto 2.4.1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 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 62 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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | # -*- coding: ascii -*-
#
# Util/asn1.py : Minimal support for ASN.1 DER binary encoding.
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
from Crypto.Util.number import long_to_bytes, bytes_to_long
import sys
from Crypto.Util.py3compat import *
__all__ = [ 'DerObject', 'DerInteger', 'DerSequence' ]
class DerObject:
typeTags = { 'SEQUENCE':b('\x30'), 'BIT STRING':b('\x03'), 'INTEGER':b('\x02') }
def __init__(self, ASN1Type=None):
self.typeTag = self.typeTags.get(ASN1Type, ASN1Type)
self.payload = b('')
def _lengthOctets(self, payloadLen):
'''
Return an octet string that is suitable for the BER/DER
length element if the relevant payload is of the given
size (in bytes).
'''
if payloadLen>127:
encoding = long_to_bytes(payloadLen)
return bchr(len(encoding)+128) + encoding
return bchr(payloadLen)
def encode(self):
return self.typeTag + self._lengthOctets(len(self.payload)) + self.payload
def _decodeLen(self, idx, str):
'''
Given a string and an index to a DER LV,
this function returns a tuple with the length of V
and an index to the first byte of it.
'''
length = bord(str[idx])
if length<=127:
return (length,idx+1)
else:
payloadLength = bytes_to_long(str[idx+1:idx+1+(length & 0x7F)])
if payloadLength<=127:
raise ValueError("Not a DER length tag.")
return (payloadLength, idx+1+(length & 0x7F))
def decode(self, input, noLeftOvers=0):
try:
self.typeTag = input[0]
if (bord(self.typeTag) & 0x1F)==0x1F:
raise ValueError("Unsupported DER tag")
(length,idx) = self._decodeLen(1,input)
if noLeftOvers and len(input) != (idx+length):
raise ValueError("Not a DER structure")
self.payload = input[idx:idx+length]
except IndexError:
raise ValueError("Not a valid DER SEQUENCE.")
return idx+length
class DerInteger(DerObject):
def __init__(self, value = 0):
DerObject.__init__(self, 'INTEGER')
self.value = value
def encode(self):
self.payload = long_to_bytes(self.value)
if bord(self.payload[0])>127:
self.payload = b('\x00') + self.payload
return DerObject.encode(self)
def decode(self, input, noLeftOvers=0):
tlvLength = DerObject.decode(self, input,noLeftOvers)
if bord(self.payload[0])>127:
raise ValueError ("Negative INTEGER.")
self.value = bytes_to_long(self.payload)
return tlvLength
class DerSequence(DerObject):
def __init__(self):
DerObject.__init__(self, 'SEQUENCE')
self._seq = []
def __delitem__(self, n):
del self._seq[n]
def __getitem__(self, n):
return self._seq[n]
def __setitem__(self, key, value):
self._seq[key] = value
if sys.version_info[0] == 2:
def __setslice__(self,i,j,sequence):
self._seq[i:j] = sequence
def __delslice__(self,i,j):
del self._seq[i:j]
def __getslice__(self, i, j):
return self._seq[max(0, i):max(0, j)]
def __len__(self):
return len(self._seq)
def append(self, item):
return self._seq.append(item)
def hasOnlyInts(self):
if not self._seq: return 0
test = 0
for item in self._seq:
try:
test += item
except TypeError:
return 0
return 1
def encode(self):
'''
Return the DER encoding for the ASN.1 SEQUENCE containing
the non-negative integers and longs added to this object.
'''
self.payload = b('')
for item in self._seq:
try:
self.payload += item
except:
try:
self.payload += DerInteger(item).encode()
except:
raise ValueError("Trying to DER encode an unknown object")
return DerObject.encode(self)
def decode(self, input,noLeftOvers=0):
'''
This function decodes the given string into a sequence of
ASN.1 objects. Yet, we only know about unsigned INTEGERs.
Any other type is stored as its rough TLV. In the latter
case, the correctectness of the TLV is not checked.
'''
self._seq = []
try:
tlvLength = DerObject.decode(self, input,noLeftOvers)
if self.typeTag!=self.typeTags['SEQUENCE'][0]:
raise ValueError("Not a DER SEQUENCE.")
# Scan one TLV at once
idx = 0
while idx<len(self.payload):
typeTag = self.payload[idx]
if typeTag==self.typeTags['INTEGER'][0]:
newInteger = DerInteger()
idx += newInteger.decode(self.payload[idx:])
self._seq.append(newInteger.value)
else:
itemLen,itemIdx = self._decodeLen(idx+1,self.payload)
self._seq.append(self.payload[idx:itemIdx+itemLen])
idx = itemIdx + itemLen
except IndexError:
raise ValueError("Not a valid DER SEQUENCE.")
return tlvLength
|