Python cryptography.hazmat.primitives.serialization.load_ssh_public_key() Examples

The following are 11 code examples of cryptography.hazmat.primitives.serialization.load_ssh_public_key(). 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 cryptography.hazmat.primitives.serialization , or try the search function .
Example #1
Source File: SupergirlOnCrypt.py    From SupergirlOnCrypt with Do What The F*ck You Want To Public License 6 votes vote down vote up
def encryptClientPrivKey(priv_key):
    """Encrypt the Clients private key (given as a str) with the servers public key"""
    with open(_helper.path('res/server.public.key'), "rb") as key_file:
        public_key = serialization.load_ssh_public_key(
            key_file.read(),
            backend=default_backend()
        )
        key_file.close()

    cipher = public_key.encrypt(
        bytes(priv_key, 'utf-8'),
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA1(),
            label=None
        )
    )
    _helper.info("Private Client Key is encrypted")
    return cipher 
Example #2
Source File: models.py    From asymmetric-jwt-auth with ISC License 6 votes vote down vote up
def validate_public_key(value):
    """
    Check that the given value is a valid RSA Public key in either PEM or OpenSSH format. If it is invalid,
    raises ``django.core.exceptions.ValidationError``.
    """
    is_valid = False
    exc = None

    for load in (load_pem_public_key, load_ssh_public_key):
        if not is_valid:
            try:
                load(value.encode('utf-8'), default_backend())
                is_valid = True
            except Exception as e:
                exc = e

    if not is_valid:
        raise ValidationError('Public key is invalid: %s' % exc) 
Example #3
Source File: sshkeys.py    From ToonRooter with MIT License 5 votes vote down vote up
def check_public_key(data):
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.backends import default_backend
    try:
        key = serialization.load_ssh_public_key(
            data, default_backend())
        return True
    except:
        return False 
Example #4
Source File: test_gpg.py    From securesystemslib with MIT License 5 votes vote down vote up
def test_export_pubkey(self):
    """ export a public key and make sure the parameters are the right ones:

      since there's very little we can do to check rsa key parameters are right
      we pre-exported the public key to an ssh key, which we can load with
      cryptography for the sake of comparison """

    # export our gpg key, using our functions
    key_data = export_pubkey(self.default_keyid, homedir=self.gnupg_home)
    our_exported_key = rsa_create_pubkey(key_data)

    # load the equivalent ssh key, and make sure that we get the same RSA key
    # parameters
    ssh_key_basename = "{}.ssh".format(self.default_keyid)
    ssh_key_path = os.path.join(self.gnupg_home, ssh_key_basename)
    with open(ssh_key_path, "rb") as fp:
      keydata = fp.read()

    ssh_key = serialization.load_ssh_public_key(keydata,
        backends.default_backend())

    self.assertEqual(ssh_key.public_numbers().n,
        our_exported_key.public_numbers().n)
    self.assertEqual(ssh_key.public_numbers().e,
        our_exported_key.public_numbers().e)

    subkey_keyids = list(key_data["subkeys"].keys())
    # We export the whole master key bundle which must contain the subkeys
    self.assertTrue(self.signing_subkey_keyid.lower() in subkey_keyids)
    # Currently we do not exclude encryption subkeys
    self.assertTrue(self.encryption_subkey_keyid.lower() in subkey_keyids)
    # However we do exclude subkeys, whose algorithm we do not support
    self.assertFalse(self.unsupported_subkey_keyid.lower() in subkey_keyids)

    # When passing the subkey keyid we also export the whole keybundle
    key_data2 = export_pubkey(self.signing_subkey_keyid,
        homedir=self.gnupg_home)
    self.assertDictEqual(key_data, key_data2) 
Example #5
Source File: test_gpg.py    From securesystemslib with MIT License 5 votes vote down vote up
def test_export_pubkey(self):
    """ export a public key and make sure the parameters are the right ones:

      since there's very little we can do to check rsa key parameters are right
      we pre-exported the public key to an ssh key, which we can load with
      cryptography for the sake of comparison """

    # export our gpg key, using our functions
    key_data = export_pubkey(self.default_keyid, homedir=self.gnupg_home)
    our_exported_key = dsa_create_pubkey(key_data)

    # load the equivalent ssh key, and make sure that we get the same RSA key
    # parameters
    ssh_key_basename = "{}.ssh".format(self.default_keyid)
    ssh_key_path = os.path.join(self.gnupg_home, ssh_key_basename)
    with open(ssh_key_path, "rb") as fp:
      keydata = fp.read()

    ssh_key = serialization.load_ssh_public_key(keydata,
        backends.default_backend())

    self.assertEqual(ssh_key.public_numbers().y,
        our_exported_key.public_numbers().y)
    self.assertEqual(ssh_key.public_numbers().parameter_numbers.g,
        our_exported_key.public_numbers().parameter_numbers.g)
    self.assertEqual(ssh_key.public_numbers().parameter_numbers.q,
        our_exported_key.public_numbers().parameter_numbers.q)
    self.assertEqual(ssh_key.public_numbers().parameter_numbers.p,
        our_exported_key.public_numbers().parameter_numbers.p) 
