Python pyasn1.compat.octets.str2octs() Examples

The following are 26 code examples of pyasn1.compat.octets.str2octs(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyasn1.compat.octets , or try the search function .
Example #1
Source File: encoder.py    From teleport with Apache License 2.0 6 votes vote down vote up
def encodeValue(self, value, asn1Spec, encodeFun, **options):
        chunks = self._encodeComponents(
            value, asn1Spec, encodeFun, **options)

        # sort by serialised and padded components
        if len(chunks) > 1:
            zero = str2octs('\x00')
            maxLen = max(map(len, chunks))
            paddedChunks = [
                (x.ljust(maxLen, zero), x) for x in chunks
            ]
            paddedChunks.sort(key=lambda x: x[0])

            chunks = [x[1] for x in paddedChunks]

        return null.join(chunks), True, True 
Example #2
Source File: encoder.py    From teleport with Apache License 2.0 6 votes vote down vote up
def encodeValue(self, value, asn1Spec, encodeFun, **options):
        chunks = self._encodeComponents(
            value, asn1Spec, encodeFun, **options)

        # sort by serialised and padded components
        if len(chunks) > 1:
            zero = str2octs('\x00')
            maxLen = max(map(len, chunks))
            paddedChunks = [
                (x.ljust(maxLen, zero), x) for x in chunks
            ]
            paddedChunks.sort(key=lambda x: x[0])

            chunks = [x[1] for x in paddedChunks]

        return null.join(chunks), True, True 
Example #3
Source File: encoder.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def encodeValue(self, value, asn1Spec, encodeFun, **options):
        if asn1Spec is None:
            value.verifySizeSpec()
        else:
            asn1Spec = asn1Spec.componentType

        components = [encodeFun(x, asn1Spec, **options)
                      for x in value]

        # sort by serialised and padded components
        if len(components) > 1:
            zero = str2octs('\x00')
            maxLen = max(map(len, components))
            paddedComponents = [
                (x.ljust(maxLen, zero), x) for x in components
                ]
            paddedComponents.sort(key=lambda x: x[0])

            components = [x[1] for x in paddedComponents]

        substrate = null.join(components)

        return substrate, True, True 
Example #4
Source File: test_rfc6032.py    From pyasn1-modules with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def testOpenTypes(self):
        substrate = pem.readBase64fromText(self.encrypted_key_pkg_pem_text)
        asn1Object, rest = der_decoder(substrate,
                                       asn1Spec=self.asn1Spec,
                                       decodeOpenTypes=True)
        self.assertFalse(rest)
        self.assertTrue(asn1Object.prettyPrint())
        self.assertEqual(substrate, der_encoder(asn1Object))

        self.assertIn(asn1Object['contentType'], rfc5652.cmsContentTypesMap)

        eci = asn1Object['content']['encrypted']['encryptedContentInfo']

        self.assertIn(eci['contentType'], rfc5652.cmsContentTypesMap)

        for attr in asn1Object['content']['encrypted']['unprotectedAttrs']:
            self.assertIn(attr['attrType'], rfc5652.cmsAttributesMap)
            self.assertNotEqual('0x', attr['attrValues'][0].prettyPrint()[:2])

            if attr['attrType'] == rfc6032.id_aa_KP_contentDecryptKeyID:
                self.assertEqual(str2octs(
                    'ptf-kdc-812374'), attr['attrValues'][0]) 
Example #5
Source File: test_rfc4073.py    From pyasn1-modules with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def testOpenTypes(self):
        substrate = pem.readBase64fromText(self.pem_text)
        asn1Object, rest = der_decoder(substrate,
                                       asn1Spec=rfc5652.ContentInfo(),
                                       decodeOpenTypes=True)
        self.assertFalse(rest)
        self.assertTrue(asn1Object.prettyPrint())
        self.assertEqual(substrate, der_encoder(asn1Object))

        self.assertEqual(rfc4073.id_ct_contentCollection, asn1Object['contentType'])

        for ci in asn1Object['content']:
            self.assertIn(ci['contentType'], rfc5652.cmsContentTypesMap)
            self.assertEqual(rfc4073.id_ct_contentWithAttrs, ci['contentType'])

            next_ci = ci['content']['content']

            self.assertIn(next_ci['contentType'], rfc5652.cmsContentTypesMap)
            self.assertEqual(rfc5652.id_data, next_ci['contentType'])
            self.assertIn(str2octs('Content-Type: text'), next_ci['content'])

            for attr in ci['content']['attrs']:
                self.assertIn(attr['attrType'], rfc5652.cmsAttributesMap)
                if attr['attrType'] == rfc2634.id_aa_contentHint:
                    self.assertIn('RFC 4073', attr['attrValues'][0]['contentDescription']) 
Example #6
Source File: file.py    From snmpsim with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def find_eol(file_obj, offset, block_size=256, eol=str2octs('\n')):

    while True:
        if offset < block_size:
            offset, block_size = 0, offset

        else:
            offset -= block_size

        file_obj.seek(offset)

        chunk = file_obj.read(block_size)

        try:
            return offset + chunk.rindex(eol) + 1

        except ValueError:
            if offset == 0:
                return offset

            continue


# In-place, by-OID binary search 
Example #7
Source File: file.py    From snmpsim with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_record(fileObj, line_no=None, offset=0):

    line = fileObj.readline()

    if line_no is not None and line:
        line_no += 1

    while line:
        tline = line.strip()

        # skip comment or blank line
        if not tline or tline.startswith(str2octs('#')):
            offset += len(line)
            line = fileObj.readline()
            if line_no is not None and line:
                line_no += 1

        else:
            break

    return line, line_no, offset 
Example #8
Source File: encoder.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def encodeValue(self, value, asn1Spec, encodeFun, **options):
        chunks = self._encodeComponents(
            value, asn1Spec, encodeFun, **options)

        # sort by serialised and padded components
        if len(chunks) > 1:
            zero = str2octs('\x00')
            maxLen = max(map(len, chunks))
            paddedChunks = [
                (x.ljust(maxLen, zero), x) for x in chunks
            ]
            paddedChunks.sort(key=lambda x: x[0])

            chunks = [x[1] for x in paddedChunks]

        return null.join(chunks), True, True 
Example #9
Source File: encoder.py    From teleport with Apache License 2.0 6 votes vote down vote up
def encodeValue(self, value, asn1Spec, encodeFun, **options):
        if asn1Spec is None:
            value.verifySizeSpec()
        else:
            asn1Spec = asn1Spec.componentType

        components = [encodeFun(x, asn1Spec, **options)
                      for x in value]

        # sort by serialised and padded components
        if len(components) > 1:
            zero = str2octs('\x00')
            maxLen = max(map(len, components))
            paddedComponents = [
                (x.ljust(maxLen, zero), x) for x in components
                ]
            paddedComponents.sort(key=lambda x: x[0])

            components = [x[1] for x in paddedComponents]

        substrate = null.join(components)

        return substrate, True, True 
Example #10
Source File: encoder.py    From bash-lambda-layer with MIT License 6 votes vote down vote up
def encodeValue(self, value, asn1Spec, encodeFun, **options):
        if asn1Spec is None:
            value.verifySizeSpec()
        else:
            asn1Spec = asn1Spec.componentType

        components = [encodeFun(x, asn1Spec, **options)
                      for x in value]

        # sort by serialised and padded components
        if len(components) > 1:
            zero = str2octs('\x00')
            maxLen = max(map(len, components))
            paddedComponents = [
                (x.ljust(maxLen, zero), x) for x in components
                ]
            paddedComponents.sort(key=lambda x: x[0])

            components = [x[1] for x in paddedComponents]

        substrate = null.join(components)

        return substrate, True, True 
Example #11
Source File: univ.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def prettyIn(self, value):
        if value:
            return value

        return octets.str2octs('') 
Example #12
Source File: encoder.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def encodeValue(self, value, encodeFun, **options):
        value.verifySizeSpec()
        substrate = null
        idx = len(value)
        if value.typeId == univ.Set.typeId:
            namedTypes = value.componentType
            comps = []
            compsMap = {}
            while idx > 0:
                idx -= 1
                if namedTypes:
                    if namedTypes[idx].isOptional and not value[idx].isValue:
                        continue
                    if namedTypes[idx].isDefaulted and value[idx] == namedTypes[idx].asn1Object:
                        continue

                comps.append(value[idx])
                compsMap[id(value[idx])] = namedTypes and namedTypes[idx].isOptional

            for comp in self._sortComponents(comps):
                options.update(ifNotEmpty=compsMap[id(comp)])
                substrate += encodeFun(comp, **options)
        else:
            components = [encodeFun(x, **options) for x in value]

            # sort by serialized and padded components
            if len(components) > 1:
                zero = str2octs('\x00')
                maxLen = max(map(len, components))
                paddedComponents = [
                    (x.ljust(maxLen, zero), x) for x in components
                ]
                paddedComponents.sort(key=lambda x: x[0])

                components = [x[1] for x in paddedComponents]

            substrate = null.join(components)

        return substrate, True, True 
Example #13
Source File: crypto.py    From snmpfwd with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def decrypt(self, key, enc):
        iv = enc[:16]
        cipher = AES.new(str2octs(key), AES.MODE_CBC, iv)
        return self.unpad(cipher.decrypt(enc[16:])) 
Example #14
Source File: crypto.py    From snmpfwd with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def encrypt(self, key, raw):
        raw = self.pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(str2octs(key), AES.MODE_CBC, iv)
        return iv + cipher.encrypt(raw) 
Example #15
Source File: univ.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def prettyIn(self, value):
        if value:
            return value

        return octets.str2octs('') 
Example #16
Source File: snmprec.py    From snmpsim with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def build(self, oid, tag, val):
        if oid and tag:
            return str2octs('%s|%s|%s\n' % (oid, tag, val))

        raise error.SnmpsimError('empty OID/tag <%s/%s>' % (oid, tag)) 
Example #17
Source File: univ.py    From bash-lambda-layer with MIT License 5 votes vote down vote up
def prettyIn(self, value):
        if value:
            return value

        return octets.str2octs('') 
Example #18
Source File: test_rfc3770.py    From pyasn1-modules with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def testOpenTypes(self):
        substrate = pem.readBase64fromText(self.cert_pem_text)
        asn1Object, rest = der_decoder(
            substrate, asn1Spec=self.asn1Spec, decodeOpenTypes=True)

        self.assertFalse(rest)
        self.assertTrue(asn1Object.prettyPrint())
        self.assertEqual(substrate, der_encoder(asn1Object))

        sig_alg = asn1Object['tbsCertificate']['signature']

        self.assertEqual(rfc5480.ecdsa_with_SHA384, sig_alg['algorithm'])
        self.assertFalse(sig_alg['parameters'].hasValue())
    
        spki_alg = asn1Object['tbsCertificate']['subjectPublicKeyInfo']['algorithm']

        self.assertEqual(rfc5480.id_ecPublicKey, spki_alg['algorithm'])
        self.assertEqual(
            rfc5480.secp384r1, spki_alg['parameters']['namedCurve'])

        extn_list = []
        for extn in asn1Object['tbsCertificate']['extensions']:
            extn_list.append(extn['extnID'])
            if extn['extnID'] in rfc5280.certificateExtensionsMap.keys():
                extnValue, rest = der_decoder(
                    extn['extnValue'],
                    asn1Spec=rfc5280.certificateExtensionsMap[extn['extnID']])

                self.assertEqual(extn['extnValue'], der_encoder(extnValue))

                if extn['extnID'] == rfc3770.id_pe_wlanSSID:
                    self.assertIn(str2octs('Example'), extnValue)

                if extn['extnID'] == rfc5280.id_ce_extKeyUsage:
                    self.assertIn(rfc3770.id_kp_eapOverLAN, extnValue)
                    self.assertIn(rfc3770.id_kp_eapOverPPP, extnValue)

        self.assertIn(rfc3770.id_pe_wlanSSID, extn_list)
        self.assertIn(rfc5280.id_ce_extKeyUsage, extn_list) 
Example #19
Source File: test_rfc6032.py    From pyasn1-modules with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def testDerCodec(self):
        substrate = pem.readBase64fromText(self.encrypted_key_pkg_pem_text)
        asn1Object, rest = der_decoder(substrate, asn1Spec=self.asn1Spec)

        self.assertFalse(rest)
        self.assertTrue(asn1Object.prettyPrint())
        self.assertEqual(substrate, der_encoder(asn1Object))

        self.assertEqual(
            rfc6032.id_ct_KP_encryptedKeyPkg, asn1Object['contentType'])

        content, rest = der_decoder(
            asn1Object['content'], rfc6032.EncryptedKeyPackage())

        self.assertFalse(rest)
        self.assertTrue(content.prettyPrint())
        self.assertEqual(asn1Object['content'], der_encoder(content))
        self.assertEqual('encrypted', content.getName())

        eci = content['encrypted']['encryptedContentInfo']

        self.assertEqual(
            rfc6032.id_ct_KP_encryptedKeyPkg, eci['contentType'])

        attrType = content['encrypted']['unprotectedAttrs'][0]['attrType']

        self.assertEqual(rfc6032.id_aa_KP_contentDecryptKeyID, attrType)

        attrVal0 = content['encrypted']['unprotectedAttrs'][0]['attrValues'][0]
        keyid, rest = der_decoder(attrVal0, rfc6032.ContentDecryptKeyID())

        self.assertFalse(rest)
        self.assertTrue(keyid.prettyPrint())
        self.assertEqual(attrVal0, der_encoder(keyid))
        self.assertEqual(str2octs('ptf-kdc-812374'), keyid) 
Example #20
Source File: test_rfc4334.py    From pyasn1-modules with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def testOpenTypes(self):
        substrate = pem.readBase64fromText(self.cert_pem_text)
        asn1Object, rest = der_decoder(
            substrate, asn1Spec=self.asn1Spec, decodeOpenTypes=True)

        self.assertFalse(rest)
        self.assertTrue(asn1Object.prettyPrint())
        self.assertEqual(substrate, der_encoder(asn1Object))

        extn_list = []

        for extn in asn1Object['tbsCertificate']['extensions']:
            extn_list.append(extn['extnID'])
            if extn['extnID'] in rfc5280.certificateExtensionsMap.keys():
                extnValue, rest = der_decoder(
                    extn['extnValue'],
                    asn1Spec=rfc5280.certificateExtensionsMap[extn['extnID']])

                self.assertEqual(extn['extnValue'], der_encoder(extnValue))

                if extn['extnID'] == rfc4334.id_pe_wlanSSID:
                    self.assertIn( str2octs('Example'), extnValue)
            
                if extn['extnID'] == rfc5280.id_ce_extKeyUsage:
                    self.assertIn(rfc4334.id_kp_eapOverLAN, extnValue)
                    self.assertIn(rfc4334.id_kp_eapOverPPP, extnValue)

        self.assertIn(rfc4334.id_pe_wlanSSID, extn_list)
        self.assertIn(rfc5280.id_ce_extKeyUsage, extn_list) 
Example #21
Source File: univ.py    From teleport with Apache License 2.0 5 votes vote down vote up
def prettyIn(self, value):
        if value:
            return value

        return octets.str2octs('') 
Example #22
Source File: univ.py    From teleport with Apache License 2.0 5 votes vote down vote up
def prettyIn(self, value):
        if value:
            return value

        return octets.str2octs('') 
Example #23
Source File: encoder.py    From baidupan_shell with GNU General Public License v2.0 4 votes vote down vote up
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
        if value.isPlusInfinity():
            return int2oct(0x40), 0
        if value.isMinusInfinity():
            return int2oct(0x41), 0
        m, b, e = value
        if not m:
            return null, 0
        if b == 10:
            return str2octs('\x03%dE%s%d' % (m, e == 0 and '+' or '', e)), 0
        elif b == 2:
            fo = 0x80                 # binary enoding
            if m < 0:
                fo = fo | 0x40  # sign bit
                m = -m
            while int(m) != m: # drop floating point
                m *= 2
                e -= 1
            while m & 0x1 == 0: # mantissa normalization
                m >>= 1
                e += 1
            eo = null
            while e not in (0, -1):
                eo = int2oct(e&0xff) + eo
                e >>= 8
            if e == 0 and eo and oct2int(eo[0]) & 0x80:
                eo = int2oct(0) + eo
            n = len(eo)
            if n > 0xff:
                raise error.PyAsn1Error('Real exponent overflow')
            if n == 1:
                pass
            elif n == 2:
                fo |= 1
            elif n == 3:
                fo |= 2
            else:
                fo |= 3
                eo = int2oct(n//0xff+1) + eo
            po = null
            while m:
                po = int2oct(m&0xff) + po
                m >>= 8
            substrate = int2oct(fo) + eo + po
            return substrate, 0
        else:
            raise error.PyAsn1Error('Prohibited Real base %s' % b) 
Example #24
Source File: encoder.py    From xbmc-addons-chinese with GNU General Public License v2.0 4 votes vote down vote up
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
        if value.isPlusInfinity():
            return int2oct(0x40), 0
        if value.isMinusInfinity():
            return int2oct(0x41), 0
        m, b, e = value
        if not m:
            return null, 0
        if b == 10:
            return str2octs('\x03%dE%s%d' % (m, e == 0 and '+' or '', e)), 0
        elif b == 2:
            fo = 0x80                 # binary enoding
            if m < 0:
                fo = fo | 0x40  # sign bit
                m = -m
            while int(m) != m: # drop floating point
                m *= 2
                e -= 1
            while m & 0x1 == 0: # mantissa normalization
                m >>= 1
                e += 1
            eo = null
            while e not in (0, -1):
                eo = int2oct(e&0xff) + eo
                e >>= 8
            if e == 0 and eo and oct2int(eo[0]) & 0x80:
                eo = int2oct(0) + eo
            n = len(eo)
            if n > 0xff:
                raise error.PyAsn1Error('Real exponent overflow')
            if n == 1:
                pass
            elif n == 2:
                fo |= 1
            elif n == 3:
                fo |= 2
            else:
                fo |= 3
                eo = int2oct(n//0xff+1) + eo
            po = null
            while m:
                po = int2oct(m&0xff) + po
                m >>= 8
            substrate = int2oct(fo) + eo + po
            return substrate, 0
        else:
            raise error.PyAsn1Error('Prohibited Real base %s' % b) 
Example #25
Source File: encoder.py    From opsbro with MIT License 4 votes vote down vote up
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
        if value.isPlusInfinity():
            return int2oct(0x40), 0
        if value.isMinusInfinity():
            return int2oct(0x41), 0
        m, b, e = value
        if not m:
            return null, 0
        if b == 10:
            return str2octs('\x03%dE%s%d' % (m, e == 0 and '+' or '', e)), 0
        elif b == 2:
            fo = 0x80                 # binary enoding
            if m < 0:
                fo = fo | 0x40  # sign bit
                m = -m
            while int(m) != m: # drop floating point
                m *= 2
                e -= 1
            while m & 0x1 == 0: # mantissa normalization
                m >>= 1
                e += 1
            eo = null
            while e not in (0, -1):
                eo = int2oct(e&0xff) + eo
                e >>= 8
            if e == 0 and eo and oct2int(eo[0]) & 0x80:
                eo = int2oct(0) + eo
            n = len(eo)
            if n > 0xff:
                raise error.PyAsn1Error('Real exponent overflow')
            if n == 1:
                pass
            elif n == 2:
                fo |= 1
            elif n == 3:
                fo |= 2
            else:
                fo |= 3
                eo = int2oct(n//0xff+1) + eo
            po = null
            while m:
                po = int2oct(m&0xff) + po
                m >>= 8
            substrate = int2oct(fo) + eo + po
            return substrate, 0
        else:
            raise error.PyAsn1Error('Prohibited Real base %s' % b) 
Example #26
Source File: encoder.py    From nzb-subliminal with GNU General Public License v3.0 4 votes vote down vote up
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
        if value.isPlusInfinity():
            return int2oct(0x40), 0
        if value.isMinusInfinity():
            return int2oct(0x41), 0
        m, b, e = value
        if not m:
            return null, 0
        if b == 10:
            return str2octs('\x03%dE%s%d' % (m, e == 0 and '+' or '', e)), 0
        elif b == 2:
            fo = 0x80                 # binary enoding
            if m < 0:
                fo = fo | 0x40  # sign bit
                m = -m
            while int(m) != m: # drop floating point
                m *= 2
                e -= 1
            while m & 0x1 == 0: # mantissa normalization
                m >>= 1
                e += 1
            eo = null
            while e not in (0, -1):
                eo = int2oct(e&0xff) + eo
                e >>= 8
            if e == 0 and eo and oct2int(eo[0]) & 0x80:
                eo = int2oct(0) + eo
            n = len(eo)
            if n > 0xff:
                raise error.PyAsn1Error('Real exponent overflow')
            if n == 1:
                pass
            elif n == 2:
                fo |= 1
            elif n == 3:
                fo |= 2
            else:
                fo |= 3
                eo = int2oct(n//0xff+1) + eo
            po = null
            while m:
                po = int2oct(m&0xff) + po
                m >>= 8
            substrate = int2oct(fo) + eo + po
            return substrate, 0
        else:
            raise error.PyAsn1Error('Prohibited Real base %s' % b)