当前位置: 首页>>代码示例>>Python>>正文


Python asn1.DerObject类代码示例

本文整理汇总了Python中Crypto.Util.asn1.DerObject的典型用法代码示例。如果您正苦于以下问题:Python DerObject类的具体用法?Python DerObject怎么用?Python DerObject使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了DerObject类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: exportKey

    def exportKey(self, format='PEM'):
        """Export the RSA key. A string is returned
        with the encoded public or the private half
        under the selected format.

        format:		'DER' (PKCS#1) or 'PEM' (RFC1421)
        """
        der = DerSequence()
        if self.has_private():
            keyType = "RSA PRIVATE"
            der[:] = [ 0, self.n, self.e, self.d, self.p, self.q,
                   self.d % (self.p-1), self.d % (self.q-1),
                   self.u ]
        else:
            keyType = "PUBLIC"
            der.append(b('\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01\x05\x00'))
            bitmap = DerObject('BIT STRING')
            derPK = DerSequence()
            derPK[:] = [ self.n, self.e ]
            bitmap.payload = b('\x00') + derPK.encode()
            der.append(bitmap.encode())
        if format=='DER':
            return der.encode()
        if format=='PEM':
            pem = b("-----BEGIN %s KEY-----\n" % keyType)
            binaryKey = der.encode()
            # Each BASE64 line can take up to 64 characters (=48 bytes of data)
            chunks = [ binascii.b2a_base64(binaryKey[i:i+48]) for i in range(0, len(binaryKey), 48) ]
            pem += b('').join(chunks)
            pem += b("-----END %s KEY-----" % keyType)
            return pem
        return ValueError("")
开发者ID:4ZM,项目名称:pycrypto,代码行数:32,代码来源:RSA.py

示例2: _importKeyDER

 def _importKeyDER(self, externKey):
     der = DerSequence()
     der.decode(externKey, True)
     if len(der)==9 and der.hasOnlyInts() and der[0]==0:
         # ASN.1 RSAPrivateKey element
         del der[6:]	# Remove d mod (p-1), d mod (q-1), and q^{-1} mod p
         der.append(inverse(der[4],der[5])) # Add p^{-1} mod q
         del der[0]	# Remove version
         return self.construct(der[:])
     if len(der)==2:
         # The DER object is a SEQUENCE with two elements:
         # a SubjectPublicKeyInfo SEQUENCE and an opaque BIT STRING.
         #
         # The first element is always the same:
         # 0x30 0x0D     SEQUENCE, 12 bytes of payload
         #   0x06 0x09   OBJECT IDENTIFIER, 9 bytes of payload
         #     0x2A 0x86 0x48 0x86 0xF7 0x0D 0x01 0x01 0x01
         #               rsaEncryption (1 2 840 113549 1 1 1) (PKCS #1)
         #   0x05 0x00   NULL
         #
         # The second encapsulates the actual ASN.1 RSAPublicKey element.
         if der[0]==b('\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01\x05\x00'):
             bitmap = DerObject()
             bitmap.decode(der[1], True)
             if bitmap.typeTag==b('\x03')[0] and bitmap.payload[0]==b('\x00')[0]:
                 der.decode(bitmap.payload[1:], True)
                 if len(der)==2 and der.hasOnlyInts():
                     return self.construct(der[:])
     raise ValueError("RSA key format is not supported")
开发者ID:GunioRobot,项目名称:pycrypto-1,代码行数:29,代码来源:RSA.py

