Converts EC key pair to JSON web key.

@param keyPair
EC key pair
@param provider
Java security provider
@return the JSON web key, converted from EC key pair.
502431
public static JsonWebKey fromEC(KeyPair keyPair, Provider provider) {

        ECPublicKey apub = (ECPublicKey) keyPair.getPublic();
        ECPoint point = apub.getW();
        ECPrivateKey apriv = (ECPrivateKey) keyPair.getPrivate();

        if (apriv != null) {
            return new JsonWebKey().withKty(JsonWebKeyType.EC).withCrv(getCurveFromKeyPair(keyPair, provider))
                    .withX(point.getAffineX().toByteArray()).withY(point.getAffineY().toByteArray())
                    .withD(apriv.getS().toByteArray()).withKty(JsonWebKeyType.EC);
        } else {
            return new JsonWebKey().withKty(JsonWebKeyType.EC).withCrv(getCurveFromKeyPair(keyPair, provider))
                    .withX(point.getAffineX().toByteArray()).withY(point.getAffineY().toByteArray())
                    .withKty(JsonWebKeyType.EC);
        }
    }
1306961
public <K, V> Pair<K, V> getPair(String key, Class<K> keyClass, Class<V> valueClass) {
        return getValue(Pair.class, key);
    }
1086360
private RSAPublicKey getKeyForUser(String userName) throws KeyNotFoundException {
    RSAPublicKey key = null;
    for (final KeyProvider keyProvider : keyProviders) {
      try {
        key = keyProvider.getKey(userName);
        break;
      } catch (KeyNotFoundException e) {
        // that's fine, try the next provider
      }
    }

    if (key == null) {
      throw new KeyNotFoundException();
    }

    return key;
  }
1175307
private static String getKeyValuePair(final String key, final String value, 
        final boolean formEncoding)
        {
        final StringBuilder sb = new StringBuilder ();
        
        final String firstEncoded;
        final String secondEncoded;
        if (formEncoding)
            {
            firstEncoded = urlFormEncode (key);
            secondEncoded = urlFormEncode (value);
            }
        else
            {
            firstEncoded = urlNonFormEncode (key);
            secondEncoded = urlNonFormEncode (value);
            }
        sb.append (firstEncoded);
        sb.append ('=');
        sb.append (secondEncoded);
        
        return sb.toString ();
        }
569255
public static RsaJsonWebKey getJsonWebKeyFromJsonWebKeySet(final JsonWebKeySet jwks) {
        if (jwks.getJsonWebKeys().isEmpty()) {
            LOGGER.warn("No JSON web keys are available in the keystore");
            return null;
        }

        val key = (RsaJsonWebKey) jwks.getJsonWebKeys().get(0);
        if (StringUtils.isBlank(key.getAlgorithm())) {
            LOGGER.warn("Located JSON web key [{}] has no algorithm defined", key);
        }
        if (StringUtils.isBlank(key.getKeyId())) {
            LOGGER.warn("Located JSON web key [{}] has no key id defined", key);
        }

        if (key.getPublicKey() == null) {
            LOGGER.warn("Located JSON web key [{}] has no public key", key);
            return null;
        }
        return key;
    }
249059
public static <T> Provider<T> guicify(javax.inject.Provider<T> provider) {
    if (provider instanceof Provider) {
      return (Provider<T>) provider;
    }

    final javax.inject.Provider<T> delegate = checkNotNull(provider, "provider");

    // Ensure that we inject all injection points from the delegate provider.
    Set<InjectionPoint> injectionPoints =
        InjectionPoint.forInstanceMethodsAndFields(provider.getClass());
    if (injectionPoints.isEmpty()) {
      return new GuicifiedProvider<T>(delegate);
    } else {
      Set<Dependency<?>> mutableDeps = Sets.newHashSet();
      for (InjectionPoint ip : injectionPoints) {
        mutableDeps.addAll(ip.getDependencies());
      }
      final Set<Dependency<?>> dependencies = ImmutableSet.copyOf(mutableDeps);
      return new GuicifiedProviderWithDependencies<T>(dependencies, delegate);
    }
  }
957356
public static String convertToJavaIdentifier( String key, JsonConfig jsonConfig ) {
      try{
         return jsonConfig.getJavaIdentifierTransformer()
               .transformToJavaIdentifier( key );
      }catch( JSONException jsone ){
         throw jsone;
      }catch( Exception e ){
         throw new JSONException( e );
      }
   }
314573
public KeyPair toEC(boolean includePrivateParameters, Provider provider) {

        if (provider == null) {
            // Our default provider for this class
            provider = Security.getProvider("SunEC");
        }

        if (!JsonWebKeyType.EC.equals(kty) && !JsonWebKeyType.EC_HSM.equals(kty)) {
            throw new IllegalArgumentException("Not an EC key.");
        }

        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", provider);

            ECGenParameterSpec gps = new ECGenParameterSpec(CURVE_TO_SPEC_NAME.get(crv));
            kpg.initialize(gps);

            // Generate dummy keypair to get parameter spec.
            KeyPair apair = kpg.generateKeyPair();
            ECPublicKey apub = (ECPublicKey) apair.getPublic();
            ECParameterSpec aspec = apub.getParams();

            ECPoint ecPoint = new ECPoint(new BigInteger(1, x), new BigInteger(1, y));

            KeyPair realKeyPair;

            if (includePrivateParameters) {
                realKeyPair = new KeyPair(getECPublicKey(ecPoint, aspec, provider),
                        getECPrivateKey(d, aspec, provider));
            } else {
                realKeyPair = new KeyPair(getECPublicKey(ecPoint, aspec, provider), null);
            }

            return realKeyPair;
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e);
        }
    }
