Load private key contents from root directory
193831
protected function loadPrivateKey($key)
    {
        if (app()->runningUnitTests()) {
            return '===FAKE-KEY===';
        }

        // If it's a relative path, start searching in the
        // project root
        if ($key[0] !== '/') {
            $key = base_path().'/'.$key;
        }

        return file_get_contents($key);
    }
620753
def load_private_key(self, priv_key):
        """"""
        with open(priv_key) as fd:
            self._private_key = paramiko.RSAKey.from_private_key(fd)
330668
def from_der_private_key(data: bytes, password: Optional[str] = None) -> _RSAPrivateKey:
        
        return serialization.load_der_private_key(data, password, default_backend())
1080196
function loadKeyPair (pub, prv, use) {
  var pubPEM, prvPEM, pubJWK

  try {
    pubPEM = fs.readFileSync(pub).toString('ascii')
  } catch (e) {
    throw new Error('Unable to read the public key from ' + pub)
  }

  try {
    prvPEM = fs.readFileSync(prv).toString('ascii')
  } catch (e) {
    throw new Error('Unable to read the private key from ' + pub)
  }

  try {
    pubJWK = pemjwk.pem2jwk(pubPEM)
  } catch (e) {
    throw new Error('Unable to convert the public key ' + pub + ' to a JWK')
  }

  return {
    pem: {
      pub: pubPEM,
      prv: prvPEM
    },
    jwk: {
      pub: {
        kty: pubJWK.kty,
        use: use,
        alg: 'RS256',
        n: pubJWK.n,
        e: pubJWK.e
      }
    }
  }
}
1299865
def from_directory(cls, directory):
        """"""
        cert_path = os.path.join(directory, 'skein.crt')
        key_path = os.path.join(directory, 'skein.pem')
        for path, name in [(cert_path, 'cert'), (key_path, 'key')]:
            if not os.path.exists(path):
                raise context.FileNotFoundError(
                    "Security %s file not found at %r" % (name, path)
                )
        return Security(cert_file=cert_path, key_file=key_path)
93255
def __get_keys(self, name='master', passphrase=None):
        '''
        
        '''
        path = os.path.join(self.opts['pki_dir'],
                            name + '.pem')
        if not os.path.exists(path):
            log.info('Generating %s keys: %s', name, self.opts['pki_dir'])
            gen_keys(self.opts['pki_dir'],
                     name,
                     self.opts['keysize'],
                     self.opts.get('user'),
                     passphrase)
        if HAS_M2:
            key_error = RSA.RSAError
        else:
            key_error = ValueError
        try:
            key = get_rsa_key(path, passphrase)
        except key_error as e:
            message = 'Unable to read key: {0}; passphrase may be incorrect'.format(path)
            log.error(message)
            raise MasterExit(message)
        log.debug('Loaded %s key: %s', name, path)
        return key
107995
def load(path: str) -> "Store":
        """"""
        # load source (decrypting if necessary)
        if _gpg.is_encrypted(path):
            src_bytes = _gpg.decrypt(path)
        else:
            src_bytes = open(path, "rb").read()
        src = src_bytes.decode("utf-8")

        # parse database source
        ext = _gpg.unencrypted_ext(path)
        assert ext not in [
            ".yml",
            ".yaml",
        ], "YAML support was removed in version 0.12.0"
        entries = _parse_entries(src)

        return Store(path, entries)
1360814
def open(cls, blob, username, password):
        """"""
        return cls(blob, blob.encryption_key(username, password))
