Ejemplo n.º 1
0
 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'))
Ejemplo n.º 2
0
	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')
Ejemplo n.º 3
0
 def testObjEncode4(self):
     # Implicit tags (constructed)
     der = DerObject(0x10, implicit=1, constructed=True)
     der.payload = b('ppll')
     self.assertEquals(der.encode(), b('\xa1\x04ppll'))
     # Implicit tags (primitive)
     der = DerObject(0x02, implicit=0x1E, constructed=False)
     der.payload = b('ppll')
     self.assertEquals(der.encode(), b('\x9E\x04ppll'))
Ejemplo n.º 4
0
 def testObjEncode1(self):
     # No payload
     der = DerObject(b('\x33'))
     self.assertEqual(der.encode(), b('\x33\x00'))
     # Small payload
     der.payload = b('\x45')
     self.assertEqual(der.encode(), b('\x33\x01\x45'))
     # Invariant
     self.assertEqual(der.encode(), b('\x33\x01\x45'))
     # Initialize with numerical tag
     der = DerObject(b(0x33))
     der.payload = b('\x45')
     self.assertEqual(der.encode(), b('\x33\x01\x45'))
Ejemplo n.º 5
0
 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'))
Ejemplo n.º 6
0
 def testObjEncode1(self):
     # No payload
     der = DerObject(b('\x02'))
     self.assertEquals(der.encode(), b('\x02\x00'))
     # Small payload (primitive)
     der.payload = b('\x45')
     self.assertEquals(der.encode(), b('\x02\x01\x45'))
     # Invariant
     self.assertEquals(der.encode(), b('\x02\x01\x45'))
     # Initialize with numerical tag
     der = DerObject(0x04)
     der.payload = b('\x45')
     self.assertEquals(der.encode(), b('\x04\x01\x45'))
     # Initialize with constructed type
     der = DerObject(b('\x10'), constructed=True)
     self.assertEquals(der.encode(), b('\x30\x00'))
Ejemplo n.º 7
0
 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'))
Ejemplo n.º 8
0
    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("")
Ejemplo n.º 9
0
	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("")
Ejemplo n.º 10
0
    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("")
Ejemplo n.º 11
0
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())
Ejemplo n.º 12
0
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())
Ejemplo n.º 13
0
 def testObjEncode5(self):
     # Encode type with explicit tag
     der = DerObject(0x10, explicit=5)
     der.payload = b("xxll")
     self.assertEqual(der.encode(), b("\xa5\x06\x10\x04xxll"))
Ejemplo n.º 14
0
	def testObjEncode2(self):
		# Known types
		der = DerObject('SEQUENCE')
		self.assertEquals(der.encode(), '\x30\x00')
		der = DerObject('BIT STRING')
		self.assertEquals(der.encode(), '\x03\x00')
Ejemplo n.º 15
0
 def testObjEncode2(self):
     # Initialize with payload
     der = DerObject(0x03, b('\x12\x12'))
     self.assertEqual(der.encode(), b('\x03\x02\x12\x12'))
Ejemplo n.º 16
0
 def testObjEncode3(self):
     # Long payload
     der = DerObject(b('\x10'))
     der.payload = b("0") * 128
     self.assertEquals(der.encode(), b('\x10\x81\x80' + "0" * 128))
Ejemplo n.º 17
0
 def testObjEncode2(self):
     # Initialize with payload
     der = DerObject(0x03, b('\x12\x12'))
     self.assertEquals(der.encode(), b('\x03\x02\x12\x12'))
Ejemplo n.º 18
0
 def testObjEncode3(self):
     # Long payload
     der = DerObject(b('\x10'))
     der.payload = b("0")*128
     self.assertEqual(der.encode(), b('\x10\x81\x80' + "0"*128))
