Check if a public key is in the certificate store.
@param publicKey needs to be a 32 byte array representing the public key
543126
public boolean containsPublicKey(byte[] publicKey)
    {
        Utils.checkArgument(
                            publicKey.length == 32,
                            "publickey needs to have a size of 32 bytes. got only " + publicKey.length);
        return containsPublicKey(ZMQ.Curve.z85Encode(publicKey));
    }
1011524
public static PublicKey loadPublicKeyFromKeyStore(String location,String alias,String storeType,String storePass,String keyPass){
        try {			
        	storeType = null == storeType ? KeyStore.getDefaultType() : storeType;
        	keyPass = keyPass == null ? storePass : keyPass;
        	KeyStore keyStore = KeyStore.getInstance(storeType);
        	InputStream is = new FileInputStream(location);
        	keyStore.load(is, storePass.toCharArray());
        	
        	RSAPrivateCrtKey key = (RSAPrivateCrtKey) keyStore.getKey(alias, keyPass.toCharArray());
			RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(),
					key.getPublicExponent());
			PublicKey publicKey = KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(spec);
            return publicKey;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
    }
958163
public static PublicKey readPublicKeyFromCert(InputStream in) {
		final Certificate certificate = readX509Certificate(in);
		if (null != certificate) {
			return certificate.getPublicKey();
		}
		return null;
	}
520074
def load_pkcs12(self, key):
        
        self.x509 = key.get_certificate().to_cryptography()
        self.public_key = key.get_certificate().to_cryptography().public_key()
        self.private_key = key.get_privatekey().to_cryptography_key()
960363
public boolean verifySignature(byte[] publicKey, byte[] message, byte[] signature) {
    if (publicKey == null || publicKey.length != 32) {
      throw new IllegalArgumentException("Invalid public key!");
    }

    if (message == null || signature == null || signature.length != 64) {
      return false;
    }

    return provider.verifySignature(publicKey, message, signature);
  }
996313
public static boolean checkByPublicKey(String data, String sign, String publicKey) throws Exception {
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		byte[] encodedKey = base64.decode(publicKey);
		PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
		java.security.Signature signature = java.security.Signature.getInstance("SHA256WithRSA");
		signature.initVerify(pubKey);
		signature.update(data.getBytes("utf-8"));
		return signature.verify(base64.decode(sign.getBytes("UTf-8")));
	}
583444
def fully_valid_pubkey?
      return false unless valid_pubkey?
      point = ECDSA::Format::PointOctetString.decode(pubkey.htb, ECDSA::Group::Secp256k1)
      ECDSA::Group::Secp256k1.valid_public_key?(point)
    end
656520
public static boolean ciphersSupported (PublicKey key)
    {
        return getRSACipher(key) != null && getAESCipher(Cipher.ENCRYPT_MODE, new byte[16]) != null;
    }
129774
private synchronized PublicKey fetchPublicKey(JsonNode messageJson) {
        URI certUrl = URI.create(messageJson.get(SIGNING_CERT_URL).asText());
        PublicKey publicKey = certificateCache.get(certUrl.toString());
        if (publicKey == null) {
            publicKey = createPublicKey(downloadCertWithRetries(certUrl));
            certificateCache.add(certUrl.toString(), publicKey);
        }
        return publicKey;
    }
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
220363
public void checkKeyStore() {
        if (sslContext != null)
            return; //nothing to check if using preconfigured context
        
        if (keyStoreInputStream == null &&
	    sslConfig.getKeyStorePath() == null) {
            throw new IllegalStateException("SSL doesn't have a valid keystore");
        }
        // if the keystore has been configured but there is no
        // truststore configured, use the keystore as the truststore
        if (trustStoreInputStream == null && sslConfig.getTrustStorePath() == null) {
            trustStoreInputStream = keyStoreInputStream;
            sslConfig.setTrustStorePath(sslConfig.getKeyStorePath());
            sslConfig.setTrustStoreType(sslConfig.getKeyStoreType());
            sslConfig.setTrustStoreProvider(sslConfig.getKeyStoreProvider());
            sslConfig.setTrustStorePassword(sslConfig.getKeyStorePassword());
            sslConfig.setTrustManagerFactoryAlgorithm(sslConfig.getKeyManagerFactoryAlgorithm());
        }

        // It's the same stream we cannot read it twice, so read it once in memory
        if (keyStoreInputStream != null && keyStoreInputStream == trustStoreInputStream) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
		streamCopy(keyStoreInputStream, baos, null, false);
                keyStoreInputStream.close();
                keyStoreInputStream = new ByteArrayInputStream(baos.toByteArray());
                trustStoreInputStream = new ByteArrayInputStream(baos.toByteArray());
            } catch (Exception ex) {
                throw new IllegalStateException(ex);
            }
        }
    }
