Manage OpenPGP Application.

    Examples:

    \b
      Set the retries for PIN, Reset Code and Admin PIN to 10:
      $ ykman openpgp set-retries 10 10 10

    \b
      Require touch to use the authentication key:
      $ ykman openpgp touch aut on
515485
def openpgp(ctx):
    
    try:
        ctx.obj['controller'] = OpgpController(ctx.obj['dev'].driver)
    except APDUError as e:
        if e.sw == SW.NOT_FOUND:
            ctx.fail("The OpenPGP application can't be found on this "
                     'YubiKey.')
        logger.debug('Failed to load OpenPGP Application', exc_info=e)
        ctx.fail('Failed to load OpenPGP Application')
296348
function setupAutoUpdatePreference() {
        PreferencesManager.definePreference("autoUpdate.AutoUpdate", "boolean", true, {
            description: Strings.DESCRIPTION_AUTO_UPDATE
        });

        // Set or unset the auto update, based on preference state change
        PreferencesManager.on("change", "autoUpdate.AutoUpdate", function () {
            if (_isAutoUpdateEnabled()) {
                setupAutoUpdate();
                UpdateNotification.registerUpdateHandler(_updateProcessHandler);
            } else {
                unsetAutoUpdate();
                UpdateNotification.resetToDefaultUpdateHandler();
            }
        });
    }
936136
function (token, deviceId, appId, events) {
    var options = {
      deviceId: deviceId,
      appId: appId,
    };

    require('./helpers').startAppUninstall(options, events);

  }
80732
async def authenticate_with_device(atv):
    """"""
    credentials = await atv.airplay.generate_credentials()
    await atv.airplay.load_credentials(credentials)

    try:
        await atv.airplay.start_authentication()
        pin = input('PIN Code: ')
        await atv.airplay.finish_authentication(pin)
        print('Credentials: {0}'.format(credentials))

    except exceptions.DeviceAuthenticationError:
        print('Failed to authenticate', file=sys.stderr)
977994
def confirmation(self, pdu):
        """"""
        if _debug: StateMachineAccessPoint._debug("confirmation %r", pdu)

        # check device communication control
        if self.dccEnableDisable == 'enable':
            if _debug: StateMachineAccessPoint._debug("    - communications enabled")
        elif self.dccEnableDisable == 'disable':
            if (pdu.apduType == 0) and (pdu.apduService == 17):
                if _debug: StateMachineAccessPoint._debug("    - continue with DCC request")
            elif (pdu.apduType == 0) and (pdu.apduService == 20):
                if _debug: StateMachineAccessPoint._debug("    - continue with reinitialize device")
            elif (pdu.apduType == 1) and (pdu.apduService == 8):
                if _debug: StateMachineAccessPoint._debug("    - continue with Who-Is")
            else:
                if _debug: StateMachineAccessPoint._debug("    - not a Who-Is, dropped")
                return
        elif self.dccEnableDisable == 'disableInitiation':
            if _debug: StateMachineAccessPoint._debug("    - initiation disabled")

        # make a more focused interpretation
        atype = apdu_types.get(pdu.apduType)
        if not atype:
            StateMachineAccessPoint._warning("    - unknown apduType: %r", pdu.apduType)
            return

        # decode it
        apdu = atype()
        apdu.decode(pdu)
        if _debug: StateMachineAccessPoint._debug("    - apdu: %r", apdu)

        if isinstance(apdu, ConfirmedRequestPDU):
            # find duplicates of this request
            for tr in self.serverTransactions:
                if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
                    break
            else:
                # build a server transaction
                tr = ServerSSM(self, apdu.pduSource)

                # add it to our transactions to track it
                self.serverTransactions.append(tr)

            # let it run with the apdu
            tr.indication(apdu)

        elif isinstance(apdu, UnconfirmedRequestPDU):
            # deliver directly to the application
            self.sap_request(apdu)

        elif isinstance(apdu, SimpleAckPDU) \
            or isinstance(apdu, ComplexAckPDU) \
            or isinstance(apdu, ErrorPDU) \
            or isinstance(apdu, RejectPDU):

            # find the client transaction this is acking
            for tr in self.clientTransactions:
                if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
                    break
            else:
                return

            # send the packet on to the transaction
            tr.confirmation(apdu)

        elif isinstance(apdu, AbortPDU):
            # find the transaction being aborted
            if apdu.apduSrv:
                for tr in self.clientTransactions:
                    if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
                        break
                else:
                    return

                # send the packet on to the transaction
                tr.confirmation(apdu)
            else:
                for tr in self.serverTransactions:
                    if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
                        break
                else:
                    return

                # send the packet on to the transaction
                tr.indication(apdu)

        elif isinstance(apdu, SegmentAckPDU):
            # find the transaction being aborted
            if apdu.apduSrv:
                for tr in self.clientTransactions:
                    if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
                        break
                else:
                    return

                # send the packet on to the transaction
                tr.confirmation(apdu)
            else:
                for tr in self.serverTransactions:
                    if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
                        break
                else:
                    return

                # send the packet on to the transaction
                tr.indication(apdu)

        else:
            raise RuntimeError("invalid APDU (8)")
