Verifies that the signature is correct for the specified data using a given certificate

@param string $certPath
@param string $data
@param string $signature
@return int
@throws \opus\payment\Exception
163866
protected function verifySignatureWithCertificate($certPath, $data, $signature)
    {
        $file = @fopen($certPath, "r");
        if ($file === false) {
            throw new Exception('Could not open certificate file. ');
        }
        $fileSize = filesize($certPath);

        $certificate = fread($file, $fileSize);
        fclose($file);

        $publicKey = openssl_pkey_get_public($certificate);

        $isVerified = openssl_verify($data, $signature, $publicKey);
        openssl_free_key($publicKey);

        if ($isVerified === 0) {
            throw new Exception('Incorrect signature');
        } elseif ($isVerified === -1) {
            throw new Exception('Could not verify signature');
        }

        return $isVerified;
    }
677803
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
        String keyBytes = Base64Utils.encode(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes.getBytes());
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicK = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicK);
        signature.update(data);
        return signature.verify(Base64Utils.decode(sign).getBytes());
    }
1264743
private function verifySignature($data, $sig)
    {
        $this->initOpenSSL();
        $ret = openssl_verify($data, $sig, $this->publicKey, 'sha256');
        if ($ret == -1) {
            throw new SignatureException(openssl_error_string());
        }
        return $ret;
    }
1018477
private function _checkValidity(Certificate $cert)
    {
        $refdt = $this->_config->dateTime();
        $validity = $cert->tbsCertificate()->validity();
        if ($validity->notBefore()
            ->dateTime()
            ->diff($refdt)->invert) {
            throw new PathValidationException(
                "Certificate validity period has not started.");
        }
        if ($refdt->diff($validity->notAfter()
            ->dateTime())->invert) {
            throw new PathValidationException("Certificate has expired.");
        }
    }
177158
function _validateSignatureCountable($caonly, $count)
    {
        if (!is_array($this->currentCert) || !isset($this->signatureSubject)) {
            return null;
        }

        if ($count == self::$recur_limit) {
            return false;
        }

        /* TODO:
           "emailAddress attribute values are not case-sensitive (e.g., "subscriber@example.com" is the same as "SUBSCRIBER@EXAMPLE.COM")."
            -- http://tools.ietf.org/html/rfc5280#section-4.1.2.6

           implement pathLenConstraint in the id-ce-basicConstraints extension */

        switch (true) {
            case isset($this->currentCert['tbsCertificate']):
                // self-signed cert
                switch (true) {
                    case !defined('FILE_X509_IGNORE_TYPE') && $this->currentCert['tbsCertificate']['issuer'] === $this->currentCert['tbsCertificate']['subject']:
                    case defined('FILE_X509_IGNORE_TYPE') && $this->getIssuerDN(self::DN_STRING) === $this->getDN(self::DN_STRING):
                        $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier');
                        $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier');
                        switch (true) {
                            case !is_array($authorityKey):
                            case !$subjectKeyID:
                            case isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID:
                                $signingCert = $this->currentCert; // working cert
                        }
                }

                if (!empty($this->CAs)) {
                    for ($i = 0; $i < count($this->CAs); $i++) {
                        // even if the cert is a self-signed one we still want to see if it's a CA;
                        // if not, we'll conditionally return an error
                        $ca = $this->CAs[$i];
                        switch (true) {
                            case !defined('FILE_X509_IGNORE_TYPE') && $this->currentCert['tbsCertificate']['issuer'] === $ca['tbsCertificate']['subject']:
                            case defined('FILE_X509_IGNORE_TYPE') && $this->getDN(self::DN_STRING, $this->currentCert['tbsCertificate']['issuer']) === $this->getDN(self::DN_STRING, $ca['tbsCertificate']['subject']):
                                $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier');
                                $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca);
                                switch (true) {
                                    case !is_array($authorityKey):
                                    case !$subjectKeyID:
                                    case isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID:
                                        if (is_array($authorityKey) && isset($authorityKey['authorityCertSerialNumber']) && !$authorityKey['authorityCertSerialNumber']->equals($ca['tbsCertificate']['serialNumber'])) {
                                            break 2; // serial mismatch - check other ca
                                        }
                                        $signingCert = $ca; // working cert
                                        break 3;
                                }
                        }
                    }
                    if (count($this->CAs) == $i && $caonly) {
                        return $this->_testForIntermediate($caonly, $count) && $this->validateSignature($caonly);
                    }
                } elseif (!isset($signingCert) || $caonly) {
                    return $this->_testForIntermediate($caonly, $count) && $this->validateSignature($caonly);
                }
                return $this->_validateSignature(
                    $signingCert['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'],
                    $signingCert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'],
                    $this->currentCert['signatureAlgorithm']['algorithm'],
                    substr(base64_decode($this->currentCert['signature']), 1),
                    $this->signatureSubject
                );
            case isset($this->currentCert['certificationRequestInfo']):
                return $this->_validateSignature(
                    $this->currentCert['certificationRequestInfo']['subjectPKInfo']['algorithm']['algorithm'],
                    $this->currentCert['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'],
                    $this->currentCert['signatureAlgorithm']['algorithm'],
                    substr(base64_decode($this->currentCert['signature']), 1),
                    $this->signatureSubject
                );
            case isset($this->currentCert['publicKeyAndChallenge']):
                return $this->_validateSignature(
                    $this->currentCert['publicKeyAndChallenge']['spki']['algorithm']['algorithm'],
                    $this->currentCert['publicKeyAndChallenge']['spki']['subjectPublicKey'],
                    $this->currentCert['signatureAlgorithm']['algorithm'],
                    substr(base64_decode($this->currentCert['signature']), 1),
                    $this->signatureSubject
                );
            case isset($this->currentCert['tbsCertList']):
                if (!empty($this->CAs)) {
                    for ($i = 0; $i < count($this->CAs); $i++) {
                        $ca = $this->CAs[$i];
                        switch (true) {
                            case !defined('FILE_X509_IGNORE_TYPE') && $this->currentCert['tbsCertList']['issuer'] === $ca['tbsCertificate']['subject']:
                            case defined('FILE_X509_IGNORE_TYPE') && $this->getDN(self::DN_STRING, $this->currentCert['tbsCertList']['issuer']) === $this->getDN(self::DN_STRING, $ca['tbsCertificate']['subject']):
                                $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier');
                                $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca);
                                switch (true) {
                                    case !is_array($authorityKey):
                                    case !$subjectKeyID:
                                    case isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID:
                                        if (is_array($authorityKey) && isset($authorityKey['authorityCertSerialNumber']) && !$authorityKey['authorityCertSerialNumber']->equals($ca['tbsCertificate']['serialNumber'])) {
                                            break 2; // serial mismatch - check other ca
                                        }
                                        $signingCert = $ca; // working cert
                                        break 3;
                                }
                        }
                    }
                }
                if (!isset($signingCert)) {
                    return false;
                }
                return $this->_validateSignature(
                    $signingCert['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'],
                    $signingCert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'],
                    $this->currentCert['signatureAlgorithm']['algorithm'],
                    substr(base64_decode($this->currentCert['signature']), 1),
                    $this->signatureSubject
                );
            default:
                return false;
        }
    }