Example #6
Source File: rsa_public_key.py    From bless with Apache License 2.0 5 votes vote down vote up
def __init__(self, ssh_public_key):
        """
        Extracts the useful RSA Public Key information from an SSH Public Key file.
        :param ssh_public_key: SSH Public Key file contents. (i.e. 'ssh-rsa AAAAB3NzaC1yc2E..').
        """
        super(RSAPublicKey, self).__init__()

        self.type = SSHPublicKeyType.RSA

        split_ssh_public_key = ssh_public_key.split(' ')
        split_key_len = len(split_ssh_public_key)

        # is there a key comment at the end?
        if split_key_len > 2:
            self.key_comment = ' '.join(split_ssh_public_key[2:])
        else:
            self.key_comment = ''

        public_key = serialization.load_ssh_public_key(ssh_public_key.encode('ascii'), default_backend())
        ca_pub_numbers = public_key.public_numbers()
        if not isinstance(ca_pub_numbers, RSAPublicNumbers):
            raise TypeError("Public Key is not the correct type or format")

        self.key_size = public_key.key_size
        self.e = ca_pub_numbers.e
        self.n = ca_pub_numbers.n

        key_bytes = base64.b64decode(split_ssh_public_key[1])
        fingerprint = hashlib.md5(key_bytes).hexdigest()

        self.fingerprint = 'RSA ' + ':'.join(
            fingerprint[i:i + 2] for i in range(0, len(fingerprint), 2)) 
Example #7
Source File: validators.py    From refstack with Apache License 2.0 5 votes vote down vote up
def validate(self, request):
        """Validate uploaded test results."""
        super(TestResultValidator, self).validate(request)
        if request.headers.get('X-Signature') or \
                request.headers.get('X-Public-Key'):
            try:
                sign = binascii.a2b_hex(request.headers.get('X-Signature', ''))
            except (binascii.Error, TypeError) as e:
                raise api_exc.ValidationError('Malformed signature', e)

            try:
                key = load_ssh_public_key(
                    request.headers.get('X-Public-Key', ''),
                    backend=backends.default_backend()
                )
            except (binascii.Error, ValueError) as e:
                raise api_exc.ValidationError('Malformed public key', e)

            verifier = key.verifier(sign, padding.PKCS1v15(), hashes.SHA256())
            verifier.update(request.body)
            try:
                verifier.verify()
            except InvalidSignature:
                raise api_exc.ValidationError('Signature verification failed')
        if self._is_empty_result(request):
            raise api_exc.ValidationError('Uploaded results must contain at '
                                          'least one passing test.') 
Example #8
Source File: validators.py    From refstack with Apache License 2.0 5 votes vote down vote up
def validate(self, request):
        """Validate uploaded test results."""
        super(PubkeyValidator, self).validate(request)
        body = json.loads(request.body.decode('utf-8'))
        key_format = body['raw_key'].strip().split()[0]

        if key_format not in ('ssh-dss', 'ssh-rsa',
                              'pgp-sign-rsa', 'pgp-sign-dss'):
            raise api_exc.ValidationError('Public key has unsupported format')

        try:
            sign = binascii.a2b_hex(body['self_signature'])
        except (binascii.Error, TypeError) as e:
            raise api_exc.ValidationError('Malformed signature', e)

        try:
            key = load_ssh_public_key(body['raw_key'].encode('utf-8'),
                                      backend=backends.default_backend())
        except (binascii.Error, ValueError) as e:
            raise api_exc.ValidationError('Malformed public key', e)

        verifier = key.verifier(sign, padding.PKCS1v15(), hashes.SHA256())
        verifier.update('signature'.encode('utf-8'))
        try:
            verifier.verify()
        except InvalidSignature:
            raise api_exc.ValidationError('Signature verification failed') 