497491
def chalresp(ctx, slot, key, totp, touch, force, generate):
    
    controller = ctx.obj['controller']

    if key:
        if generate:
            ctx.fail('Invalid options: --generate conflicts with KEY argument.')
        elif totp:
            key = parse_b32_key(key)
        else:
            key = parse_key(key)
    else:
        if force and not generate:
            ctx.fail('No secret key given. Please remove the --force flag, '
                     'set the KEY argument or set the --generate flag.')
        elif totp:
            while True:
                key = click.prompt('Enter a secret key (base32)', err=True)
                try:
                    key = parse_b32_key(key)
                    break
                except Exception as e:
                    click.echo(e)
        else:
            if generate:
                key = os.urandom(20)
                click.echo('Using a randomly generated key: {}'.format(
                    b2a_hex(key).decode('ascii')))
            else:
                key = click.prompt('Enter a secret key', err=True)
                key = parse_key(key)

    cred_type = 'TOTP' if totp else 'challenge-response'
    force or click.confirm('Program a {} credential in slot {}?'
                           .format(cred_type, slot), abort=True, err=True)
    try:
        controller.program_chalresp(slot, key, touch)
    except YkpersError as e:
        _failed_to_write_msg(ctx, e)
407025
static void setAuthParams(String appKey, String desiredUid,
                              String[] alreadyAuthedUids, String webHost, String apiType) {
        setAuthParams(appKey, desiredUid, alreadyAuthedUids, null, null, null);
    }
1109545
def handle_two_step_for_device(device_id)
      # Request token to device
      r = request(:put) do |req|
        req.url("https://idmsa.apple.com/appleauth/auth/verify/device/#{device_id}/securitycode")
        update_request_headers(req)
      end

      # we use `Spaceship::TunesClient.new.handle_itc_response`
      # since this might be from the Dev Portal, but for 2 step
      Spaceship::TunesClient.new.handle_itc_response(r.body)

      puts("Successfully requested notification")
      code = ask("Please enter the 4 digit code: ")
      puts("Requesting session...")

      # Send token to server to get a valid session
      r = request(:post) do |req|
        req.url("https://idmsa.apple.com/appleauth/auth/verify/device/#{device_id}/securitycode")
        req.headers['Content-Type'] = 'application/json'
        req.body = { "code" => code.to_s }.to_json
        update_request_headers(req)
      end

      begin
        Spaceship::TunesClient.new.handle_itc_response(r.body) # this will fail if the code is invalid
      rescue => ex
        # If the code was entered wrong
        # {
        #   "securityCode": {
        #     "code": "1234"
        #   },
        #   "securityCodeLocked": false,
        #   "recoveryKeyLocked": false,
        #   "recoveryKeySupported": true,
        #   "manageTrustedDevicesLinkName": "appleid.apple.com",
        #   "suppressResend": false,
        #   "authType": "hsa",
        #   "accountLocked": false,
        #   "validationErrors": [{
        #     "code": "-21669",
        #     "title": "Incorrect Verification Code",
        #     "message": "Incorrect verification code."
        #   }]
        # }
        if ex.to_s.include?("verification code") # to have a nicer output
          puts("Error: Incorrect verification code")
          return handle_two_step_for_device(device_id)
        end

        raise ex
      end

      store_session

      return true
    end
