com.nimbusds.jose.jwk.JWK类的使用及代码示例

x33g5p2x  于2022-01-22 转载在 其他  
字(12.7k)|赞(0)|评价(0)|浏览(556)

本文整理了Java中com.nimbusds.jose.jwk.JWK类的一些代码示例,展示了JWK类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JWK类的具体详情如下:
包路径:com.nimbusds.jose.jwk.JWK
类名称:JWK

JWK介绍

[英]The base abstract class for JSON Web Keys (JWKs). It serialises to a JSON object.

The following JSON object members are common to all JWK types:

  • #getKeyType (required)
  • #getKeyUse (optional)
  • #getKeyOperations (optional)
  • #getKeyID (optional)
  • #getX509CertURL() (optional)
  • #getX509CertThumbprint() (optional)
  • #getX509CertSHA256Thumbprint() (optional)
  • #getX509CertChain() (optional)
  • #getKeyStore()

Example JWK (of the Elliptic Curve type):

{ 
"kty" : "EC", 
"crv" : "P-256", 
"x"   : "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", 
"y"   : "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", 
"use" : "enc", 
"kid" : "1" 
}

[中]JSON Web键(JWKs)的基本抽象类。它序列化为一个JSON对象。
以下JSON对象成员对于所有JWK类型都是通用的:
*#getKeyType(必需)
*#getKeyUse(可选)
*#getKeyOperations(可选)
*#getKeyID(可选)
*#getX509CertURL()(可选)
*#getX509CertThumbprint()(可选)
*#getX509CertSHA256Thumbprint()(可选)
*#getX509CertChain()(可选)
*#getKeyStore()
示例JWK(椭圆曲线类型):

{ 
"kty" : "EC", 
"crv" : "P-256", 
"x"   : "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", 
"y"   : "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", 
"use" : "enc", 
"kid" : "1" 
}

代码示例

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

/**
 * Build this service based on the given keystore. All keys must have a key
 * id ({@code kid}) field in order to be used.
 *
 * @param keyStore
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws JOSEException
 */