示例3: exportKey

	def exportKey(self, format='PEM', public=False, type=None):
		"""Export the RSA key. A string is returned
		with the encoded public or the private half
		under the selected format.
		format: 'DER' (PKCS#1) or 'PEM' (RFC1421)
		"""
		if type == 'ssh-rsa' and public:
			return ''.join(binascii.b2a_base64('\x00\x00\x00\x07ssh-rsa\x00\x00\x00\x03' + '\x00\x00\x01\x01\x00'.join([long_to_bytes(self.e), long_to_bytes(self.n)])).split("\n"))
		
		der = DerSequence()
		if not public and self.has_private():
			keyType = "RSA PRIVATE"
			der[:] = [ 0, self.n, self.e, self.d, self.p, self.q,
				   self.d % (self.p-1), self.d % (self.q-1),
				   self.u ]
		else:
			keyType = "PUBLIC"
			der.append('\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01\x05\x00')
			bitmap = DerObject('BIT STRING')
			derPK = DerSequence()
			derPK[:] = [ self.n, self.e ]
			bitmap.payload = '\x00' + derPK.encode()
			der.append(bitmap.encode())
		if format=='DER':
			return der.encode()
		if format=='PEM':
			pem = "-----BEGIN %s KEY-----\n" % keyType
			binaryKey = der.encode()
			# Each BASE64 line can take up to 64 characters (=48 bytes of data)
			chunks = [ binascii.b2a_base64(binaryKey[i:i+48]) for i in range(0, len(binaryKey), 48) ]
			pem += ''.join(chunks)
			pem += "-----END %s KEY-----" % keyType
			return pem
		return ValueError("")
开发者ID:GunioRobot,项目名称:pycrypto,代码行数:34,代码来源:RSA.py

示例4: testObjEncode1

	def testObjEncode1(self):
		# No payload
		der = DerObject('\x33')
		self.assertEquals(der.encode(), '\x33\x00')
		# Small payload
		der.payload = '\x45'
		self.assertEquals(der.encode(), '\x33\x01\x45')
		# Invariant
		self.assertEquals(der.encode(), '\x33\x01\x45')
开发者ID:Acidburn0zzz,项目名称:KomodoEdit,代码行数:9,代码来源:test_asn1.py

示例5: exportKey

    def exportKey(self, format="PEM"):
        """Export the RSA key. A string is returned
        with the encoded public or the private half
        under the selected format.

        format:		'DER' (PKCS#1) or 'PEM' (RFC1421)
        """
        der = DerSequence()
        if self.has_private():
            keyType = "RSA PRIVATE"
            der[:] = [0, self.n, self.e, self.d, self.p, self.q, self.d % (self.p - 1), self.d % (self.q - 1), self.u]
        else:
            keyType = "PUBLIC"
            der.append("\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01\x05\x00")
            bitmap = DerObject("BIT STRING")
            derPK = DerSequence()
            derPK[:] = [self.n, self.e]
            bitmap.payload = "\x00" + derPK.encode()
            der.append(bitmap.encode())
        if format == "DER":
            return der.encode()
        if format == "PEM":
            pem = "-----BEGIN %s KEY-----\n" % keyType
            binaryKey = der.encode()
            # Each BASE64 line can take up to 64 characters (=48 bytes of data)
            chunks = []
            for i in range(0, len(binaryKey), 48):
                chunks.append(binascii.b2a_base64(binaryKey[i : i + 48]))
            pem += "".join(chunks)
            pem += "-----END %s KEY-----" % keyType
            return pem
        if format == "SSH":
            # Create public key.
            ssh_rsa = "00000007" + base64.b16encode("ssh-rsa")

            # Exponent.
            exponent = "%x" % (self.key.e,)
            if len(exponent) % 2:
                exponent = "0" + exponent

            ssh_rsa += "%08x" % (len(exponent) / 2,)
            ssh_rsa += exponent

            modulus = "%x" % (self.key.n,)
            if len(modulus) % 2:
                modulus = "0" + modulus

            if modulus[0] in "89abcdef":
                modulus = "00" + modulus

            ssh_rsa += "%08x" % (len(modulus) / 2,)
            ssh_rsa += modulus

            return "ssh-rsa %s" % (base64.b64encode(base64.b16decode(ssh_rsa.upper())),)

        return ValueError("")
开发者ID:jorgeecardona,项目名称:pycrypto,代码行数:56,代码来源:RSA.py

示例6: get_pubkey_ssh2_fingerprint

