Import a private key.

    Write a private key to one of the slots on the YubiKey.

    \b
    SLOT        PIV slot to import the private key to.
    PRIVATE-KEY File containing the private key. Use '-' to use stdin.
777273
def import_key(
        ctx, slot, management_key, pin, private_key,
        pin_policy, touch_policy, password):
    
    dev = ctx.obj['dev']
    controller = ctx.obj['controller']
    _ensure_authenticated(ctx, controller, pin, management_key)

    data = private_key.read()

    while True:
        if password is not None:
            password = password.encode()
        try:
            private_key = parse_private_key(data, password)
        except (ValueError, TypeError):
            if password is None:
                password = click.prompt(
                    'Enter password to decrypt key',
                    default='', hide_input=True,
                    show_default=False,
                    err=True)
                continue
            else:
                password = None
                click.echo('Wrong password.')
            continue
        break

    if pin_policy:
        pin_policy = PIN_POLICY.from_string(pin_policy)
    if touch_policy:
        touch_policy = TOUCH_POLICY.from_string(touch_policy)

    _check_pin_policy(ctx, dev, controller, pin_policy)
    _check_touch_policy(ctx, controller, touch_policy)
    _check_key_size(ctx, controller, private_key)

    controller.import_key(
            slot,
            private_key,
            pin_policy,
            touch_policy)
985509
def key_create(options)
      ssh_key = key_generation(options)
      ssh_private_key_file = options[:private_key]
      ssh_public_key_file = "#{ssh_private_key_file}.pub"

      # TODO: - add to .fenton/config file
      File.write(ssh_private_key_file, ssh_key.private_key)
      File.chmod(0o600, ssh_private_key_file)
      File.write(ssh_public_key_file, ssh_key.ssh_public_key)
      File.chmod(0o600, ssh_public_key_file)

      [true, 'Key': ['creation failed']]
    end
40944
def __set_private_key(self, pk):
		
		self.__private_key = pk
		self.__public_key = pk.public_key()
1084671
def from_private_key(path: str) -> SigningKeyType:
        
        key = load_key(path)
        key.pubkey = Base58Encoder.encode(key.vk)
        return key
172225
function export_key($key, $fp = null, $include_private = false)
    {
        $this->load_pgp_driver();
        $result = $this->pgp_driver->export($key, $include_private, $this->get_passwords());

        if ($result instanceof enigma_error) {
            self::raise_error($result, __LINE__);
            return $result;
        }

        if ($fp) {
            fwrite($fp, $result);
        }
        else {
            return $result;
        }
    }