1324190
public static java.security.KeyPair generateLongTermRevocationKey() {
        try {
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
            SecureRandom random = new SecureRandom();
            AlgorithmParameterSpec params = new ECGenParameterSpec("secp384r1");
            keyGen.initialize(params, random);

            return keyGen.generateKeyPair();
        } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
            throw new RuntimeException("Error during the LTRevocation key. Invalid algorithm");
        }
    }
943231
public static List<String> convertProviderToUrls(ProviderConfig providerConfig) {
        @SuppressWarnings("unchecked")
        List<ServerConfig> servers = providerConfig.getServer();
        if (servers != null && !servers.isEmpty()) {
            List<String> urls = new ArrayList<String>();
            for (ServerConfig server : servers) {
                StringBuilder sb = new StringBuilder(200);
                String host = server.getVirtualHost(); // 虚拟ip
                if (host == null) {
                    host = server.getHost();
                    if (NetUtils.isLocalHost(host) || NetUtils.isAnyHost(host)) {
                        host = SystemInfo.getLocalHost();
                    }
                }

                Map<String, String> metaData = convertProviderToMap(providerConfig, server);
                //noinspection unchecked
                sb.append(server.getProtocol()).append("://").append(host).append(":")
                    .append(server.getPort()).append(server.getContextPath()).append("?version=1.0")
                    .append(convertMap2Pair(metaData));
                urls.add(sb.toString());
            }
            return urls;
        }
        return null;
    }
53432
public static RSAPrivateKey getRSAPrivateKeyFromPEM(Provider provider, String pem) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA", provider);
            return (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(getKeyBytesFromPEM(pem)));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("Algorithm SHA256withRSA is not available", e);
        } catch (InvalidKeySpecException e) {
            throw new IllegalArgumentException("Invalid PEM provided", e);
        }
    }
392647
private static String getProviderProperty(String key, Provider provider) {
        String prop = provider.getProperty(key);
        if (prop == null) {
            // Is there a match if we do a case-insensitive property name
            // comparison? Let's try ...
            for (Enumeration<Object> e = provider.keys();
                                e.hasMoreElements() && prop == null; ) {
                String matchKey = (String)e.nextElement();
                if (key.equalsIgnoreCase(matchKey)) {
                    prop = provider.getProperty(matchKey);
                    break;
                }
            }
        }
        return prop;
    }
1080196
function loadKeyPair (pub, prv, use) {
  var pubPEM, prvPEM, pubJWK

  try {
    pubPEM = fs.readFileSync(pub).toString('ascii')
  } catch (e) {
    throw new Error('Unable to read the public key from ' + pub)
  }

  try {
    prvPEM = fs.readFileSync(prv).toString('ascii')
  } catch (e) {
    throw new Error('Unable to read the private key from ' + pub)
  }

  try {
    pubJWK = pemjwk.pem2jwk(pubPEM)
  } catch (e) {
    throw new Error('Unable to convert the public key ' + pub + ' to a JWK')
  }

  return {
    pem: {
      pub: pubPEM,
      prv: prvPEM
    },
    jwk: {
      pub: {
        kty: pubJWK.kty,
        use: use,
        alg: 'RS256',
        n: pubJWK.n,
        e: pubJWK.e
      }
    }
  }
}
100194
private static SFPair<OcspResponseCacheKey, SFPair<Long, String>>
  decodeCacheFromJSON(Map.Entry<String, JsonNode> elem) throws IOException
  {
    long currentTimeSecond = new Date().getTime() / 1000;
    byte[] certIdDer = Base64.decodeBase64(elem.getKey());
    DLSequence rawCertId = (DLSequence) ASN1ObjectIdentifier.fromByteArray(certIdDer);
    ASN1Encodable[] rawCertIdArray = rawCertId.toArray();
    byte[] issuerNameHashDer = ((DEROctetString) rawCertIdArray[1]).getEncoded();
    byte[] issuerKeyHashDer = ((DEROctetString) rawCertIdArray[2]).getEncoded();
    BigInteger serialNumber = ((ASN1Integer) rawCertIdArray[3]).getValue();

    OcspResponseCacheKey k = new OcspResponseCacheKey(
        issuerNameHashDer, issuerKeyHashDer, serialNumber);

    JsonNode ocspRespBase64 = elem.getValue();
    if (!ocspRespBase64.isArray() || ocspRespBase64.size() != 2)
    {
      LOGGER.debug("Invalid cache file format.");
      return null;
    }
    long producedAt = ocspRespBase64.get(0).asLong();
    String ocspResp = ocspRespBase64.get(1).asText();

    if (currentTimeSecond - CACHE_EXPIRATION_IN_SECONDS <= producedAt)
    {
      // add cache
      return SFPair.of(k, SFPair.of(producedAt, ocspResp));
    }
    else
    {
      // delete cache
      return SFPair.of(k, SFPair.of(producedAt, (String) null));
    }
  }
162818
protected Key getKeyByType(KeyType type) {
		switch (type) {
		case PrivateKey:
			if (null == this.privateKey) {
				throw new NullPointerException("Private key must not null when use it !");
			}
			return this.privateKey;
		case PublicKey:
			if (null == this.publicKey) {
				throw new NullPointerException("Public key must not null when use it !");
			}
			return this.publicKey;
		}
		throw new CryptoException("Uknown key type: " + type);
	}
806749
public static KeyPair newKeyPair(final PublicKey publicKey, final PrivateKey privateKey)
	{
		final KeyPair keyPair = new KeyPair(publicKey, privateKey);
		return keyPair;
	}
1150183
public static KeyPair keyPair() {
            KeyPair kp = new KeyPair();

            crypto_sign_keypair(kp.getPublicKey(), kp.getSecretKey(), false);
            return kp;
        }