def get_pubkey_ssh2_fingerprint(pubkey):
    # This is the format that EC2 shows for public key fingerprints in its
    # KeyPair mgmt API
    if not pycrypto_available:
        raise RuntimeError('pycrypto is not available')
    k = importKey(pubkey)
    derPK = DerSequence([k.n, k.e])
    bitmap = DerObject('BIT STRING')
    bitmap.payload = bchr(0x00) + derPK.encode()
    der = DerSequence([algorithmIdentifier, bitmap.encode()])
    return _to_md5_fingerprint(der.encode())
开发者ID:kevin-zhangsen,项目名称:badam,代码行数:11,代码来源:publickey.py

示例7: testObjEncode1

 def testObjEncode1(self):
     # No payload
     der = DerObject(b('\x02'))
     self.assertEqual(der.encode(), b('\x02\x00'))
     # Small payload (primitive)
     der.payload = b('\x45')
     self.assertEqual(der.encode(), b('\x02\x01\x45'))
     # Invariant
     self.assertEqual(der.encode(), b('\x02\x01\x45'))
     # Initialize with numerical tag
     der = DerObject(0x04)
     der.payload = b('\x45')
     self.assertEqual(der.encode(), b('\x04\x01\x45'))
     # Initialize with constructed type
     der = DerObject(b('\x10'), constructed=True)
     self.assertEqual(der.encode(), b('\x30\x00'))
开发者ID:shubhanus,项目名称:taiga,代码行数:16,代码来源:test_asn1.py

示例8: _importKeyDER

 def _importKeyDER(self, externKey):
     der = DerSequence()
     der.decode(externKey, True)
     if len(der)==9 and der.hasOnlyInts() and der[0]==0:
         # ASN.1 RSAPrivateKey element
         del der[6:8]	# Remove d mod (p-1) and d mod (q-1)
         del der[0]	# Remove version
         return self.construct(der[:])
     if len(der)==2:
         # ASN.1 SubjectPublicKeyInfo element
         if der[0]==b('\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01\x05\x00'):
             bitmap = DerObject()
             bitmap.decode(der[1], True)
             if bitmap.typeTag==b('\x03')[0] and bitmap.payload[0]==b('\x00')[0]:
                 der.decode(bitmap.payload[1:], True)
                 if len(der)==2 and der.hasOnlyInts():
                     return self.construct(der[:])
     raise ValueError("RSA key format is not supported")
开发者ID:4ZM,项目名称:pycrypto,代码行数:18,代码来源:RSA.py

示例9: testObjEncode1

 def testObjEncode1(self):
     # No payload
     der = DerObject(b('\x33'))
     self.assertEquals(der.encode(), b('\x33\x00'))
     # Small payload
     der.payload = b('\x45')
     self.assertEquals(der.encode(), b('\x33\x01\x45'))
     # Invariant
     self.assertEquals(der.encode(), b('\x33\x01\x45'))
     # Initialize with numerical tag
     der = DerObject(b(0x33))
     der.payload = b('\x45')
     self.assertEquals(der.encode(), b('\x33\x01\x45'))
开发者ID:nessvm,项目名称:eVoting,代码行数:13,代码来源:test_asn1.py

示例10: testObjEncode4

 def testObjEncode4(self):
     # Implicit tags (constructed)
     der = DerObject(0x10, implicit=1, constructed=True)
     der.payload = b('ppll')
     self.assertEqual(der.encode(), b('\xa1\x04ppll'))
     # Implicit tags (primitive)
     der = DerObject(0x02, implicit=0x1E, constructed=False)
     der.payload = b('ppll')
     self.assertEqual(der.encode(), b('\x9E\x04ppll'))
开发者ID:shubhanus,项目名称:taiga,代码行数:9,代码来源:test_asn1.py

