Load an RSA Public key PEM file
    :param str rsakeyfile: RSA public key PEM file to load
    :rtype: cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey
    :return: RSAPublicKey
350690
def load_rsa_public_key_file(rsakeyfile):
    # type: (str, str) ->
    #        cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey
    
    keypath = os.path.expandvars(os.path.expanduser(rsakeyfile))
    with open(keypath, 'rb') as keyfile:
        return cryptography.hazmat.primitives.serialization.\
            load_pem_public_key(
                keyfile.read(),
                backend=cryptography.hazmat.backends.default_backend()
            )
209463
def load_keys(path)
      file_lines = read_keys_file(path)

      keys = []
      file_lines.map do |l|
        components = LoginPolicy.parse_public_key(l)

        if components
          #preserve algorithm, key and comments; discard options (the 0th element)
          keys << [ components[1], components[2], components[3] ]
        elsif l =~ COMMENT
          next
        else
          RightScale::Log.error("Malformed (or not SSH2) entry in authorized_keys file: #{l}")
          next
        end
      end

      keys
    end
1035406
def app_public_key(self, id, **kwargs):
        ""
        api_path = "/api/v2/apps/{id}/public_key.pem"
        api_path = api_path.format(id=id)
        return self.call(api_path, **kwargs)
306749
def __load_file(self, key_list) -> str:
        
        file = str(key_list[0]) + self.extension
        key_list.pop(0)
        file_path = os.path.join(self.path, file)
        if os.path.exists(file_path):
            return Json.from_file(file_path)
        else:
            raise FileNotFoundError(file_path)
699239
def import_keys(self, keyspec):
        
        for where, spec in keyspec.items():
            if where == 'file':
                for typ, files in spec.items():
                    if typ == 'rsa':
                        for fil in files:
                            _key = RSAKey(
                                key=import_private_rsa_key_from_file(fil),
                                use='sig')
                            _kb = KeyBundle()
                            _kb.append(_key)
                            self.keyjar.add_kb('', _kb)
            elif where == 'url':
                for iss, url in spec.items():
                    kb = KeyBundle(source=url)
                    self.keyjar.add_kb(iss, kb)
362230
def export_public_key(self):
		
		if self.__public_key is None:
			raise ValueError('Unable to call this method. Public key must be set')

		return self.__public_key.public_bytes(
			encoding=serialization.Encoding.PEM,
			format=serialization.PublicFormat.SubjectPublicKeyInfo
		)
1028167
def load(self, record_key, secret_key=''):

        ''' 
            
        '''

        title = '%s.load' % self.__class__.__name__
    
    # validate inputs
        input_fields = {
            'record_key': record_key,
            'secret_key': secret_key
        }
        for key, value in input_fields.items():
            if value:
                object_title = '%s(%s=%s)' % (title, key, str(value))
                self.fields.validate(value, '.%s' % key, object_title)

    # verify permissions
        if not self.permissions_content:
            raise Exception('%s requires an access_token with file content permissions.' % title)
            
    # retrieve file id
        file_id, parent_id = self._get_id(record_key)
        if not file_id:
            raise Exception('%s(record_key=%s) does not exist.' % (title, record_key))
    
    # request file data
        try:
            record_data = self.drive.get_media(fileId=file_id).execute()
        except:
            raise DriveConnectionError(title)
    
    # retrieve data from response
    #     import io
    #     from googleapiclient.http import MediaIoBaseDownload
    #     file_header = io.BytesIO
    #     record_data = MediaIoBaseDownload(file_header, response)
    #     done = False
    #     while not done:
    #         status, done = record_data.next_chunk()
    
    # TODO export google document to other format
            
    # decrypt (if necessary)
        if secret_key:
            from labpack.encryption import cryptolab
            record_data = cryptolab.decrypt(record_data, secret_key)
    
        return record_data
536386
public static PublicKey decodePublicKey(String pemEncoded) throws Exception {
        pemEncoded = removeBeginEnd(pemEncoded);
        byte[] encodedBytes = Base64.getDecoder().decode(pemEncoded);

        X509EncodedKeySpec spec = new X509EncodedKeySpec(encodedBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(spec);
    }
798168
def _load_private_key(self, private_key, passphrase=None):
        
        key = None
        last_exception = None
        for pkey_class in (RSAKey, DSSKey):
            try:
                key = pkey_class.from_private_key(StringIO(private_key),
                    passphrase)
            except PasswordRequiredException as e:
                # The key file is encrypted and no passphrase was provided.
                # There's no point to continue trying
                raise
            except SSHException as e:
                last_exception = e
                continue
            else:
                break
        if key is None and last_exception:
            raise last_exception
        return key
1048026
public static RSAPublicKey getRSAPublicKeyFromPEM(Provider provider, String pem) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA", provider);
            return (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(getKeyBytesFromPEM(pem)));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("Algorithm SHA256withRSA is not available", e);
        } catch (InvalidKeySpecException e) {
            throw new IllegalArgumentException("Invalid PEM provided", e);
        }
    }
