Runs OCSP verification and returns error code - 0 means success
331603
def verify_ocsp(cls, certificate, issuer):
        

        return OCSPVerifier(certificate, issuer,
                            cls.get_ocsp_url(),
                            cls.get_ocsp_responder_certificate_path()).verify()
849264
private void validateBasicOcspResponse(
      Date currentTime, BasicOCSPResp basicOcspResp)
  throws CertificateEncodingException
  {
    for (SingleResp singleResps : basicOcspResp.getResponses())
    {
      Date thisUpdate = singleResps.getThisUpdate();
      Date nextUpdate = singleResps.getNextUpdate();
      LOGGER.debug("Current Time: {}, This Update: {}, Next Update: {}",
                   currentTime, thisUpdate, nextUpdate);
      CertificateStatus certStatus = singleResps.getCertStatus();
      if (certStatus != CertificateStatus.GOOD)
      {
        if (certStatus instanceof RevokedStatus)
        {
          RevokedStatus status = (RevokedStatus) certStatus;
          int reason;
          try
          {
            reason = status.getRevocationReason();
          }
          catch (IllegalStateException ex)
          {
            reason = -1;
          }
          Date revocationTime = status.getRevocationTime();
          throw new CertificateEncodingException(
              String.format(
                  "The certificate has been revoked. Reason: %d, Time: %s",
                  reason, DATE_FORMAT_UTC.format(revocationTime)));
        }
        else
        {
          // Unknown status
          throw new CertificateEncodingException(
              "Failed to validate the certificate for UNKNOWN reason.");
        }
      }
      if (!isValidityRange(currentTime, thisUpdate, nextUpdate))
      {
        throw new CertificateEncodingException(
            String.format(
                "The validity is out of range: " +
                "Current Time: %s, This Update: %s, Next Update: %s",
                DATE_FORMAT_UTC.format(currentTime),
                DATE_FORMAT_UTC.format(thisUpdate),
                DATE_FORMAT_UTC.format(nextUpdate)));
      }
    }
    LOGGER.debug("OK. Verified the certificate revocation status.");
  }
21206
def _custom_validate(self, verify, trust_bundle):
        
        # If we disabled cert validation, just say: cool.
        if not verify:
            return

        # We want data in memory, so load it up.
        if os.path.isfile(trust_bundle):
            with open(trust_bundle, 'rb') as f:
                trust_bundle = f.read()

        cert_array = None
        trust = Security.SecTrustRef()

        try:
            # Get a CFArray that contains the certs we want.
            cert_array = _cert_array_from_pem(trust_bundle)

            # Ok, now the hard part. We want to get the SecTrustRef that ST has
            # created for this connection, shove our CAs into it, tell ST to
            # ignore everything else it knows, and then ask if it can build a
            # chain. This is a buuuunch of code.
            result = Security.SSLCopyPeerTrust(
                self.context, ctypes.byref(trust)
            )
            _assert_no_error(result)
            if not trust:
                raise ssl.SSLError("Failed to copy trust reference")

            result = Security.SecTrustSetAnchorCertificates(trust, cert_array)
            _assert_no_error(result)

            result = Security.SecTrustSetAnchorCertificatesOnly(trust, True)
            _assert_no_error(result)

            trust_result = Security.SecTrustResultType()
            result = Security.SecTrustEvaluate(
                trust, ctypes.byref(trust_result)
            )
            _assert_no_error(result)
        finally:
            if trust:
                CoreFoundation.CFRelease(trust)

            if cert_array is not None:
                CoreFoundation.CFRelease(cert_array)

        # Ok, now we can look at what the result was.
        successes = (
            SecurityConst.kSecTrustResultUnspecified,
            SecurityConst.kSecTrustResultProceed
        )
        if trust_result.value not in successes:
            raise ssl.SSLError(
                "certificate verify failed, error code: %d" %
                trust_result.value
            )