10394
public static boolean isSelfSigned(X509Certificate cert,
        String sigProvider) {
        if (isSelfIssued(cert)) {
            try {
                if (sigProvider == null) {
                    cert.verify(cert.getPublicKey());
                } else {
                    cert.verify(cert.getPublicKey(), sigProvider);
                }
                return true;
            } catch (Exception e) {
                // In case of exception, return false
            }
        }
        return false;
    }
1195792
public static void validate(byte[] cert, String pass) throws Exception {

        try {
            KeyStore keyStore = KeyStore.getInstance(ALGORITHM);
            keyStore.load(new ByteArrayInputStream(cert), pass.toCharArray());
        } catch (Exception e) {
            throw new Exception("Certificate is not valid!", e);
        }
    }
72928
private function checkSignature($signature, $status, $code)
    {
        if (!$signature) {
            throw new EndpointException("Invalid signature");
        }
      
        $data = $this->app->getAppId() . $this->requestId . $this->connectId . $code . $status;
        $result = openssl_verify($data, $signature, $this->app->getSecretKey(), OPENSSL_ALGO_SHA512);
        
        if ($result < 1) {
            $errstr = openssl_error_string();

            throw new EndpointException("Invalid signature or an openssl error (" . ($errstr ? $errstr : "-") . ")");
        }
    }
800543
private function getCertificate($certificatePath)
    {
        $httpCurlRequest  = new HttpCurl($this->ipnConfig);

    $response = $httpCurlRequest->httpGet($certificatePath);

        return $response;
    }
199083
public function verifySignature($data, $signature)
    {
        switch ($this->cryptParams['library']) {
            case 'openssl':
                return $this->verifyOpenSSL($data, $signature);
            case (self::HMAC_SHA1):
                $expectedSignature = hash_hmac("sha1", $data, $this->key, true);
                return strcmp($signature, $expectedSignature) == 0;
        }
    }