public DefaultJWTEncryptionAndDecryptionService(JWKSetKeyStore keyStore) throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException {
  // convert all keys in the keystore to a map based on key id
  for (JWK key : keyStore.getKeys()) {
    if (!Strings.isNullOrEmpty(key.getKeyID())) {
      this.keys.put(key.getKeyID(), key);
    } else {
      throw new IllegalArgumentException("Tried to load a key from a keystore without a 'kid' field: " + key);
    }
  }
  buildEncryptersAndDecrypters();
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void getWhenMatchThenCreatesKeys() {
  when(this.matcher.matches(any())).thenReturn(true);
  List<JWK> keys = this.source.get(this.selector).block();
  assertThat(keys).hasSize(2);
  JWK key1 = keys.get(0);
  assertThat(key1.getKeyID()).isEqualTo("1923397381d9574bb873202a90c32b7ceeaed027");
  assertThat(key1.getAlgorithm().getName()).isEqualTo("RS256");
  assertThat(key1.getKeyType()).isEqualTo(KeyType.RSA);
  assertThat(key1.getKeyUse()).isEqualTo(KeyUse.SIGNATURE);
  JWK key2 = keys.get(1);
  assertThat(key2.getKeyID()).isEqualTo("7ddf54d3032d1f0d48c3618892ca74c1ac30ad77");
  assertThat(key2.getAlgorithm().getName()).isEqualTo("RS256");
  assertThat(key2.getKeyType()).isEqualTo(KeyType.RSA);
  assertThat(key2.getKeyUse()).isEqualTo(KeyUse.SIGNATURE);
}

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

@Override
public Map<String, JWK> getAllPublicKeys() {
  Map<String, JWK> pubKeys = new HashMap<>();
  // pull all keys out of the verifiers if we know how
  for (String keyId : keys.keySet()) {
    JWK key = keys.get(keyId);
    JWK pub = key.toPublicJWK();
    if (pub != null) {
      pubKeys.put(keyId, pub);
    }
  }
  return pubKeys;
}

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

encrypters.put(id, encrypter);
if (jwk.isPrivate()) { // we can decrypt!
  RSADecrypter decrypter = new RSADecrypter((RSAKey) jwk);
  decrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance());
  decrypters.put(id, decrypter);
} else {
  logger.warn("No private key for key #" + jwk.getKeyID());
encrypters.put(id, encrypter);
if (jwk.isPrivate()) { // we can decrypt too
  ECDHDecrypter decrypter = new ECDHDecrypter((ECKey) jwk);
  decrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance());
  decrypters.put(id, decrypter);
} else {
  logger.warn("No private key for key # " + jwk.getKeyID());

代码示例来源:origin: com.nimbusds/nimbus-jose-jwt

if (hasUse && key.getKeyUse() == null)
  return false;
if (hasID && (key.getKeyID() == null || key.getKeyID().trim().isEmpty()))
  return false;
if (privateOnly && ! key.isPrivate())
  return false;
if (publicOnly && key.isPrivate())
  return false;
if (types != null && ! types.contains(key.getKeyType()))
  return false;
if (uses != null && ! uses.contains(key.getKeyUse()))
  return false;
  if (ops.contains(null) && key.getKeyOperations() == null) {
  } else if (key.getKeyOperations() != null && ops.containsAll(key.getKeyOperations())) {
if (algs != null && ! algs.contains(key.getAlgorithm()))
  return false;
if (ids != null && ! ids.contains(key.getKeyID()))
  return false;
  if (key.size() < minSizeBits)

代码示例来源:origin: gravitee-io/graviteeio-access-management

private JWK convert(com.nimbusds.jose.jwk.JWK nimbusJwk) {
  RSAKey jwk = new RSAKey();
  if (nimbusJwk.getKeyType() != null) {
    jwk.setKty(nimbusJwk.getKeyType().getValue());
  if (nimbusJwk.getKeyUse() != null) {
    jwk.setUse(nimbusJwk.getKeyUse().identifier());
  if (nimbusJwk.getKeyOperations() != null) {
    jwk.setKeyOps(nimbusJwk.getKeyOperations().stream().map(keyOperation -> keyOperation.identifier()).collect(Collectors.toSet()));
  if (nimbusJwk.getAlgorithm() != null) {
    jwk.setAlg(nimbusJwk.getAlgorithm().getName());
  if (nimbusJwk.getKeyID() != null) {
    jwk.setKid(nimbusJwk.getKeyID());
  if (nimbusJwk.getX509CertURL() != null) {
    jwk.setX5u(nimbusJwk.getX509CertURL().toString());
  if (nimbusJwk.getX509CertChain() != null) {
    jwk.setX5c(nimbusJwk.getX509CertChain().stream().map(cert -> cert.toString()).collect(Collectors.toSet()));
  if (nimbusJwk.getX509CertThumbprint() != null) {
    jwk.setX5t(nimbusJwk.getX509CertThumbprint().toString());
  if (nimbusJwk.getX509CertSHA256Thumbprint() != null) {
    jwk.setX5tS256(nimbusJwk.getX509CertSHA256Thumbprint().toString());

代码示例来源:origin: de.adorsys.sts/sts-crypto-utils

public StsServerKeyMap(JWKSet jwkSet) {
  List<JWK> keys = jwkSet.getKeys();
  for (JWK jwk : keys) {
    if (jwk instanceof RSAKey) {
      Key key = KeyConverter.toPrivateOrSecret(jwk);
      if(key!=null && jwk.getKeyID()!=null){
        KeyAndJwk keyAndJwk = new KeyAndJwk(key, jwk);
        keyMap.put(jwk.getKeyID(), keyAndJwk);
        if(KeyUse.SIGNATURE.equals(jwk.getKeyUse())){
          signKeyList.add(keyAndJwk);
        } else if (KeyUse.ENCRYPTION.equals(jwk.getKeyUse())){
          encKeyList.add(keyAndJwk);
        }
      }
    } else if (jwk instanceof SecretJWK) {
      Key key = KeyConverter.toPrivateOrSecret(jwk);
      if(key!=null && jwk.getKeyID()!=null){
        KeyAndJwk keyAndJwk = new KeyAndJwk(key, jwk);
        keyMap.put(jwk.getKeyID(), keyAndJwk);
        secretKeyList.add(keyAndJwk);
      }
    }
  }
}

代码示例来源:origin: GoogleCloudPlatform/java-docs-samples

private ECPublicKey getKey(String kid, String alg) throws Exception {
 JWK jwk = keyCache.get(kid);
 if (jwk == null) {
  // update cache loading jwk public key data from url
  JWKSet jwkSet = JWKSet.load(new URL(PUBLIC_KEY_VERIFICATION_URL));
  for (JWK key : jwkSet.getKeys()) {
   keyCache.put(key.getKeyID(), key);
  }
  jwk = keyCache.get(kid);
 }
 // confirm that algorithm matches
 if (jwk != null && jwk.getAlgorithm().getName().equals(alg)) {
  return ECKey.parse(jwk.toJSONString()).toECPublicKey();
 }
 return null;
}

代码示例来源:origin: de.adorsys.cryptoutils/jjwk

boolean change = false;
for (JWK jwk : keys) {
  String keyID = jwk.getKeyID();
  Base64URL thumbprint = jwk.computeThumbprint();
  String expectedKeyId = thumbprint.toString().toLowerCase();
  if(!StringUtils.equals(keyID, expectedKeyId)){

代码示例来源:origin: de.adorsys.sts/sts-simple-encryption

private JWK tryToParseJwk(String key) {
    JWK parsedKey;

    try {
      parsedKey = JWK.parse(key);
    } catch (ParseException e) {
      throw new IllegalArgumentException(e);
    }

    return parsedKey;
  }
}

代码示例来源:origin: de.adorsys.cryptoutils/jjwk

public static JWSAlgorithm getJWSAlgo(KeyAndJwk randomKey) {
  Algorithm algorithm = randomKey.jwk.getAlgorithm();
  if(algorithm!=null && (algorithm instanceof JWSAlgorithm)) return (JWSAlgorithm) algorithm;
  
  KeyType keyType = randomKey.jwk.getKeyType();
  if(keyType!=null){
    if(KeyType.RSA.equals(keyType)){
      return JWSAlgorithm.RS256;
    } else if(KeyType.EC.equals(keyType)){
      return JWSAlgorithm.ES256;
    } else if(KeyType.OCT.equals(keyType)){
      return JWSAlgorithm.HS256;
    } else {
      throw new IllegalStateException("Unknown key type: " + keyType);
    }
  } else {
    if(randomKey.jwk instanceof RSAKey){
      return JWSAlgorithm.RS256;
    } else if (randomKey.jwk instanceof ECKey){
      return JWSAlgorithm.ES256;
    } else if (randomKey.jwk instanceof OctetSequenceKey){
      return JWSAlgorithm.HS256;
    } else {
      throw new IllegalStateException("Unknown key type: " + randomKey.jwk.getClass().getName());				
    }
  }
}

代码示例来源:origin: io.gravitee.am.gateway.handlers/gravitee-am-gateway-handler

private JWK convert(com.nimbusds.jose.jwk.JWK jwk) {
  if (jwk == null) {
    return null;
  }
  switch (KeyType.valueOf(jwk.getKeyType().getValue())) {
    case EC:
      return fromEC((com.nimbusds.jose.jwk.ECKey) jwk);
    case RSA:
      return fromRSA((com.nimbusds.jose.jwk.RSAKey) jwk);
    case OCT:
      throw new NotImplementedException("JWK Key Type:" + KeyType.OCT.getKeyType());
    case OKP:
      throw new NotImplementedException("JWK Key Type:" + KeyType.OKP.getKeyType());
    default:
      throw new InvalidClientMetadataException("Unknown JWK Key Type (kty)");
  }
}

代码示例来源:origin: de.adorsys.cryptoutils/jjwk

try {
  Algorithm alg = jwk.getAlgorithm();
  if(alg!=null){
    if(alg instanceof JWSAlgorithm) {

代码示例来源:origin: com.nimbusds/nimbus-jose-jwt

/**
 * Returns the JSON object representation of this JSON Web Key (JWK) 
 * set.
 *
 * @param publicKeysOnly Controls the inclusion of private keys and
 *                       parameters into the output JWK members. If
 *                       {@code true} private keys and parameters will
 *                       be omitted. If {@code false} all available key
 *                       parameters will be included.
 *
 * @return The JSON object representation.
 */
public JSONObject toJSONObject(final boolean publicKeysOnly) {
  JSONObject o = new JSONObject(customMembers);
  JSONArray a = new JSONArray();
  for (JWK key: keys) {
    if (publicKeysOnly) {
      // Try to get public key, then serialise
      JWK publicKey = key.toPublicJWK();
      if (publicKey != null) {
        a.add(publicKey.toJSONObject());
      }
    } else {
      a.add(key.toJSONObject());
    }
  }
  o.put("keys", a);
  return o;
}

代码示例来源:origin: de.adorsys.cryptoutils/jjwk

public ServerKeyMap(JWKSet jwkSet){
  List<JWK> keys = jwkSet.getKeys();
  for (JWK jwk : keys) {
    if (jwk instanceof AssymetricJWK) {
      Key key = KeyConverter.toPrivateOrSecret(jwk);
      if(key!=null && jwk.getKeyID()!=null){
        KeyAndJwk keyAndJwk = new KeyAndJwk(key, jwk);
        keyMap.put(jwk.getKeyID(), keyAndJwk);
        if(KeyUse.SIGNATURE.equals(jwk.getKeyUse())){
          signKeyList.add(keyAndJwk);
        } else if (KeyUse.ENCRYPTION.equals(jwk.getKeyUse())){
          encKeyList.add(keyAndJwk);
        }
      }
    } else if (jwk instanceof SecretJWK) {
      Key key = KeyConverter.toPrivateOrSecret(jwk);
      if(key!=null && jwk.getKeyID()!=null){
        KeyAndJwk keyAndJwk = new KeyAndJwk(key, jwk);
        keyMap.put(jwk.getKeyID(), keyAndJwk);
        secretKeyList.add(keyAndJwk);
      }
    }
  }
}

代码示例来源:origin: de.adorsys.sts/sts-simple-encryption

private static Key extractSecretKey(String jwkAsString) {
    Key key;

    try {
      JWK parsedKey = JWK.parse(jwkAsString);
      key = KeyConverter.toPrivateOrSecret(parsedKey, "AES");
    } catch (ParseException e) {
      throw new IllegalArgumentException(e);
    }

    return key;
  }
}

代码示例来源:origin: gravitee-io/graviteeio-access-management

private JWK convert(com.nimbusds.jose.jwk.JWK jwk) {
  if (jwk == null) {
    return null;
  }
  switch (KeyType.valueOf(jwk.getKeyType().getValue())) {
    case EC:
      return fromEC((com.nimbusds.jose.jwk.ECKey) jwk);
    case RSA:
      return fromRSA((com.nimbusds.jose.jwk.RSAKey) jwk);
    case OCT:
      throw new NotImplementedException("JWK Key Type:" + KeyType.OCT.getKeyType());
    case OKP:
      throw new NotImplementedException("JWK Key Type:" + KeyType.OKP.getKeyType());
    default:
      throw new InvalidClientMetadataException("Unknown JWK Key Type (kty)");
  }
}

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

/**
 * Build this service based on the given keystore. All keys must have a key
 * id ({@code kid}) field in order to be used.
 *
 * @param keyStore
 *            the keystore to load all keys from
 *
 * @throws InvalidKeySpecException
 *             If the keys in the JWKs are not valid
 * @throws NoSuchAlgorithmException
 *             If there is no appropriate algorithm to tie the keys to.
 */
public DefaultJWTSigningAndValidationService(JWKSetKeyStore keyStore) throws NoSuchAlgorithmException, InvalidKeySpecException {
  // convert all keys in the keystore to a map based on key id
  if (keyStore!= null && keyStore.getJwkSet() != null) {
    for (JWK key : keyStore.getKeys()) {
      if (!Strings.isNullOrEmpty(key.getKeyID())) {
        // use the key ID that's built into the key itself
        this.keys.put(key.getKeyID(), key);
      } else {
        // create a random key id
        String fakeKid = UUID.randomUUID().toString();
        this.keys.put(fakeKid, key);
      }
    }
  }
  buildSignersAndVerifiers();
}

代码示例来源:origin: com.nimbusds/nimbus-jose-jwt

/**
 * Parses a JWK from the specified JSON object string representation. 
 * The JWK must be an {@link ECKey}, an {@link RSAKey}, or a 
 * {@link OctetSequenceKey}.
 *
 * @param s The JSON object string to parse. Must not be {@code null}.
 *
 * @return The JWK.
 *
 * @throws ParseException If the string couldn't be parsed to a
 *                        supported JWK.
 */
public static JWK parse(final String s)
  throws ParseException {
  return parse(JSONObjectUtils.parse(s));
}

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

@Override
public Map<String, JWK> getAllPublicKeys() {
  Map<String, JWK> pubKeys = new HashMap<>();
  // pull out all public keys
  for (String keyId : keys.keySet()) {
    JWK key = keys.get(keyId);
    JWK pub = key.toPublicJWK();
    if (pub != null) {
      pubKeys.put(keyId, pub);
    }
  }
  return pubKeys;
}

相关文章