181025
def create_binary_security_token(key_file):
    
    node = etree.Element(
        ns_id('BinarySecurityToken', ns.wssens),
        nsmap={ns.wssens[0]: ns.wssens[1]})
    node.set(ns_id('Id', ns.wsuns), get_unique_id())
    node.set('EncodingType', ns.wssns[1] + 'Base64Binary')
    node.set('ValueType', BINARY_TOKEN_TYPE)

    with open(key_file) as fh:
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, fh.read())
        node.text = base64.b64encode(
            crypto.dump_certificate(crypto.FILETYPE_ASN1, cert))
    return node
705429
def key_from_keyfile(keyfile):
    
    if hasattr(keyfile, 'read'):
        buf = keyfile.read()
    else:
        # Assume it is a filename and open it to read contents.
        with open(keyfile, 'rb') as fp:
            buf = fp.read()
            
    sha = SHA256.new()
    if len(buf) == 33:
        sha.update(buf)
        return sha.digest()
    elif len(buf) == 65:
        sha.update(struct.unpack('<65s', buf)[0].decode())
        return sha.digest()
    else:
        # This chunked updating of the sha is probably not really necessary
        while buf:
            if len(buf) <= 2049:
                sha.update(buf)
                buf = ''
            else:
                sha.update(buf[:2048])
                buf = buf[2048:]
        return sha.digest()
934252
def load_pem(cls, private_key, password=None):
        
        # TODO(sam): try to break this in tests
        maybe_path = normpath(private_key)
        if os.path.isfile(maybe_path):
            with open(maybe_path, 'rb') as pkf:
                private_key = pkf.read()
        if not isinstance(private_key, six.binary_type):
            private_key = private_key.encode('utf-8')

        pkey = serialization.load_pem_private_key(
            private_key,
            password=password,
            backend=crypto_backends.default_backend())
        return cls(pkey)
1057213
def load_signing_key(signing_key, crypto_backend=default_backend()):
    
    if isinstance(signing_key, EllipticCurvePrivateKey):
        return signing_key

    elif isinstance(signing_key, (str, unicode)):
        invalid_strings = [b'-----BEGIN PUBLIC KEY-----']
        invalid_string_matches = [
            string_value in signing_key
            for string_value in invalid_strings
        ]
        if any(invalid_string_matches):
            raise ValueError(
                'Signing key must be a private key, not a public key.')

        if is_hex(signing_key):
            try:
                private_key_pem = ECPrivateKey(signing_key).to_pem()
            except:
                pass
            else:
                try:
                    return load_pem_private_key(
                        private_key_pem, password=None, backend=crypto_backend)
                except:
                    raise InvalidPrivateKeyError()

            try:
                return load_der_private_key(
                    signing_key, password=None, backend=crypto_backend)
            except Exception as e:
                traceback.print_exc()
                raise InvalidPrivateKeyError()
        else:
            try:
                return load_pem_private_key(
                    signing_key, password=None, backend=crypto_backend)
            except:
                raise InvalidPrivateKeyError()
    else:
        raise ValueError('Signing key must be in string or unicode format.')
62350
def load(self, filename):
        
        # Compute sha1 hash (key)
        with open(filename) as fp:
            key = sha1(fp.read()).hexdigest()
        path = self.key_to_path(key)
        # Return the cached file if available
        if key in self.hashes:
            try:
                with open(path) as fp:
                    return cPickle.load(fp)
            except EOFError:
                os.unlink(path)
                self.hashes.remove(key)
            except IOError:
                self.hashes.remove(key)
        # Create the nested cache directory
        try:
            os.makedirs(os.path.dirname(path))
        except OSError as exc:
            if exc.errno != errno.EEXIST:
                raise
        # Process the file and save in the cache
        scratch = kurt.Project.load(filename)  # can fail
        with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT,
                               0400), 'w') as fp:
            # open file for writing but make it immediately read-only
            cPickle.dump(scratch, fp, cPickle.HIGHEST_PROTOCOL)
        self.hashes.add(key)
        return scratch
118112
def load_rsa_key(rsa_keypath)
      File.open(rsa_keypath, 'r') do |file|
        rsa_key = nil
        rsa_key = [file.read]
        if !rsa_key.nil?
          FastlaneCore::UI.success('Successfully loaded RSA key...')
        else
          FastlaneCore::UI.user_error!('Failed to load RSA key...')
        end
        rsa_key
      end
    end
520074
def load_pkcs12(self, key):
        
        self.x509 = key.get_certificate().to_cryptography()
        self.public_key = key.get_certificate().to_cryptography().public_key()
        self.private_key = key.get_privatekey().to_cryptography_key()