Check the signature algorithm with the specified public key.

@param key the public key to verify the CRL signature
@param crl the target CRL
767515
static void check(PublicKey key, X509CRL crl)
                        throws CertPathValidatorException {

        X509CRLImpl x509CRLImpl = null;
        try {
            x509CRLImpl = X509CRLImpl.toImpl(crl);
        } catch (CRLException ce) {
            throw new CertPathValidatorException(ce);
        }

        AlgorithmId algorithmId = x509CRLImpl.getSigAlgId();
        check(key, algorithmId);
    }
291410
def Verify(self, public_key):
    
    # TODO(amoser): We have to do this manually for now since cryptography does
    # not yet support cert verification. There is PR 2460:
    # https://github.com/pyca/cryptography/pull/2460/files
    # that will add it, once it's in we should switch to using this.

    # Note that all times here are in UTC.
    now = rdfvalue.RDFDatetime.Now().AsDatetime()
    if now > self._value.not_valid_after:
      raise VerificationError("Certificate expired!")
    if now < self._value.not_valid_before:
      raise VerificationError("Certificate not yet valid!")

    public_key.Verify(
        self._value.tbs_certificate_bytes,
        self._value.signature,
        hash_algorithm=self._value.signature_hash_algorithm)
    return True
1140424
def key_verify(rsakey, signature, message, digest):
    """"""
    padding = _asymmetric.padding.PKCS1v15()
    if isinstance(rsakey, _asymmetric.rsa.RSAPrivateKey):
        rsakey = rsakey.public_key()

    try:
        rsakey.verify(signature, message, padding, digest)
    except Exception as e:
        return False
    else:
        return True
10859
private static void validateKey(String key) {
		if (key == null || key.length() > MAX_KEY_SIZE) {
			throw new IllegalArgumentException("Invalid key - must be non null and have a length less than " + MAX_KEY_SIZE);
		}
	}
1164335
public void hasLastKey(@NullableDecl Object key) {
    if (actualAsNavigableMap().isEmpty()) {
      failWithActual("expected to have last key", key);
      return;
    }

    if (!Objects.equal(actualAsNavigableMap().lastKey(), key)) {
      if (actualAsNavigableMap().containsKey(key)) {
        failWithoutActual(
            simpleFact(
                lenientFormat(
                    "Not true that %s has last key <%s>. "
                        + "It does contain this key, but the last key is <%s>",
                    actualAsString(), key, actualAsNavigableMap().lastKey())));
        return;
      }
      failWithoutActual(
          simpleFact(
              lenientFormat(
                  "Not true that %s has last key <%s>. "
                      + "It does not contain this key, and the last key is <%s>",
                  actualAsString(), key, actualAsNavigableMap().lastKey())));
    }
  }
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;
	}
262122
public static boolean verifySignature(byte[] publicKey, byte[] message, byte[] signature) {
        return curve_sigs.curve25519_verify(SHA512Provider, signature, publicKey, message, message.length) == 0;
    }
920181
@Override
    public Builder signWith(String algorithm, String key) throws KeyException {

        if (algorithm == null || algorithm.isEmpty() || !algorithm.equals(Constants.SIGNATURE_ALG_HS256)) {
            String err = Tr.formatMessage(tc, "JWT_INVALID_ALGORITHM_ERR", new Object[] { algorithm, Constants.SIGNATURE_ALG_HS256 });
            throw new KeyException(err);
        }
        if (key == null || key.isEmpty()) {
            String err = Tr.formatMessage(tc, "JWT_INVALID_KEY_ERR", new Object[] { algorithm, key });
            throw new KeyException(err);
        }
        alg = algorithm;
        sharedKey = key;
        return this;
    }
1036367
public boolean setPublicKey (String key)
    {
        return key == null ? false : setPublicKey(SecureUtil.stringToRSAPublicKey(key));
    }
474825
public void sign(OneKey key) throws CoseException {
        if (rgbContent == null) throw new CoseException("No Content Specified");
        if (rgbSignature != null) return;

        if (rgbProtected == null) {
            if (objProtected.size() > 0) rgbProtected = objProtected.EncodeToBytes();
            else rgbProtected = new byte[0];
        }
                
        CBORObject obj = CBORObject.NewArray();
        obj.Add(contextString);
        obj.Add(rgbProtected);
        obj.Add(externalData);
        obj.Add(rgbContent);
        
        rgbSignature = computeSignature(obj.EncodeToBytes(), key);
        
        ProcessCounterSignatures();
    }
466335
public static PublicKey generatePublicKey(String algorithm, byte[] key) {
		if (null == key) {
			return null;
		}
		return generatePublicKey(algorithm, new X509EncodedKeySpec(key));
	}