1237931
public function verifySign($data = '', $sign = '')
    {
        if (!is_string($sign) || !is_string($sign)) {
            return false;
        }
        return (bool)openssl_verify(
                      $data,
                      base64_decode($sign),
                      self::getPublicKey(),
                      OPENSSL_ALGO_SHA256
                    );
    }
570581
private function verifyPHPECCSignature(JWKInterface $key, $data, $R, $S)
    {
        $p = $this->getGenerator();
        $x = $this->convertBase64ToGmp($key->get('x'));
        $y = $this->convertBase64ToGmp($key->get('y'));
        $hash = $this->convertHexToGmp(hash($this->getHashAlgorithm(), $data));

        $public_key = $p->getPublicKeyFrom($x, $y);

        $signer = EccFactory::getSigner();

        return $signer->verify(
            $public_key,
            new Signature(
                $this->convertHexToGmp($R),
                $this->convertHexToGmp($S)
            ),
            $hash
        );
    }
1049867
private boolean verifySignature(X509Certificate cert)
        throws CertPathValidatorException {

        try {
            Signature respSignature = Signature.getInstance(sigAlgId.getName());
            respSignature.initVerify(cert.getPublicKey());
            respSignature.update(tbsResponseData);

            if (respSignature.verify(signature)) {
                if (debug != null) {
                    debug.println("Verified signature of OCSP Response");
                }
                return true;

            } else {
                if (debug != null) {
                    debug.println(
                        "Error verifying signature of OCSP Response");
                }
                return false;
            }
        } catch (InvalidKeyException | NoSuchAlgorithmException |
                 SignatureException e)
        {
            throw new CertPathValidatorException(e);
        }
    }
823921
public function sign(string $data, string $secret): string
    {
        $signature = hash_hmac($this->algorithm, $data, $secret);

        return $signature;
    }
150224
public function setSSLCert($certPath, $passPhrase = null)
    {
        $this->curlOptions[CURLOPT_SSLCERT] = realpath($certPath);
        if (isset($passPhrase) && trim($passPhrase) != "") {
            $this->curlOptions[CURLOPT_SSLCERTPASSWD] = $passPhrase;
        }
    }
702648
@Override
	public X509Certificate sign(Trans trans, CSRMeta csrmeta) throws IOException, CertException {
		GregorianCalendar gc = new GregorianCalendar();
		Date start = gc.getTime();
		gc.add(GregorianCalendar.DAY_OF_MONTH, 1);
		Date end = gc.getTime();
		X509Certificate x509;
		TimeTaken tt = trans.start("Create/Sign Cert",Env.SUB);
		try {
			BigInteger bi;
			synchronized(serialish) {
				random.nextBytes(serialish);
				bi = new BigInteger(serialish);
			}
				
			X509v3CertificateBuilder xcb = new X509v3CertificateBuilder(
					issuer,
					bi, // replace with Serialnumber scheme
					start,
					end,
					csrmeta.x500Name(),
//					SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(caCert.getPublicKey().getEn)
					new SubjectPublicKeyInfo(ASN1Sequence.getInstance(caCert.getPublicKey().getEncoded()))
					);
			List<GeneralName> lsan = new ArrayList<GeneralName>();
			for(String s : csrmeta.sans()) {
				lsan.add(new GeneralName(GeneralName.dNSName,s));
			}
			GeneralName[] sans = new GeneralName[lsan.size()];
			lsan.toArray(sans);

		    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
		    xcb		.addExtension(Extension.basicConstraints,
                    	false, new BasicConstraints(false))
		            .addExtension(Extension.keyUsage,
		                true, new KeyUsage(KeyUsage.digitalSignature
		                                 | KeyUsage.keyEncipherment))
		            .addExtension(Extension.extendedKeyUsage,
		                          true, new ExtendedKeyUsage(ASN_WebUsage))

                    .addExtension(Extension.authorityKeyIdentifier,
		                          false, extUtils.createAuthorityKeyIdentifier(caCert))
		            .addExtension(Extension.subjectKeyIdentifier,
		                          false, extUtils.createSubjectKeyIdentifier(caCert.getPublicKey()))
		            .addExtension(Extension.subjectAlternativeName,
		            		false, new GeneralNames(sans))
		                                           ;
	
			x509 = new JcaX509CertificateConverter().getCertificate(
					xcb.build(BCFactory.contentSigner(caKey)));
		} catch (GeneralSecurityException|OperatorCreationException e) {
			throw new CertException(e);
		} finally {
			tt.done();
		}
		return x509;
	}
546840
function verify($data, $signature) {
    $status = openssl_verify($data, $signature, $this->publicKey, "sha256");
    if ($status === -1) {
      throw new Exception('Signature verification error: ' . openssl_error_string());
    }
    return $status === 1;
  }