501427
def nfc(ctx, enable, disable, enable_all, disable_all, list, lock_code, force):
    

    if not (list or enable_all or enable or disable_all or disable):
        ctx.fail('No configuration options chosen.')

    if enable_all:
        enable = APPLICATION.__members__.keys()

    if disable_all:
        disable = APPLICATION.__members__.keys()

    _ensure_not_invalid_options(ctx, enable, disable)

    dev = ctx.obj['dev']
    nfc_supported = dev.config.nfc_supported
    nfc_enabled = dev.config.nfc_enabled

    if not nfc_supported:
        ctx.fail('NFC interface not available.')

    if list:
        _list_apps(ctx, nfc_enabled)

    for app in enable:
        if APPLICATION[app] & nfc_supported:
            nfc_enabled |= APPLICATION[app]
        else:
            ctx.fail('{} not supported over NFC.'.format(app))
    for app in disable:
        if APPLICATION[app] & nfc_supported:
            nfc_enabled &= ~APPLICATION[app]
        else:
            ctx.fail('{} not supported over NFC.'.format(app))

    f_confirm = '{}{}Configure NFC interface?'.format(
        'Enable {}.\n'.format(
            ', '.join(
                [str(APPLICATION[app]) for app in enable])) if enable else '',
        'Disable {}.\n'.format(
            ', '.join(
                [str(APPLICATION[app]) for app in disable])) if disable else '')

    is_locked = dev.config.configuration_locked

    if force and is_locked and not lock_code:
        ctx.fail('Configuration is locked - please supply the --lock-code '
                 'option.')
    if lock_code and not is_locked:
        ctx.fail('Configuration is not locked - please remove the '
                 '--lock-code option.')

    force or click.confirm(f_confirm, abort=True, err=True)

    if is_locked and not lock_code:
        lock_code = prompt_lock_code()

    if lock_code:
        lock_code = _parse_lock_code(ctx, lock_code)

    try:
        dev.write_config(
            device_config(
                nfc_enabled=nfc_enabled),
            reboot=True, lock_key=lock_code)
    except Exception as e:
        logger.error('Failed to write config', exc_info=e)
        ctx.fail('Failed to configure NFC applications.')
564433
def touch(self, mode=0o666, exist_ok=True):
        
        if exist_ok:
            # First try to bump modification time
            # Implementation note: GNU touch uses the UTIME_NOW option of
            # the utimensat() / futimens() functions.
            try:
                os.utime(self, None)
            except OSError:
                # Avoid exception chaining
                pass
            else:
                return
        flags = os.O_CREAT | os.O_WRONLY
        if not exist_ok:
            flags |= os.O_EXCL
        fd = os.open(self, flags, mode)
        os.close(fd)
970392
def init_app(self, app):
        """"""
        # Ensure SECRET_KEY is set.
        SECRET_KEY = app.config.get('SECRET_KEY')

        if SECRET_KEY is None:
            app.config['SECRET_KEY'] = 'CHANGE_ME'
            warnings.warn(
                'Set configuration variable SECRET_KEY with random string',
                UserWarning)
769408
async def finish_pairing(self, pin):
        """"""
        self.srp.step1(pin)

        pub_key, proof = self.srp.step2(self._atv_pub_key, self._atv_salt)

        msg = messages.crypto_pairing({
            tlv8.TLV_SEQ_NO: b'\x03',
            tlv8.TLV_PUBLIC_KEY: pub_key,
            tlv8.TLV_PROOF: proof})
        resp = await self.protocol.send_and_receive(
            msg, generate_identifier=False)

        pairing_data = _get_pairing_data(resp)
        atv_proof = pairing_data[tlv8.TLV_PROOF]
        log_binary(_LOGGER, 'Device', Proof=atv_proof)

        encrypted_data = self.srp.step3()
        msg = messages.crypto_pairing({
            tlv8.TLV_SEQ_NO: b'\x05',
            tlv8.TLV_ENCRYPTED_DATA: encrypted_data})
        resp = await self.protocol.send_and_receive(
            msg, generate_identifier=False)

        pairing_data = _get_pairing_data(resp)
        encrypted_data = pairing_data[tlv8.TLV_ENCRYPTED_DATA]

        return self.srp.step4(encrypted_data)