880988
function signSPKAC($signatureAlgorithm = 'sha1WithRSAEncryption')
    {
        if (!is_object($this->privateKey)) {
            return false;
        }

        $origPublicKey = $this->publicKey;
        $class = get_class($this->privateKey);
        $this->publicKey = new $class();
        $this->publicKey->loadKey($this->privateKey->getPublicKey());
        $this->publicKey->setPublicKey();
        $publicKey = $this->_formatSubjectPublicKey();
        if (!$publicKey) {
            return false;
        }
        $this->publicKey = $origPublicKey;

        $currentCert = isset($this->currentCert) ? $this->currentCert : null;
        $signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject: null;

        // re-signing a SPKAC seems silly but since everything else supports re-signing why not?
        if (isset($this->currentCert) && is_array($this->currentCert) && isset($this->currentCert['publicKeyAndChallenge'])) {
            $this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm;
            $this->currentCert['publicKeyAndChallenge']['spki'] = $publicKey;
            if (!empty($this->challenge)) {
                // the bitwise AND ensures that the output is a valid IA5String
                $this->currentCert['publicKeyAndChallenge']['challenge'] = $this->challenge & str_repeat("\x7F", strlen($this->challenge));
            }
        } else {
            $this->currentCert = array(
                'publicKeyAndChallenge' =>
                    array(
                        'spki' => $publicKey,
                        // quoting <https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen>,
                        // "A challenge string that is submitted along with the public key. Defaults to an empty string if not specified."
                        // both Firefox and OpenSSL ("openssl spkac -key private.key") behave this way
                        // we could alternatively do this instead if we ignored the specs:
                        // Random::string(8) & str_repeat("\x7F", 8)
                        'challenge' => !empty($this->challenge) ? $this->challenge : ''
                    ),
                    'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm),
                    'signature'          => false // this is going to be overwritten later
            );
        }

        // resync $this->signatureSubject
        // save $publicKeyAndChallenge in case there are any \phpseclib\File\ASN1\Element objects in it
        $publicKeyAndChallenge = $this->currentCert['publicKeyAndChallenge'];
        $this->loadSPKAC($this->saveSPKAC($this->currentCert));

        $result = $this->_sign($this->privateKey, $signatureAlgorithm);
        $result['publicKeyAndChallenge'] = $publicKeyAndChallenge;

        $this->currentCert = $currentCert;
        $this->signatureSubject = $signatureSubject;

        return $result;
    }
205831
public void doesNotContainKey(@NullableDecl Object key) {
    check("keySet()").that(actual().keySet()).doesNotContain(key);
  }
581511
private static boolean issues(X509CertImpl cert, X509CRLImpl crl,
                                  String provider) throws IOException
    {
        boolean matched = false;

        AdaptableX509CertSelector issuerSelector =
                                    new AdaptableX509CertSelector();

        // check certificate's key usage
        boolean[] usages = cert.getKeyUsage();
        if (usages != null) {
            usages[6] = true;       // cRLSign
            issuerSelector.setKeyUsage(usages);
        }

        // check certificate's subject
        X500Principal crlIssuer = crl.getIssuerX500Principal();
        issuerSelector.setSubject(crlIssuer);

        /*
         * Facilitate certification path construction with authority
         * key identifier and subject key identifier.
         *
         * In practice, conforming CAs MUST use the key identifier method,
         * and MUST include authority key identifier extension in all CRLs
         * issued. [section 5.2.1, RFC 2459]
         */
        AuthorityKeyIdentifierExtension crlAKID = crl.getAuthKeyIdExtension();
        if (crlAKID != null) {
            issuerSelector.parseAuthorityKeyIdentifierExtension(crlAKID);
        }

        matched = issuerSelector.match(cert);

        // if AKID is unreliable, verify the CRL signature with the cert
        if (matched && (crlAKID == null ||
                cert.getAuthorityKeyIdentifierExtension() == null)) {
            try {
                crl.verify(cert.getPublicKey(), provider);
                matched = true;
            } catch (GeneralSecurityException e) {
                matched = false;
            }
        }

        return matched;
    }
467598
private boolean verifyUsingPublicKey(byte[] data, byte[] signature, PublicKey pubKey)
            throws GeneralSecurityException {
        Signature sig = Signature.getInstance("SHA256withRSA");
        sig.initVerify(pubKey);
        sig.update(data);
        return sig.verify(signature);
    }
801505
public void proveIdentity(byte[] sharedSecret, KeyPair key) throws IOException, GeneralSecurityException {
        String algorithm = detectKeyAlgorithm(key);
        writeUTF(algorithm);
        writeKey(key.getPublic());

        Signature sig = Signature.getInstance("SHA1with"+algorithm);
        sig.initSign(key.getPrivate());
        sig.update(key.getPublic().getEncoded());
        sig.update(sharedSecret);
        writeObject(sig.sign());
    }
252128
public static void setEncryptionKey(final String key) {

		if (key == null) {

			logger.info("set_encryption_key() was called with null parameter, resetting global secret key");

			// reset hash
			secretKeyHash = null;
			return;
		}

		try {

			secretKeyHash = MessageDigest.getInstance(HASH_ALGO).digest(key.getBytes("UTF-8"));

		} catch (Throwable t) {
			logger.error("Unable to set secret key: {}", t.getMessage());
		}
	}