694825
function validateSignature(fileName, signature, cb) {
   if (isUndefined(signature) || isUndefined(signature.codesign)) {
      cb();
      return;
   }

   if (isUndefined(codeSignCertFileName)) {
      cb(new Error('No code sign certificate file specified'));
      return;
   }

   var codeSignCert;

   try {
      codeSignCert = fs.readFileSync(codeSignCertFileName, 'utf8');
   } catch (err) {
      // unable to read codeSignCertFileName file
      cb(new Error('Error encountered trying to read ' + codeSignCertFileName));
      return;
   }

   var verify;
   try {
      verify = crypto.createVerify(signature.codesign.signatureAlgorithm);
   } catch (err) {
      console.warn('Unable to use signature algorithm: ' + signature.codesign.signatureAlgorithm + ' attempting to use default algorithm SHA256');
      try {
         verify = crypto.createVerify('SHA256');
      } catch (err) {
         cb(err);
         return;
      }
   }

   var stream = fs.createReadStream(fileName);

   stream.on('data', function (data) {
      verify.write(data);
   }).on('end', function () {
      verify.end();

      try {
         if (!verify.verify(codeSignCert, signature.codesign.signature, 'base64')) {
            var err = new Error('Signature validation failed');
            err.fileName = fileName;
            cb(err);
         } else {
            cb();
         }
      } catch (err) {
         cb(err);
         return;
      }
   }).on('error', function (err) {
      err.fileName = fileName;
      cb(err);
   });
}
766132
static void verifyCAKeyUsage(X509Certificate cert)
            throws CertPathValidatorException {
        String msg = "CA key usage";
        if (debug != null) {
            debug.println("KeyChecker.verifyCAKeyUsage() ---checking " + msg
                          + "...");
        }

        boolean[] keyUsageBits = cert.getKeyUsage();

        // getKeyUsage returns null if the KeyUsage extension is not present
        // in the certificate - in which case there is nothing to check
        if (keyUsageBits == null) {
            return;
        }

        // throw an exception if the keyCertSign bit is not set
        if (!keyUsageBits[KEY_CERT_SIGN]) {
            throw new CertPathValidatorException
                (msg + " check failed: keyCertSign bit is not set", null,
                 null, -1, PKIXReason.INVALID_KEY_USAGE);
        }

        if (debug != null) {
            debug.println("KeyChecker.verifyCAKeyUsage() " + msg
                          + " verified.");
        }
    }
1317422
void validateRevocationStatus(X509Certificate[] chain, String peerHost) throws CertificateException
  {
    final List<Certificate> bcChain = convertToBouncyCastleCertificate(chain);
    final List<SFPair<Certificate, Certificate>> pairIssuerSubjectList =
        getPairIssuerSubject(bcChain);

    if (peerHost.startsWith("ocspssd"))
    {
      return;
    }

    if (ocspCacheServer.new_endpoint_enabled)
    {
      ocspCacheServer.resetOCSPResponseCacheServer(peerHost);
    }

    synchronized (OCSP_RESPONSE_CACHE_LOCK)
    {
      boolean isCached = isCached(pairIssuerSubjectList);
      if (this.useOcspResponseCacheServer && !isCached)
      {
        if (!ocspCacheServer.new_endpoint_enabled)
        {
          LOGGER.debug(
              "Downloading OCSP response cache from the server. URL: {}",
              SF_OCSP_RESPONSE_CACHE_SERVER_URL);
        }
        else
        {
          LOGGER.debug(
              "Downloading OCSP response cache from the server. URL: {}",
              ocspCacheServer.SF_OCSP_RESPONSE_CACHE_SERVER);
        }
        readOcspResponseCacheServer();
        // if the cache is downloaded from the server, it should be written
        // to the file cache at all times.
        WAS_CACHE_UPDATED = true;
      }
      executeRevocationStatusChecks(pairIssuerSubjectList, peerHost);
      if (WAS_CACHE_UPDATED)
      {
        JsonNode input = encodeCacheToJSON();
        fileCacheManager.writeCacheFile(input);
        WAS_CACHE_UPDATED = false;
      }
    }
  }
585238
def _verify_cas1(ticket, service):
    

    params = {'ticket': ticket, 'service': service}
    url = (urljoin(settings.CAS_SERVER_URL, 'validate') + '?' +
           urlencode(params))
    page = urlopen(url)

    try:
        verified = page.readline().strip()
        if verified == 'yes':
            return page.readline().strip()
        else:
            return None
    finally:
        page.close()