275414
function extractReadableKeys (dir, options) {
  const pwd = options.input
  prompt.start()
  prompt.get(promptSchema, (err, { password }) => {
    const key = fs.readFileSync(path.join(pwd, dir, 'sign_key'))
    const pubKey = fs.readFileSync(path.join(pwd, dir, 'sign_key.pub'))

    const decrypted = Crypto.decryptPrivateKey(password, key)

    const privateHex = Buffer.from(decrypted).toString('hex')
    const decryptedPub = Crypto.decryptPubKey(password, pubKey)

    console.log(`Private key (hex): ${privateHex}`)
    console.log(`Public key (base check): ak_${Crypto.encodeBase58Check(decryptedPub)}`)
    console.log(`Public key (hex): ${decryptedPub.toString('hex')}`)
  })
}
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
804606
def load(keystorerc=None, keystore=None, copyto=None, verbose=False):
  ''''''

  config = None
  if keystorerc:
    config = config_reader.read(keystorerc)
    if not config:
      print('No configuration found.', file=sys.stderr)
      sys.exit(-1)
  elif keystore:
    config = {
      'keystore': keystore,
      'files': []
    }

  if 'verbose' in config and config['verbose']:
    verbose = True

  keystore_path = None
  if 'keystore' not in config:
    print('.keystorerc needs to specify a keystore file path.', file=sys.stderr)
    sys.exit(-1)
  elif not pathlib.Path(os.path.expanduser(config['keystore'])).is_file():
    # If keystore file does not exist, nothing to load and exits
    print('keystore does not exist: {}'.format(config['keystore']), file=sys.stderr)
    sys.exit(-1)
  else:
    keystore_path = config['keystore']

  if copyto and not pathlib.Path(os.path.expanduser(copyto)).is_dir():
    print('The folder to copy to does not exist: {}'.format(copyto), file=sys.stderr)
    sys.exit(-1)

  # load and attempt to unencrypt keystore by passphrase

  encrypted_keystore = None
  try:
    with open(os.path.expanduser(keystore_path), 'rb') as keystore_file:
      encrypted_keystore = keystore_file.read()

    if verbose: print('Located encrypted keystore at {}.'.format(keystore_path))

    decrypted = False
    decrypted_keystore = None
    while not decrypted:
      try:
        passphrase = getpass.getpass('Please enter the passphrase: ')
        decrypted_keystore = simplecrypt.decrypt(passphrase, encrypted_keystore)
        decrypted = True
      except simplecrypt.DecryptionException as err:
        print('Invalid passphrase. Please try again.')
      except UnicodeDecodeError as err:
        print('Keyring cannot be decrypted.\nError: {}'.format(err), file=sys.stderr)
        sys.exit(-1)

  except OSError as err:
    print('keystore cannot be opened: {}'.format(err), file=sys.stderr)
    sys.exit(-1)

  # attempt to uncompress the keystore

  decompressed_keystore = gzip.decompress(decrypted_keystore)

  # attempt to unserialise the keystore

  try:
    keystore = json.loads(decompressed_keystore)
  except json.decoder.JSONDecodeError as err:
    print('Please contact the author about this as this is a serious problem. {}'.format(err), file=sys.stderr)
    sys.exit(-1)

  if verbose: print('Keystore decrypted successfully.')

  count = 0
  for filepath, key in keystore.items():
    expanded_filepath = os.path.expanduser(filepath)
    if copyto:
      expanded_filepath = os.path.join(copyto, os.path.basename(filepath))

    confirmed = False
    overwrite = False
    if not pathlib.Path(expanded_filepath).exists():
      confirmed = True
      overwrite = True

    while not confirmed:
      overwrite = input('File {} exists. Are you sure you want to overwrite? (y)/n: '.format(expanded_filepath))
      if overwrite == '' or overwrite == 'y' or overwrite == 'Y':
        overwrite = True
        confirmed = True
      elif overwrite == 'n' or overwrite == 'N':
        overwrite = False
        confirmed = True
      else:
        print('Please enter y or n.')
    if not overwrite:
      continue

    # key ready to be created
    if verbose: print('Writing key to {} ...'.format(expanded_filepath))
    try:
      with open(expanded_filepath, 'wb') as keyfile:
        b64_decoded = base64.decodebytes(key.encode('utf-8'))
        keyfile.write(b64_decoded)
      count += 1
    except OSError as err:
      print('File system threw an error: {}'.format(err), file=sys.stderr)
      print('Skipping {}'.format(expanded_filepath))

  if verbose: print('Keystore restored {} keys.'.format(count))