1203741
public static String encryptByPublicKey(String data, String publicKey) throws Exception {
		return encryptByPublicKey(data, publicKey, "RSA/ECB/PKCS1Padding");
	}
428210
public synchronized boolean containsKey(CacheKey key) {
    Preconditions.checkNotNull(key);
    if (!mMap.containsKey(key)) {
      return false;
    }
    EncodedImage storedEncodedImage = mMap.get(key);
    synchronized (storedEncodedImage) {
      if (!EncodedImage.isValid(storedEncodedImage)) {
        // Reference is not valid, this means that someone cleared reference while it was still in
        // use. Log error
        // TODO: 3697790
        mMap.remove(key);
        FLog.w(
            TAG,
            "Found closed reference %d for key %s (%d)",
            System.identityHashCode(storedEncodedImage),
            key.getUriString(),
            System.identityHashCode(key));
        return false;
      }
      return true;
    }
  }
386578
public boolean checkKeyBelongsToNode(byte[] key, int nodeId) {
        List<Integer> nodePartitions = cluster.getNodeById(nodeId).getPartitionIds();
        List<Integer> replicatingPartitions = getReplicatingPartitionList(key);
        // remove all partitions from the list, except those that belong to the
        // node
        replicatingPartitions.retainAll(nodePartitions);
        return replicatingPartitions.size() > 0;
    }
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);
        }
    }
1055528
public static String getPEMFromRSAPublicKey(RSAPublicKey publicKey) {
        StringBuilder builder = new StringBuilder();
        builder.append("-----BEGIN PUBLIC KEY-----\n");

        String encoded  = new String(BASE_64.encode(publicKey.getEncoded()));

        int start = 0;
        int end = 64;
        try {
            //noinspection InfiniteLoopStatement
            while (true) {
                builder.append(encoded.substring(start, end));
                builder.append("\n");
                start = end;
                end = start + 64;
            }
        } catch (IndexOutOfBoundsException e) {
            if (start != encoded.length()) {
                builder.append(encoded.substring(start, encoded.length()));
                builder.append("\n");
            }
        }

        builder.append("-----END PUBLIC KEY-----\n");
        return builder.toString();
    }
184299
private static KeyStore saveCertificateAsKeyStore(KeyStore existingKeyStore, boolean deleteOnExit, String keyStoreFileName, String certificationAlias, Key privateKey, char[] keyStorePassword, Certificate[] chain, X509Certificate caCert) {
        try {
            KeyStore keyStore = existingKeyStore;
            if (keyStore == null) {
                // create new key store
                keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(null, keyStorePassword);
            }

            // add certificate
            try {
                keyStore.deleteEntry(certificationAlias);
            } catch (KeyStoreException kse) {
                // ignore as may not exist in keystore yet
            }
            keyStore.setKeyEntry(certificationAlias, privateKey, keyStorePassword, chain);

            // add CA certificate
            try {
                keyStore.deleteEntry(KEY_STORE_CA_ALIAS);
            } catch (KeyStoreException kse) {
                // ignore as may not exist in keystore yet
            }
            keyStore.setCertificateEntry(KEY_STORE_CA_ALIAS, caCert);

            // save as JKS file
            String keyStoreFileAbsolutePath = new File(keyStoreFileName).getAbsolutePath();
            try (FileOutputStream fileOutputStream = new FileOutputStream(keyStoreFileAbsolutePath)) {
                keyStore.store(fileOutputStream, keyStorePassword);
                MOCK_SERVER_LOGGER.trace("Saving key store to file [" + keyStoreFileAbsolutePath + "]");
            }
            if (deleteOnExit) {
                new File(keyStoreFileAbsolutePath).deleteOnExit();
            }
            return keyStore;
        } catch (Exception e) {
            throw new RuntimeException("Exception while saving KeyStore", e);
        }
    }