Ejemplo n.º 19
0
    def exportKey(self, format='PEM', passphrase=None, pkcs=1):
        """Export this RSA key.

        :Parameter format: The format to use for wrapping the key.

            - *'DER'*. Binary encoding, always unencrypted.
            - *'PEM'*. Textual encoding, done according to `RFC1421`_/`RFC1423`_.
              Unencrypted (default) or encrypted.
            - *'OpenSSH'*. Textual encoding, done according to OpenSSH specification.
              Only suitable for public keys (not private keys).
        :Type format: string

        :Parameter passphrase: In case of PEM, the pass phrase to derive the encryption key from.
        :Type passphrase: string 

        :Parameter pkcs: The PKCS standard to follow for assembling the key.
         You have two choices:

          - with **1**, the public key is embedded into an X.509 `SubjectPublicKeyInfo` DER SEQUENCE.
            The private key is embedded into a `PKCS#1`_ `RSAPrivateKey` DER SEQUENCE.
            This mode is the default.
          - with **8**, the private key is embedded into a `PKCS#8`_ `PrivateKeyInfo` DER SEQUENCE.
            This mode is not available for public keys.

         PKCS standards are not relevant for the *OpenSSH* format.
        :Type pkcs: integer

        :Return: A byte string with the encoded public or private half.
        :Raise ValueError:
            When the format is unknown.

        .. _RFC1421:    http://www.ietf.org/rfc/rfc1421.txt
        .. _RFC1423:    http://www.ietf.org/rfc/rfc1423.txt
        .. _`PKCS#1`:   http://www.ietf.org/rfc/rfc3447.txt
        .. _`PKCS#8`:   http://www.ietf.org/rfc/rfc5208.txt
        """
        if passphrase is not None:
            passphrase = tobytes(passphrase)
        if format=='OpenSSH':
               eb = long_to_bytes(self.e)
               nb = long_to_bytes(self.n)
               if bord(eb[0]) & 0x80: eb=bchr(0x00)+eb
               if bord(nb[0]) & 0x80: nb=bchr(0x00)+nb
               keyparts = [ b('ssh-rsa'), eb, nb ]
               keystring = b('').join([ struct.pack(">I",len(kp))+kp for kp in keyparts])
               return b('ssh-rsa ')+binascii.b2a_base64(keystring)[:-1]

        # DER format is always used, even in case of PEM, which simply
        # encodes it into BASE64.
        der = DerSequence()
        if self.has_private():
                keyType= { 1: 'RSA PRIVATE', 8: 'PRIVATE' }[pkcs]
                der[:] = [ 0, self.n, self.e, self.d, self.p, self.q,
                           self.d % (self.p-1), self.d % (self.q-1),
                           inverse(self.q, self.p) ]
                if pkcs==8:
                    derkey = der.encode()
                    der = DerSequence([0])
                    der.append(algorithmIdentifier)
                    der.append(DerObject('OCTET STRING', derkey).encode())
        else:
                keyType = "PUBLIC"
                der.append(algorithmIdentifier)
                bitmap = DerObject('BIT STRING')
                derPK = DerSequence( [ self.n, self.e ] )
                bitmap.payload = bchr(0x00) + derPK.encode()
                der.append(bitmap.encode())
        if format=='DER':
                return der.encode()
        if format=='PEM':
                pem = b("-----BEGIN " + keyType + " KEY-----\n")
                objenc = None
                if passphrase and keyType.endswith('PRIVATE'):
                    # We only support 3DES for encryption
                    import Crypto.Hash.MD5
                    from Crypto.Cipher import DES3
                    from Crypto.Protocol.KDF import PBKDF1
                    salt = self._randfunc(8)
                    key =  PBKDF1(passphrase, salt, 16, 1, Crypto.Hash.MD5)
                    key += PBKDF1(key+passphrase, salt, 8, 1, Crypto.Hash.MD5)
                    objenc = DES3.new(key, Crypto.Cipher.DES3.MODE_CBC, salt)
                    pem += b('Proc-Type: 4,ENCRYPTED\n')
                    pem += b('DEK-Info: DES-EDE3-CBC,') + binascii.b2a_hex(salt).upper() + b('\n\n')
                
                binaryKey = der.encode()
                if objenc:
                    # Add PKCS#7-like padding
                    padding = objenc.block_size-len(binaryKey)%objenc.block_size
                    binaryKey = objenc.encrypt(binaryKey+bchr(padding)*padding)

                # 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 " + keyType + " KEY-----")
                return pem
        return ValueError("Unknown key format '%s'. Cannot export the RSA key." % format)
Ejemplo n.º 20
0
 def testObjEncode2(self):
     # Known types
     der = DerObject("SEQUENCE")
     self.assertEquals(der.encode(), b("\x30\x00"))
     der = DerObject("BIT STRING")
     self.assertEquals(der.encode(), b("\x03\x00"))
Ejemplo n.º 21
0
 def testObjEncode3(self):
     # Long payload
     der = DerObject(b("\x34"))
     der.payload = b("0") * 128
     self.assertEquals(der.encode(), b("\x34\x81\x80" + "0" * 128))
Ejemplo n.º 22
0
	def testObjEncode3(self):
		# Long payload
		der = DerObject('\x34')
		der.payload = "0"*128
		self.assertEquals(der.encode(), '\x34\x81\x80' + ("0"*128))		
Ejemplo n.º 23
0
 def testObjEncode5(self):
     # Encode type with explicit tag
     der = DerObject(0x10, explicit=5)
     der.payload = b("xxll")
     self.assertEqual(der.encode(), b("\xa5\x06\x10\x04xxll"))