197513
private static PrivateKey loadPrivateKey(byte[] keyBytes) {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
                keyBytes);
        try {
            KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateKey = factory
                    .generatePrivate(pkcs8EncodedKeySpec);
            return privateKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
659114
def load_pem_private_key(data, password):
    """"""
    key = _serialization.load_pem_private_key(
        data, password, _backends.default_backend())
    return key
1320618
def privatekey_to_publickey(private_key_bin: bytes) -> bytes:
    
    if not ishash(private_key_bin):
        raise ValueError('private_key_bin format mismatch. maybe hex encoded?')
    return keys.PrivateKey(private_key_bin).public_key.to_bytes()
592850
def load_private_key(key_file, key_password=None):
    
    key_file = os.path.expanduser(key_file)
    key_file = os.path.abspath(key_file)

    if not key_password:
        with open(key_file, 'r') as key:
            return key.read()

    with open(key_file, 'rb') as key:
        key_bytes = key.read()
    return decrypt_key(key_bytes, key_password).decode(ENCODING)
1236944
def import_public_key(self, pem_text):
		
		if isinstance(pem_text, str) is True:
			pem_text = pem_text.encode()
		self.__set_public_key(
			serialization.load_pem_public_key(pem_text, backend=default_backend())
		)
224481
def dump_private_keys_or_addrs_chooser(wallet_obj):
    '''
    
    '''

    if wallet_obj.private_key:
        puts('Which private keys and addresses do you want?')
    else:
        puts('Which addresses do you want?')
    with indent(2):
        puts(colored.cyan('1: Active - have funds to spend'))
        puts(colored.cyan('2: Spent - no funds to spend (because they have been spent)'))
        puts(colored.cyan('3: Unused - no funds to spend (because the address has never been used)'))
        puts(colored.cyan('0: All (works offline) - regardless of whether they have funds to spend (super advanced users only)'))
        puts(colored.cyan('\nb: Go Back\n'))
    choice = choice_prompt(
            user_prompt=DEFAULT_PROMPT,
            acceptable_responses=[0, 1, 2, 3],
            default_input='1',
            show_default=True,
            quit_ok=True,
            )

    if choice is False:
        return

    if choice == '1':
        return dump_selected_keys_or_addrs(wallet_obj=wallet_obj, zero_balance=False, used=True)
    elif choice == '2':
        return dump_selected_keys_or_addrs(wallet_obj=wallet_obj, zero_balance=True, used=True)
    elif choice == '3':
        return dump_selected_keys_or_addrs(wallet_obj=wallet_obj, zero_balance=None, used=False)
    elif choice == '0':
        return dump_all_keys_or_addrs(wallet_obj=wallet_obj)
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
      }
    }
  }
}
329267
def import_keys(hsm, args):
    
    res = True

    # ykksm 1
    #123456,ftftftcccc,534543524554,fcacd309a20ce1809c2db257f0e8d6ea,000000000000,,,

    for line in sys.stdin:
        if line[0] == '#':
            continue

        l = line.split(',')
        modhex_id = l[1]
        uid = l[2].decode('hex')
        key = l[3].decode('hex')

        if modhex_id and uid and key:
            public_id = pyhsm.yubikey.modhex_decode(modhex_id)
            padded_id = modhex_id.rjust(args.public_id_chars, 'c')

        if int(public_id, 16) == 0:
            print "WARNING: Skipping import of key with public ID: %s" % (padded_id)
            print "This public ID is unsupported by the YubiHSM.\n"
            continue

        if args.verbose:
            print "  %s" % (padded_id)

        secret = pyhsm.aead_cmd.YHSM_YubiKeySecret(key, uid)
        hsm.load_secret(secret)

        for kh in args.key_handles.keys():
            if(args.random_nonce):
                nonce = ""
            else:
                nonce = public_id.decode('hex')
            aead = hsm.generate_aead(nonce, kh)

            if args.internal_db:
                if not store_in_internal_db(
                        args, hsm, modhex_id, public_id, kh, aead):
                    res = False
                continue

            filename = output_filename(
                args.output_dir, args.key_handles[kh], padded_id)

            if args.verbose:
                print "    %4s, %i bytes (%s) -> %s" % \
                    (args.key_handles[kh], len(aead.data), shorten_aead(aead), filename)

            aead.save(filename)

        if args.verbose:
            print ""

    if res:
        print "\nDone\n"
    else:
        print "\nDone (one or more entries rejected)"
    return res
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
19864
def gen_keys(hsm, args):
    

    if args.verbose:
        print "Generating %i keys :\n" % (args.count)
    else:
        print "Generating %i keys" % (args.count)

    for int_id in range(args.start_id, args.start_id + args.count):
        public_id = ("%x" % int_id).rjust(args.public_id_chars, '0')
        padded_id = pyhsm.yubikey.modhex_encode(public_id)

        if args.verbose:
            print "  %s" % (padded_id)

        num_bytes = len(pyhsm.aead_cmd.YHSM_YubiKeySecret('a' * 16, 'b' * 6).pack())
        hsm.load_random(num_bytes)
        for kh in args.key_handles.keys():
            if args.random_nonce:
                nonce = ""
            else:
                nonce = public_id.decode('hex')
            aead = hsm.generate_aead(nonce, kh)

            filename = output_filename(args.output_dir, args.key_handles[kh], padded_id)

            if args.verbose:
                print "    %4s, %i bytes (%s) -> %s" % \
                    (args.key_handles[kh], len(aead.data), shorten_aead(aead), filename)
            aead.save(filename)

        if args.verbose:
            print ""

    print "\nDone\n"
1066568
def import_public_key(line):
    """"""
    log.debug('loading SSH public key: %r', line)
    file_type, base64blob, name = line.split()
    blob = base64.b64decode(base64blob)
    result = parse_pubkey(blob)
    result['name'] = name.encode('utf-8')
    assert result['type'] == file_type.encode('ascii')
    log.debug('loaded %s public key: %s', file_type, result['fingerprint'])
    return result
1271587
private KeyPair loadKeyPair() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        // Read Private Key
        final File filePrivateKey = getKeyPath(KeyType.PRIVATE);

        // Read Public Key
        final File filePublicKey = getKeyPath(KeyType.PUBLIC);

        byte[] encodedPrivateKey;
        byte[] encodedPublicKey;

        try (InputStream pvtfis = Files.newInputStream(filePrivateKey.toPath());
             InputStream pubfis = Files.newInputStream(filePublicKey.toPath())) {

            encodedPrivateKey = new byte[(int) filePrivateKey.length()];
            pvtfis.read(encodedPrivateKey);

            encodedPublicKey = new byte[(int) filePublicKey.length()];
            pubfis.read(encodedPublicKey);
        }

        // Generate KeyPair
        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
        final PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
        final PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
        final PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

        return this.keyPair = new KeyPair(publicKey, privateKey);
    }