1033501
def verify(num, filename=None, exit=True):
    """"""
    p = Problem(num)

    filename = filename or p.filename()

    if not os.path.isfile(filename):
        # Attempt to verify the first problem file matched by glob
        if p.glob:
            filename = str(p.file)
        else:
            click.secho('No file found for problem %i.' % p.num, fg='red')
            sys.exit(1)

    solution = p.solution
    click.echo('Checking "{}" against solution: '.format(filename), nl=False)

    cmd = (sys.executable or 'python', filename)
    start = clock()
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    stdout = proc.communicate()[0]
    end = clock()
    time_info = format_time(start, end)

    # Return value of anything other than 0 indicates an error
    if proc.poll() != 0:
        click.secho('Error calling "{}".'.format(filename), fg='red')
        click.secho(time_info, fg='cyan')

        # Return None if option is not --verify-all, otherwise exit
        return sys.exit(1) if exit else None

    # Decode output if returned as bytes (Python 3)
    if isinstance(stdout, bytes):
        output = stdout.decode('ascii')

    # Split output lines into array; make empty output more readable
    output_lines = output.splitlines() if output else ['[no output]']

    # If output is multi-lined, print the first line of the output on a
    # separate line from the "checking against solution" message, and
    # skip the solution check (multi-line solution won't be correct)
    if len(output_lines) > 1:
        is_correct = False
        click.echo()  # force output to start on next line
        click.secho('\n'.join(output_lines), bold=True, fg='red')
    else:
        is_correct = output_lines[0] == solution
        fg_colour = 'green' if is_correct else 'red'
        click.secho(output_lines[0], bold=True, fg=fg_colour)

    click.secho(time_info, fg='cyan')

    # Remove any suffix from the filename if its solution is correct
    if is_correct:
        p.file.change_suffix('')

    # Exit here if answer was incorrect, otherwise return is_correct value
    return sys.exit(1) if exit and not is_correct else is_correct
1366120
def verify_cb(conn, cert, errnum, depth, ok):
    
    if not ok:
        raise SecurityError("Could not verify CA certificate {0}"
                            .format(cert.get_subject()))
    return ok
1159890
def verify(sig, signed_text = nil, plain = Data.new)
      err = GPGME::gpgme_op_verify(self, sig, signed_text, plain)
      exc = GPGME::error_to_exception(err)
      raise exc if exc
      plain
    end
556398
def verify(self):
		
		logging.debug("\n\n")
		logging.debug("[+] -- Verify debugging")
		logging.debug("\n\n")

		if self.request.body:
			logging.debug("\n Request body")
			logging.debug(self.request.body)
			data = json.loads(self.request.body)
			message = json.dumps(data.get("message")).replace(" ", "")
			logging.debug("\n")
			logging.debug(message)

		elif self.request.arguments:
			logging.debug("\n Arguments")
			logging.debug(self.request.arguments)
			data = {i:self.get_argument(i) for i in self.request.arguments}
			message = data.get("message", "{}")
			logging.debug(message)

		try:
			# Check if required fields exist
			assert "public_key" in data.keys(), "Missed public key in parameters"
			assert "message" in data.keys(), "Missed message in parameters"
			assert "signature" in data.keys(),"Missed signature in parameters"
			public_key = data["public_key"]
			signature = data["signature"]
			timestamp = data.get("timestamp", None)
			
			# Check if
			#assert ManagementSystemHandler.get_time_stamp() == timestamp, "Timestamps does not match. Try again."

		except Exception as e:
			self.set_status(403)
			self.write({"error":403, "reason": "Missing signature " + str(e)})
			raise tornado.web.Finish

		else:
			# Check if message and signature exist
			# If not - return 403 error code
			if not all([message, public_key, signature]):
				raise tornado.web.HTTPError(403)
		# If exist - call verifying static method
		try:
			logging.debug("\n[] Try block. Verifying")
			logging.debug(message)
			logging.debug(signature)
			logging.debug(public_key)
			flag = Qtum.verify_message(message, signature, public_key)
		except Exception as e:
			# If public key is not valid or it`s missing - return 404 error
			#self.set_status(403)
			#self.write({"error":403, 
			#			"reason":"Forbidden. Invalid signature." + str(e)})
			#raise tornado.web.Finish
			logging.debug("\n Exception")
			logging.debug(str(e))
			pass
1264535
def has_ocsp_must_staple_extension(certificate: cryptography.x509.Certificate) -> bool:
        
        has_ocsp_must_staple = False
        try:
            tls_feature_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.TLS_FEATURE)
            for feature_type in tls_feature_ext.value:
                if feature_type == cryptography.x509.TLSFeatureType.status_request:
                    has_ocsp_must_staple = True
                    break
        except ExtensionNotFound:
            pass

        return has_ocsp_must_staple
104978
public static void verify(X509Certificate cert, PublicKey key,
            Provider sigProvider) throws CertificateException,
            NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        cert.verify(key, sigProvider);
    }
1334033
def _verify(function):
    """"""
    # @functools.wraps
    def wrapped(pin, *args, **kwargs):
        pin = int(pin)
        if pin not in _open:
            ppath = gpiopath(pin)
            if not os.path.exists(ppath):
                log.debug("Creating Pin {0}".format(pin))
                with _export_lock:
                    with open(pjoin(gpio_root, 'export'), 'w') as f:
                        _write(f, pin)
            value = open(pjoin(ppath, 'value'), FMODE)
            direction = open(pjoin(ppath, 'direction'), FMODE)
            _open[pin] = PinState(value=value, direction=direction)
        return function(pin, *args, **kwargs)
    return wrapped