1335520
def accept_key(pki_dir, pub, id_):
    '''
    
    '''
    for key_dir in 'minions', 'minions_pre', 'minions_rejected':
        key_path = os.path.join(pki_dir, key_dir)
        if not os.path.exists(key_path):
            os.makedirs(key_path)

    key = os.path.join(pki_dir, 'minions', id_)
    with salt.utils.files.fopen(key, 'w+') as fp_:
        fp_.write(salt.utils.stringutils.to_str(pub))

    oldkey = os.path.join(pki_dir, 'minions_pre', id_)
    if os.path.isfile(oldkey):
        with salt.utils.files.fopen(oldkey) as fp_:
            if fp_.read() == pub:
                os.remove(oldkey)
247958
def load_key(self, key, key_type, key_encoding):
        
        if key_type not in (EncryptionKeyType.PRIVATE, EncryptionKeyType.PUBLIC):
            raise ValueError(
                'Invalid key type "{key_type}" for cipher "{cipher}"'.format(key_type=key_type, cipher=self.java_name)
            )

        if key_encoding not in (KeyEncodingType.DER, KeyEncodingType.PEM):
            raise ValueError(
                'Invalid key encoding "{key_encoding}" for cipher "{cipher}"'.format(
                    key_encoding=key_encoding, cipher=self.java_name
                )
            )

        return _KEY_LOADERS[self.cipher](key, key_type, key_encoding)
908225
def generate_public_ssh_key(ssh_private_key_file):
    """"""
    try:
        with open(ssh_private_key_file, "rb") as key_file:
            key = key_file.read()
    except FileNotFoundError:
        raise IpaUtilsException(
            'SSH private key file: %s cannot be found.' % ssh_private_key_file
        )

    try:
        private_key = serialization.load_pem_private_key(
            key,
            password=None,
            backend=default_backend()
        )
    except ValueError:
        raise IpaUtilsException(
            'SSH private key file: %s is not a valid key file.'
            % ssh_private_key_file
        )

    return private_key.public_key().public_bytes(
        serialization.Encoding.OpenSSH,
        serialization.PublicFormat.OpenSSH
    )
1278976
def key_file_private(self):
        '''
        '''
        if not hasattr(self, '_key_file_private'):
            self.key_file_private = '~/.ssh/{key}'.format(key=self.key_name)
        return self._key_file_private
831684
def _get_private_key(cls, private_key_path, private_key_passphrase):
        """"""
        if private_key_path is None or private_key_passphrase is None:
            return None

        with open(private_key_path, 'rb') as key:
            p_key = serialization.load_pem_private_key(
                key.read(),
                password=private_key_passphrase.encode(),
                backend=default_backend())

        return p_key.private_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption())
1003839
def load_key(key_str, key_pass):
        

        try:
            # First try to parse as a p12 file
            key, cert, _ = asymmetric.load_pkcs12(key_str, key_pass)
        except ValueError as e:
            # If it fails due to invalid password raise error here
            if e.args[0] == 'Password provided is invalid':
                raise AS2Exception('Password not valid for Private Key.')

            # if not try to parse as a pem file
            key, cert = None, None
            for kc in split_pem(key_str):
                try:
                    cert = asymmetric.load_certificate(kc)
                except (ValueError, TypeError):
                    try:
                        key = asymmetric.load_private_key(kc, key_pass)
                    except OSError:
                        raise AS2Exception(
                            'Invalid Private Key or password is not correct.')

        if not key or not cert:
            raise AS2Exception(
                'Invalid Private key file or Public key not included.')

        return key, cert