示例11: _importKeyDER

    def _importKeyDER(self, externKey):
        """Import an RSA key (public or private half), encoded in DER form."""

        try:

            der = DerSequence()
            der.decode(externKey, True)

            # Try PKCS#1 first, for a private key
            if len(der)==9 and der.hasOnlyInts() and der[0]==0:
                # ASN.1 RSAPrivateKey element
                del der[6:]     # Remove d mod (p-1), d mod (q-1), and q^{-1} mod p
                der.append(inverse(der[4],der[5])) # Add p^{-1} mod q
                del der[0]      # Remove version
                return self.construct(der[:])

            # Keep on trying PKCS#1, but now for a public key
            if len(der)==2:
                # The DER object is an RSAPublicKey SEQUENCE with two elements
                if der.hasOnlyInts():
                    return self.construct(der[:])
                # The DER object is a SubjectPublicKeyInfo SEQUENCE with two elements:
                # an 'algorithm' (or 'algorithmIdentifier') SEQUENCE and a 'subjectPublicKey' BIT STRING.
                # 'algorithm' takes the value given a few lines above.
                # 'subjectPublicKey' encapsulates the actual ASN.1 RSAPublicKey element.
                if der[0]==algorithmIdentifier:
                        bitmap = DerObject()
                        bitmap.decode(der[1], True)
                        if bitmap.isType('BIT STRING') and bord(bitmap.payload[0])==0x00:
                                der.decode(bitmap.payload[1:], True)
                                if len(der)==2 and der.hasOnlyInts():
                                        return self.construct(der[:])

            # Try unencrypted PKCS#8
            if der[0]==0:
                # The second element in the SEQUENCE is algorithmIdentifier.
                # It must say RSA (see above for description).
                if der[1]==algorithmIdentifier:
                    privateKey = DerObject()
                    privateKey.decode(der[2], True)
                    if privateKey.isType('OCTET STRING'):
                        return self._importKeyDER(privateKey.payload)

        except (ValueError, IndexError):
            pass

        raise ValueError("RSA key format is not supported")
开发者ID:5ant,项目名称:lantern,代码行数:47,代码来源:RSA.py

示例12: testObjDecode4

 def testObjDecode4(self):
     # Decode implicit tag (primitive)
     der = DerObject(0x02, constructed=False, implicit=0xF)
     self.assertRaises(ValueError, der.decode, b('\x02\x02\x01\x02'))
     der.decode(b('\x8F\x01\x00'))
     self.assertEqual(der.payload, b('\x00'))
     # Decode implicit tag (constructed)
     der = DerObject(0x02, constructed=True, implicit=0xF)
     self.assertRaises(ValueError, der.decode, b('\x02\x02\x01\x02'))
     der.decode(b('\xAF\x01\x00'))
     self.assertEqual(der.payload, b('\x00'))
开发者ID:shubhanus,项目名称:taiga,代码行数:11,代码来源:test_asn1.py

示例13: testObjDecode7

    def testObjDecode7(self):
        # Decode explicit tag
        der = DerObject(0x10, explicit=5)
        der.decode(b("\xa5\x06\x10\x04xxll"))
        self.assertEqual(der._tag_octet, 0x10)
        self.assertEqual(der.payload, b('xxll'))

        # Explicit tag may be 0
        der = DerObject(0x10, explicit=0)
        der.decode(b("\xa0\x06\x10\x04xxll"))
        self.assertEqual(der._tag_octet, 0x10)
        self.assertEqual(der.payload, b('xxll'))
开发者ID:shubhanus,项目名称:taiga,代码行数:12,代码来源:test_asn1.py

示例14: testObjDecode2

	def testObjDecode2(self):
		# Decode short payload
		der = DerObject()
		der.decode('\x22\x81\x80' + ("1"*128))
		self.assertEquals(der.payload, "1"*128)
		self.assertEquals(der.typeTag, "\x22")
开发者ID:Acidburn0zzz,项目名称:KomodoEdit,代码行数:6,代码来源:test_asn1.py

示例15: testObjEncode3

	def testObjEncode3(self):
		# Long payload
		der = DerObject('\x34')
		der.payload = "0"*128
		self.assertEquals(der.encode(), '\x34\x81\x80' + ("0"*128))		
开发者ID:Acidburn0zzz,项目名称:KomodoEdit,代码行数:5,代码来源:test_asn1.py


注:本文中的Crypto.Util.asn1.DerObject类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。