/*
The Yubikey api has a single method, verify(otp)
508557
function Yubikey(clientId, secretKey) {
  this.clientId = clientId || process.env['YUBIKEY_CLIENT_ID'];
  this.secretKey = secretKey || process.env['YUBIKEY_SECRET_KEY'];

  if (!(this.clientId && this.secretKey)) {
    throw new Error("need client id and secret key");
  }
}
1109820
def verify?(params)
      params = Utils.stringify_keys(params)
      return false if params['sign_type'] != @sign_type

      sign = params.delete('sign')
      # sign_type does not use in notify sign
      params.delete('sign_type')
      string = params_to_string(params)
      case @sign_type
      when 'RSA'
        ::Alipay::Sign::RSA.verify?(@alipay_public_key, string, sign)
      when 'RSA2'
        ::Alipay::Sign::RSA2.verify?(@alipay_public_key, string, sign)
      else
        raise "Unsupported sign_type: #{@sign_type}"
      end
    end
716531
public function validateKey()
    {
        try {
            $this->api->get('');
        } catch (\Exception $e) {
            if (starts_with($e->getMessage(), '{')) {
                $json = json_decode($e->getMessage());
                if ($json->status == 401) {
                    throw new InvalidApiKey($json->detail);
                }
            }

            throw $e;
        }
    }
264508
function verify(req, identifier, profile, done) {
    var validOpEndpoint = 'https://steamcommunity.com/openid/login';
    var identifierRegex = /^https?:\/\/steamcommunity\.com\/openid\/id\/(\d+)$/;

    if(req.query['openid.op_endpoint'] !== validOpEndpoint ||
       !identifierRegex.test(identifier)) {
      return done(null, false, { message: 'Claimed identity is invalid.' });
    }

    var steamID = identifierRegex.exec(identifier)[0];

    if(options.profile) {
      getUserProfile(options.apiKey, steamID, function(err, profile) {
        if(err) {
          done(err);
        } else {
          if(originalPassReqToCallback) {
            validate(req, identifier, profile, done);
          } else {
            validate(identifier, profile, done);
          }
        }
      });
    } else {
      if(originalPassReqToCallback) {
        validate(req, identifier, profile, done);
      } else {
        validate(identifier, profile, done);
      }
    }
  }
1331355
def parse_args():
    
    global default_device

    parser = argparse.ArgumentParser(description = "Validate YubiKey OTP's using YubiHSM",
                                     add_help=True
                                     )
    parser.add_argument('-D', '--device',
                        dest='device',
                        default=default_device,
                        required=False,
                        help='YubiHSM device (default : %s).' % default_device
                        )
    parser.add_argument('-v', '--verbose',
                        dest='verbose',
                        action='store_true', default=False,
                        help='Enable verbose operation.'
                        )
    parser.add_argument('--debug',
                        dest='debug',
                        action='store_true', default=False,
                        help='Enable debug operation.'
                        )
    group = parser.add_argument_group('Modes', 'What you want to validate')
    mode_group = group.add_mutually_exclusive_group(required = True)
    mode_group.add_argument('--otp',
                            dest='otp',
                            help='The output from your YubiKey.'
                            )
    mode_group.add_argument('--oath',
                            dest='oath',
                            help='The output from your OATH-HOTP token.'
                            )

    args = parser.parse_args()
    return args
1248008
def verify(verified_entity, verification_key):
        
        verification = get_object_or_none(Verification, verified_entity=verified_entity)

        if verification is None:
            raise ServerError(VerificationHandler.STATUS_VERIFICATION_NOT_FOUND)
        if not verification.verify(verification_key):
            raise ServerError(VerificationHandler.STATUS_INVALID_VERIFICATION_KEY)

        verification.verified = True
        verification.save()
301361
public function validate($otp, $action, $uid = null, $data = null) {
    $hash  = $this->psl['crypt/hash'];
    $store = $this->psl['store'];

    if($uid === null) {
	    $uid = $this->psl->getUid();
	  }

    $storeData = $store->read('otp', $this->storeId($uid, $action));

    if($storeData !== false) {
      if($storeData['ttl'] < time()) {
        $store->delete('otp', $this->storeId($uid, $action));
        return false;
      }

      if($hash->check($otp, $storeData['pw']) && $hash->check(serialize($data), $storeData['data'])) {
        $store->delete('otp', $this->storeId($uid, $action));
        return true;
      }
    }
    return false;
  }
276946
private static boolean Verify(InputStream isSignature, InputStream isMessage, InputStream isPublicKey) throws LRException
    {
		// Get the public key ring collection from the public key input stream
		PGPPublicKeyRingCollection pgpRings = null;
		
		try
		{
			 pgpRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(isPublicKey));
		}
		catch (Exception e)
		{
			throw new LRException(LRException.INVALID_PUBLIC_KEY);
		}
	
		// Add the Bouncy Castle security provider
		Security.addProvider(new BouncyCastleProvider());
		
		// Build an output stream from the message for verification
		boolean verify = false;
		int ch;
		ByteArrayOutputStream bOut = new ByteArrayOutputStream();
		ArmoredInputStream aIn  = null;
		
		try
		{
			aIn = new ArmoredInputStream(isMessage);
			// We are making no effort to clean the input for this example
			// If this turns into a fully-featured verification utility in a future version, this will need to be handled
			while ((ch = aIn.read()) >= 0 && aIn.isClearText())
			{
				bOut.write((byte)ch);
			}
			
			bOut.close();
		}
		catch (Exception e)
		{
			throw new LRException(LRException.MESSAGE_INVALID);
		}
		
		// Build an object factory from the signature input stream and try to get an object out of it
		Object o = null;
		try
		{
			PGPObjectFactory pgpFact = new PGPObjectFactory(PGPUtil.getDecoderStream(isSignature));
			o = pgpFact.nextObject();
		}
		catch (Exception e)
		{
			throw new LRException(LRException.SIGNATURE_INVALID);
		}
			
		// Check if the object we fetched is a signature list and if it is, get the signature and use it to verfiy
		try
		{
			if (o instanceof PGPSignatureList)
			{
				PGPSignatureList list = (PGPSignatureList)o;
				if (list.size() > 0)
				{
					PGPSignature sig = list.get(0);
					
					PGPPublicKey publicKey = pgpRings.getPublicKey(sig.getKeyID());
					sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey);
					
					sig.update(bOut.toByteArray());
					verify = sig.verify();
				}
			}
		}
		catch (Exception e)
		{
			throw new LRException(LRException.SIGNATURE_NOT_FOUND);
		}
		
		return verify;
	}
1264466
function verify (transaction) {
	var remove = 64;

	if (transaction.signSignature) {
		remove = 128;
	}

	var bytes = getBytes(transaction);
	var data2 = Buffer.alloc(bytes.length - remove);

	for (var i = 0; i < data2.length; i++) {
		data2[i] = bytes[i];
	}

	var hash = crypto.createHash('sha256').update(data2.toString('hex'), 'hex').digest();

	var signatureBuffer = Buffer.from(transaction.signature, 'hex');
	var senderPublicKeyBuffer = Buffer.from(transaction.senderPublicKey, 'hex');
	var res = naclInstance.crypto_sign_verify_detached(signatureBuffer, hash, senderPublicKeyBuffer);

	return res;
}
269237
public static boolean verifySignature(RSAPublicKey key, byte[] message, byte[] signature)
            throws InvalidKeyException, NoSuchAlgorithmException, SignatureException {
        return verifySignature(key, message, signature, DEFAULT_SIGNATURE_ALGORITHM);
    }
639141
function expectBobQueryKeys() {
    // can't query keys before ali has uploaded them
    expect(aliTestClient.deviceKeys).toBeTruthy();

    const aliKeys = {};
    aliKeys[aliDeviceId] = aliTestClient.deviceKeys;
    console.log("query result will be", aliKeys);

    bobTestClient.httpBackend.when(
        "POST", "/keys/query",
    ).respond(200, function(path, content) {
        expect(content.device_keys[aliUserId]).toEqual(
            {},
            "Expected Bob to key query for " + aliUserId + ", got " +
            Object.keys(content.device_keys),
        );
        const result = {};
        result[aliUserId] = aliKeys;
        return {device_keys: result};
    });
    return bobTestClient.httpBackend.flush("/keys/query", 1);
}
72541
function (actual, message) {
        YUITest.Assert._increment();
        if (typeof actual != "boolean"){
            throw new YUITest.UnexpectedValue(YUITest.Assert._formatMessage(message, "Value should be a Boolean."), actual);
        }
    }
1307004
@Override
	protected AbstractChainedResourceBundlePostProcessor buildProcessorByKey(String procesorKey) {
		if (PostProcessFactoryConstant.JSMIN.equals(procesorKey))
			return buildJSMinPostProcessor();
		else if (PostProcessFactoryConstant.LICENSE_INCLUDER.equals(procesorKey))
			return buildLicensesProcessor();
		else if (PostProcessFactoryConstant.UGLIFY_JS.equals(procesorKey))
			return buildUglifyJSProcessor();
		else if (PostProcessFactoryConstant.YUI_COMPRESSOR.equals(procesorKey))
			return new YUIJSCompressor(false);
		else if (PostProcessFactoryConstant.YUI_COMPRESSOR_OBFUSCATOR.equals(procesorKey))
			return new YUIJSCompressor(true);
		else
			throw new IllegalArgumentException("The supplied key [" + procesorKey
					+ "] is not bound to any ResourceBundlePostProcessor. Please check the documentation for valid keys. ");
	}
615883
public static function create_and_verify($params = null, $apiKey = null)
    {
        $class = get_class();
        if (!isset($params['address']) || !is_array($params['address'])) {
            $clone = $params;
            unset($params);
            $params['address'] = $clone;
        }

        $requestor = new Requestor($apiKey);
        $url = self::classUrl($class);
        list($response, $apiKey) = $requestor->request('post', $url.'/create_and_verify', $params);

        if (isset($response['address'])) {
            $verified_address = Util::convertToEasyPostObject($response['address'], $apiKey);
            if (!empty($response['message'])) {
                $verified_address->message = $response['message'];
                $verified_address->_immutableValues[] = 'message';
            }

            return $verified_address;
        } else {

            return Util::convertToEasyPostObject($response, $apiKey);
        }
    }
26886
private void checkKey(final byte[] key) {
		if (theBinaryKey.get() != null) {
			verifyKey(key);
		} else {
			boolean success = theBinaryKey.compareAndSet(null, key);
			if (!success) {
				// someone already beat us to it. that's fine, just verify
				// that the key is the same
				verifyKey(key);
			} else {
				pipelined(key);
			}
		}
	}
528242
def _challenge_response(self, challenge, mode, slot, variable, may_block):
        
         # Check length and pad challenge if appropriate
        if mode == 'HMAC':
            if len(challenge) > yubikey_defs.SHA1_MAX_BLOCK_SIZE:
                raise yubico_exception.InputError('Mode HMAC challenge too big (%i/%i)' \
                                                      % (yubikey_defs.SHA1_MAX_BLOCK_SIZE, len(challenge)))
            if len(challenge) < yubikey_defs.SHA1_MAX_BLOCK_SIZE:
                pad_with = b'\0'
                if variable and challenge[-1:] == pad_with:
                    pad_with = b'\xff'
                challenge = challenge.ljust(yubikey_defs.SHA1_MAX_BLOCK_SIZE, pad_with)
            response_len = yubikey_defs.SHA1_DIGEST_SIZE
        elif mode == 'OTP':
            if len(challenge) != yubikey_defs.UID_SIZE:
                raise yubico_exception.InputError('Mode OTP challenge must be %i bytes (got %i)' \
                                                      % (yubikey_defs.UID_SIZE, len(challenge)))
            challenge = challenge.ljust(yubikey_defs.SHA1_MAX_BLOCK_SIZE, b'\0')
            response_len = 16
        else:
            raise yubico_exception.InputError('Invalid mode supplied (%s, valid values are HMAC and OTP)' \
                                                  % (mode))

        try:
            command = _CMD_CHALLENGE[mode][slot]
        except:
            raise yubico_exception.InputError('Invalid slot specified (%s)' % (slot))

        frame = yubikey_frame.YubiKeyFrame(command=command, payload=challenge)
        self._device._write(frame)
        response = self._device._read_response(may_block=may_block)
        if not yubico_util.validate_crc16(response[:response_len + 2]):
            raise YubiKeyUSBHIDError("Read from device failed CRC check")
        return response[:response_len]
618019
function checkApiKey(key) {
  if (!GLOBAL.config.apis || !GLOBAL.config.apis[key]) {
    GLOBAL.error('no GLOBAL.config.apis.bing');
    return false;
  }
  return true;
}