Example #9
Source File: detect.py    From roca with MIT License 4 votes vote down vote up
def process_ssh_line(self, data, name, idx):
        """
        Processes single SSH key
        :param data:
        :param name:
        :param idx:
        :return:
        """
        data = data.strip()
        if not contains(data, 'ssh-rsa'):
            return

        # strip ssh params / adjustments
        try:
            data = data[to_bytes(data).find(b'ssh-rsa'):]
        except Exception as e:
            pass

        from cryptography.hazmat.primitives.serialization import load_ssh_public_key
        from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
        try:
            key_obj = load_ssh_public_key(data, self.get_backend())
            self.num_ssh += 1

            if not isinstance(key_obj, RSAPublicKey):
                return

            self.num_rsa += 1
            numbers = key_obj.public_numbers()

            js = collections.OrderedDict()
            js['type'] = 'ssh-rsa'
            js['fname'] = name
            js['idx'] = idx
            js['e'] = '0x%x' % numbers.e
            js['n'] = '0x%x' % numbers.n
            js['ssh'] = data

            if self.has_fingerprint(numbers.n):
                logger.warning('Fingerprint found in the SSH key %s idx %s ' % (name, idx))
                self.mark_and_add_effort(numbers.n, js)

                if self.do_print:
                    print(json.dumps(js))

            return TestResult(js)

        except Exception as e:
            logger.debug('Exception in processing SSH public key %s idx %s : %s' % (name, idx, e))
            self.trace_logger.log(e) 
Example #10
Source File: FileCrypter.py    From SupergirlOnCrypt with Do What The F*ck You Want To Public License 4 votes vote down vote up
def encrypt_file(self, file_name, client_pub_key):
        if not os.path.isfile(file_name):
            return

        #calculate the MAX_SIZE in GB
        file_size = os.path.getsize(file_name) * 0.000000001
        if file_size > Config.MAX_SIZE_LIMIT:
            return

        public_key = serialization.load_ssh_public_key(
            bytes(client_pub_key, 'utf-8'),
            backend=default_backend()
        )

        #write the AES encryption key into a seperate file
        keyb64 = base64.b64encode(self.key)
        ivb64 = base64.b64encode(self.iv)
        t = bytes(keyb64.decode(self.encoding) + ";" + ivb64.decode(self.encoding), self.encoding)

        cipher = public_key.encrypt(
            t,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA1(),
                label=None
            )
        )

        cipher = base64.b64encode(cipher)


        with open(file_name, 'rb') as fo:
            plaintext = fo.read()

        enc = self.encrypt(plaintext, self.key)

        with open(file_name + ".supergirl", 'wb') as fo:
            fo.write(enc)

        with open(file_name + ".kryptonian", 'wb') as info:
            info.write(cipher)
        os.remove(file_name) 
Example #11
Source File: utils.py    From refstack with Apache License 2.0 4 votes vote down vote up
def decode_token(request):
    """Validate request signature.

    ValidationError rises if request is not valid.
    """
    if not request.headers.get(const.JWT_TOKEN_HEADER):
        return
    try:
        auth_schema, token = request.headers.get(
            const.JWT_TOKEN_HEADER).split(' ', 1)
    except ValueError:
        raise api_exc.ValidationError("Token is not valid")
    if auth_schema != 'Bearer':
        raise api_exc.ValidationError(
            "Authorization schema 'Bearer' should be used")
    try:
        token_data = jwt.decode(token, algorithms='RS256', verify=False)
    except jwt.InvalidTokenError:
        raise api_exc.ValidationError("Token is not valid")

    openid = token_data.get(const.USER_OPENID)
    if not openid:
        raise api_exc.ValidationError("Token does not contain user's openid")
    pubkeys = db.get_user_pubkeys(openid)
    for pubkey in pubkeys:
        try:
            pubkey_string = '%s %s' % (pubkey['format'], pubkey['pubkey'])
            pubkey_obj = serialization.load_ssh_public_key(
                pubkey_string.encode('utf-8'),
                backend=backends.default_backend()
            )
            pem_pubkey = pubkey_obj.public_bytes(
                serialization.Encoding.PEM,
                serialization.PublicFormat.SubjectPublicKeyInfo)
        except (ValueError, IndexError, TypeError, binascii.Error):
            pass
        else:
            try:
                token_data = jwt.decode(
                    token, key=pem_pubkey,
                    options={'verify_signature': True,
                             'verify_exp': True,
                             'require_exp': True},
                    leeway=const.JWT_VALIDATION_LEEWAY)
                # NOTE(sslipushenko) If at least one key is valid, let
                # the validation pass
                return token_data
            except jwt.InvalidTokenError:
                pass

    # NOTE(sslipushenko) If all user's keys are not valid, the validation fails
    raise api_exc.ValidationError("Token is not valid")