1263053
def _handle_status(self, key, value):
        
        if key == "IMPORTED":
            # this duplicates info we already see in import_ok & import_problem
            pass
        elif key == "PINENTRY_LAUNCHED":
            log.warn(("GnuPG has just attempted to launch whichever pinentry "
                      "program you have configured, in order to obtain the "
                      "passphrase for this key.  If you did not use the "
                      "`passphrase=` parameter, please try doing so.  Otherwise, "
                      "see Issues #122 and #137:"
                      "\nhttps://github.com/isislovecruft/python-gnupg/issues/122"
                      "\nhttps://github.com/isislovecruft/python-gnupg/issues/137"))
        elif key == "KEY_CONSIDERED":
            self.results.append({
                'status': key.replace("_", " ").lower(),
            })
        elif key == "NODATA":
            self.results.append({'fingerprint': None,
                                 'status': 'No valid data found'})
        elif key == "IMPORT_OK":
            reason, fingerprint = value.split()
            reasons = []
            for code, text in self._ok_reason.items():
                if int(reason) == int(code):
                    reasons.append(text)
            reasontext = '\n'.join(reasons) + "\n"
            self.results.append({'fingerprint': fingerprint,
                                 'status': reasontext})
            self.fingerprints.append(fingerprint)
        elif key == "IMPORT_PROBLEM":
            try:
                reason, fingerprint = value.split()
            except:
                reason = value
                fingerprint = '<unknown>'
            self.results.append({'fingerprint': fingerprint,
                                 'status': self._problem_reason[reason]})
        elif key == "IMPORT_RES":
            import_res = value.split()
            for x in self.counts.keys():
                self.counts[x] = int(import_res.pop(0))
        elif key == "KEYEXPIRED":
            res = {'fingerprint': None,
                   'status': 'Key expired'}
            self.results.append(res)
        ## Accoring to docs/DETAILS L859, SIGEXPIRED is obsolete:
        ## "Removed on 2011-02-04. This is deprecated in favor of KEYEXPIRED."
        elif key == "SIGEXPIRED":
            res = {'fingerprint': None,
                   'status': 'Signature expired'}
            self.results.append(res)
        else:
            raise ValueError("Unknown status message: %r" % key)
1058506
function() {
            // At this point, this pinny has been closed and lockup has unlocked.
            // If there are any other pinny's open we don't want to re-enable the
            // inputs as they still require them to be disabled.
            if (this._activePinnies()) {
                return;
            }

            $('[data-orig-tabindex]').each(function(_, el) {
                var $el = $(el);
                var oldTabIndex = parseInt($el.attr('data-orig-tabindex'));

                if (oldTabIndex) {
                    $el.attr('tabindex', oldTabIndex);
                } else {
                    $el.removeAttr('tabindex');
                }

                $el.removeAttr('data-orig-tabindex');
            });
        }
1292315
async def finish_authentication(self, username, password):
        
        # Step 1
        self.srp.step1(username, password)
        data = await self._send_plist(
            'step1', method='pin', user=username)
        resp = plistlib.loads(data)

        # Step 2
        pub_key, key_proof = self.srp.step2(resp['pk'], resp['salt'])
        await self._send_plist(
            'step2',
            pk=binascii.unhexlify(pub_key),
            proof=binascii.unhexlify(key_proof))

        # Step 3
        epk, tag = self.srp.step3()
        await self._send_plist('step3', epk=epk, authTag=tag)
        return True
740961
def verify(app_id, public_key_pem)
      data = [
        ::U2F::DIGEST.digest(app_id),
        signature_data.byteslice(0, 5),
        ::U2F::DIGEST.digest(client_data_json)
      ].join

      public_key = OpenSSL::PKey.read(public_key_pem)

      begin
        public_key.verify(::U2F::DIGEST.new, signature, data)
      rescue OpenSSL::PKey::PKeyError
        false
      end
    end
1262839
def SetCredentials(api_key,api_passwd):
	""""""
	global V1_API_KEY
	global V1_API_PASSWD
	global _V1_ENABLED
	_V1_ENABLED = True
	V1_API_KEY = api_key
	V1_API_PASSWD = api_passwd