808428
def _extract_ocsp_certs(self, ocsp_response):
        

        status = ocsp_response['response_status'].native
        if status == 'successful':
            response_bytes = ocsp_response['response_bytes']
            if response_bytes['response_type'].native == 'basic_ocsp_response':
                response = response_bytes['response'].parsed
                if response['certs']:
                    for other_cert in response['certs']:
                        if self.certificate_registry.add_other_cert(other_cert):
                            self._revocation_certs[other_cert.issuer_serial] = other_cert
977390
def check(self, return_code=0):
        
        ret = self.call().return_code
        ok = ret == return_code
        if not ok:
            raise EasyProcessError(
                self, 'check error, return code is not {0}!'.format(return_code))
        return self
256077
private OCSPResp fetchOcspResponse(
      SFPair<Certificate, Certificate> pairIssuerSubject, OCSPReq req,
      String cid_enc, String hname)
  throws CertificateEncodingException
  {
    try
    {
      byte[] ocspReqDer = req.getEncoded();
      String ocspReqDerBase64 = Base64.encodeBase64String(ocspReqDer);

      Set<String> ocspUrls = getOcspUrls(pairIssuerSubject.right);
      String ocspUrlStr = ocspUrls.iterator().next(); // first one
      URL url;

      if (!ocspCacheServer.new_endpoint_enabled)
      {
        if (SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN != null)
        {
          URL ocspUrl = new URL(ocspUrlStr);
          url = new URL(String.format(
              SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN,
              ocspUrl.getHost(), ocspReqDerBase64));
        }
        else
        {
          url = new URL(String.format("%s/%s", ocspUrlStr, ocspReqDerBase64));
        }

        LOGGER.debug(
            "not hit cache. Fetching OCSP response from CA OCSP server. {}", url.toString());
      }
      else
      {
        url = new URL(ocspCacheServer.SF_OCSP_RESPONSE_RETRY_URL);
        LOGGER.debug(
            "not hit cache. Fetching OCSP response from Snowflake OCSP Response Fetcher. {}", url.toString());
      }

      long sleepTime = INITIAL_SLEEPING_TIME_IN_MILLISECONDS;
      DecorrelatedJitterBackoff backoff = new DecorrelatedJitterBackoff(
          sleepTime, MAX_SLEEPING_TIME_IN_MILLISECONDS);
      boolean success = false;
      HttpResponse response = null;

      for (int retry = 0; retry < MAX_RETRY_COUNTER; ++retry)
      {
        if (!ocspCacheServer.new_endpoint_enabled)
        {
          HttpClient client = getHttpClient();
          HttpGet get = new HttpGet(url.toString());
          response = client.execute(get);
        }
        else
        {
          HttpClient client = getHttpClient();
          HttpPost post = new HttpPost(url.toString());
          post.setHeader("Content-Type", "application/json");
          SFTrustManager.OCSPPostReqData postReqData =
              new SFTrustManager.OCSPPostReqData(ocspUrlStr,
                                                 ocspReqDerBase64,
                                                 cid_enc,
                                                 hname);
          String json_payload = OBJECT_MAPPER.writeValueAsString(postReqData);
          post.setEntity(new StringEntity(json_payload, "utf-8"));
          response = client.execute(post);

        }

        if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
        {
          success = true;
          LOGGER.debug(
              "Successfully downloaded OCSP response from CA server. " +
              "URL: {}", url.toString());
          break;
        }
        LOGGER.debug("Retrying {}/{} after sleeping {}(ms)",
                     retry + 1, MAX_RETRY_COUNTER, sleepTime);
        try
        {
          Thread.sleep(sleepTime);
          sleepTime = backoff.nextSleepTime(sleepTime);
        }
        catch (InterruptedException ex0)
        { // nop
        }
      }
      if (!success)
      {
        throw new CertificateEncodingException(
            String.format(
                "Failed to get OCSP response. StatusCode: %d, URL: %s",
                response == null ? null : response.getStatusLine().getStatusCode(),
                ocspUrlStr));
      }
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      IOUtils.copy(response.getEntity().getContent(), out);
      OCSPResp ocspResp = new OCSPResp(out.toByteArray());
      if (ocspResp.getStatus() != OCSPResp.SUCCESSFUL)
      {
        throw new CertificateEncodingException(
            String.format("Failed to get OCSP response. Status: %s",
                          OCSP_RESPONSE_CODE_TO_STRING.get(ocspResp.getStatus())));
      }

      return ocspResp;
    }
    catch (IOException ex)
    {
      throw new CertificateEncodingException("Failed to encode object.", ex);
    }
  }