本文整理汇总了Java中com.nimbusds.jose.jwk.JWK类的典型用法代码示例。如果您正苦于以下问题:Java JWK类的具体用法?Java JWK怎么用?Java JWK使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
JWK类属于com.nimbusds.jose.jwk包,在下文中一共展示了JWK类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: init
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
@PostConstruct
public void init() {
InputStream inputStream = TokenGenerator.class.getClassLoader().getResourceAsStream("rsa.keyset");
String content = new Scanner(inputStream).useDelimiter("\\Z").next();
try {
jwkSet = JWKSet.parse(content);
inputStream.close();
} catch (ParseException | IOException e) {
e.printStackTrace();
// FIXME
}
keys = jwkSet.getKeys().stream().map(JWK::getKeyID).collect(Collectors.toList());
}
示例2: verifyPropertiesWithSignature
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
/**
* verifies a set of Properties against a signature and and a public key
* @param data - the data a sorted Map of Strings
* @param base64Signature - the signature
* @param jwk -the public key
* @return true, if the properties match the signature
*/
public static boolean verifyPropertiesWithSignature(SortedMap<String, String> data, String base64Signature,
JWK jwk) {
try {
String message = generateMessagesFromProperties(data);
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initVerify(((RSAKey) jwk).toRSAPublicKey());
signature.update(message.getBytes(StandardCharsets.ISO_8859_1));
return signature.verify(Base64.getDecoder().decode(base64Signature));
} catch (Exception e) {
LOGGER.error(e);
}
return false;
}
示例3: retrievePublicKeyFromLoginToken
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
/**
* retrieves the client public key from Login Token
*
* @param token - the serialized JSON Web Token from login
* @return the public key as JWK object
*/
public static JWK retrievePublicKeyFromLoginToken(String token) {
JWK result = null;
JWEObject jweObject;
try {
jweObject = JWEObject.parse(token);
// Decrypt with shared key
jweObject.decrypt(new RSADecrypter(RSA_KEYS.getPrivate()));
// Extract payload
SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();
result = signedJWT.getHeader().getJWK();
RSAKey publicKey = RSAKey.parse(result.toJSONObject());
if (signedJWT.verify(new RSASSAVerifier(publicKey))) {
return result;
}
} catch (ParseException | JOSEException e) {
LOGGER.error(e);
}
return null;
}
示例4: createEmptyJWTwithPublicKey
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
/**
* creates an empty JSON Web Token
*
* @param webAppBaseURL - the base url of the application
*
* @return the JSON WebToken
*/
public static SignedJWT createEmptyJWTwithPublicKey(String webAppBaseURL) {
ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC);
JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(webAppBaseURL).jwtID(UUID.randomUUID().toString())
.issueTime(Date.from(currentTime.toInstant())).build();
String keyID = UUID.randomUUID().toString();
JWK jwk = new RSAKey.Builder((RSAPublicKey) RSA_KEYS.getPublic()).keyID(keyID).build();
JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).jwk(jwk).build();
SignedJWT signedJWT = new SignedJWT(jwsHeader, claims);
try {
signedJWT.sign(new RSASSASigner(RSA_KEYS.getPrivate()));
} catch (JOSEException e) {
LOGGER.error(e);
}
return signedJWT;
}
示例5: createJWT
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
/**
* creates a JSON Web Token with user id, roles and client public key
*
* @param user - the user that should be returned
* @param roles - the roles that should be returned
* @param webAppBaseURL - the base url of the application
* @param clientPublicKey - the client public key as JSON Web Key
*
* @return the JSON WebToken
*/
public static SignedJWT createJWT(String user, List<String> roles, String webAppBaseURL, JWK clientPublicKey) {
ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC);
JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(webAppBaseURL).jwtID(UUID.randomUUID().toString())
.expirationTime(Date.from(currentTime.plusMinutes(EXPIRATION_TIME_MINUTES).toInstant()))
.issueTime(Date.from(currentTime.toInstant()))
.notBeforeTime(Date.from(currentTime.minusMinutes(EXPIRATION_TIME_MINUTES).toInstant())).subject(user)
// additional claims/attributes about the subject can be added
// claims.setClaim("email", "[email protected]");
// multi-valued claims work too and will end up as a JSON array
.claim("roles", roles).claim("sub_jwk", clientPublicKey).build();
String keyID = UUID.randomUUID().toString();
JWK jwk = new RSAKey.Builder((RSAPublicKey) RSA_KEYS.getPublic()).keyID(keyID).build();
JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).jwk(jwk).build();
SignedJWT signedJWT = new SignedJWT(jwsHeader, claims);
try {
signedJWT.sign(new RSASSASigner(RSA_KEYS.getPrivate()));
} catch (JOSEException e) {
// TODO Auto-generated catch block
LOGGER.error(e);
}
System.out.println("JWT: " + signedJWT.serialize());
return signedJWT;
}
示例6: main
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
public static void main(String[] args) {
Map<String, Info> info = new HashMap<>();
// user name, apiKey/roles
info.put("Rudy", new Info("49c2b80f-12a5-4464-abad-152cc2cacedb", newRoles("user", "manager")));
info.put("Soteria", new Info("0a1726c7-068a-4de0-ac64-d27a52cbfce2", newRoles("user")));
System.out.println("Correct tokens");
info.forEach(
(k, v) -> {
String publicContent = readFile(v.getApiKey() + ".jwk");
try {
JWK publicJWK = JWK.parse(publicContent);
String apiKey = publicJWK.getKeyID();
System.out.println("Subject = " + k + " -> token = " + createToken(k, (RSAKey) publicJWK, apiKey, v.getRoles()));
} catch (ParseException | JOSEException e) {
e.printStackTrace();
}
}
);
}
示例7: getKey
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
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;
}
示例8: getUsageType
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
/**
* Convert jwk key usage type to shibboleth usage type.
*
* @param jwk
* containing usage type.
* @return usage type.
*/
private UsageType getUsageType(JWK jwk) {
switch (jwk.getKeyUse()) {
case ENCRYPTION:
return UsageType.ENCRYPTION;
case SIGNATURE:
return UsageType.SIGNING;
default:
return UsageType.UNSPECIFIED;
}
}
示例9: doCreateInstance
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
/** {@inheritDoc} */
@Override
protected BasicJWKCredential doCreateInstance() throws Exception {
if (jwkResource == null) {
log.error("{}: No JWK credential provided", getConfigDescription());
throw new BeanCreationException("No JWK credential provided");
}
JWK jwk = null;
BasicJWKCredential jwkCredential = null;
try (InputStream is = jwkResource.getInputStream()) {
jwk = JWK.parse(new String(ByteStreams.toByteArray(is)));
jwkCredential = new BasicJWKCredential();
if (jwk.getKeyType() == KeyType.EC || jwk.getKeyType() == KeyType.RSA) {
if (jwk.isPrivate()) {
jwkCredential.setPrivateKey(((AssymetricJWK) jwk).toPrivateKey());
}
jwkCredential.setPublicKey(((AssymetricJWK) jwk).toPublicKey());
} else if (jwk.getKeyType() == KeyType.OCT) {
jwkCredential.setSecretKey(((OctetSequenceKey) jwk).toSecretKey());
} else {
throw new FatalBeanException("Unsupported KeyFile at " + jwkResource.getDescription());
}
} catch (IOException | ParseException | JOSEException e) {
log.error("{}: Could not decode KeyFile at {}: {}",
getConfigDescription(), jwkResource.getDescription(), e);
throw new FatalBeanException("Could not decode provided KeyFile " + jwkResource.getDescription(), e);
}
jwkCredential.setUsageType(getUsageType(jwk));
jwkCredential.setEntityId(getEntityID());
jwkCredential.setAlgorithm(jwk.getAlgorithm());
jwkCredential.setKid(jwk.getKeyID());
final List<String> keyNames = getKeyNames();
if (keyNames != null) {
jwkCredential.getKeyNames().addAll(keyNames);
}
return jwkCredential;
}
示例10: setCredential
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
/**
* Set the credential to be resolved as JSON.
* @param credential What to set.
*/
public void setCredential(final Credential credential) {
Constraint.isNotNull(credential, "Credential cannot be null!");
final PublicKey publicKey = credential.getPublicKey();
String kid = credential instanceof JWKCredential ? ((JWKCredential) credential).getKid() : null;
final KeyUse use;
switch (credential.getUsageType()) {
case SIGNING:
use = KeyUse.SIGNATURE; break;
case ENCRYPTION:
use = KeyUse.ENCRYPTION; break;
default:
use = null;
}
final JWK jwk;
if ((publicKey instanceof RSAPublicKey)) {
final RSAKey.Builder builder = new RSAKey.Builder((RSAPublicKey) publicKey).keyID(kid).keyUse(use);
if (credential instanceof JWKCredential) {
builder.algorithm(((JWKCredential) credential).getAlgorithm());
}
jwk = builder.build();
} else {
// TODO: support other algorithms
log.warn("Unsupported public key {}", publicKey.getAlgorithm());
throw new ConstraintViolationException("Unsupported public key algorithm");
}
jsonCredential = jwk.toJSONObject();
}
示例11: getJWKSigningKey
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
public JWK getJWKSigningKey() {
boolean multiple = false;
JWK result = null;
for (JWK jwk : jwkSet.getKeys()) {
if (jwk.isPrivate() && jwk.getKeyUse() == KeyUse.SIGNATURE) {
if (result == null) {
result = jwk;
} else {
multiple = true;
}
}
}
if (multiple) {
throw new ConfigurationException("FIXME Multiple signing keys");
}
if (result == null) {
throw new ConfigurationException("FIXME No signing key found");
}
return result;
}
示例12: withSecretKeyForSigning
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
public JWTParametersBuilder withSecretKeyForSigning(JWK key) {
if (encoding == JWTEncoding.NONE) {
logger.warn("SecretKey value is not supported with JWTEncoding.NONE");
}
secretKeySigning = key;
determineSecretKeyType();
return this;
}
示例13: withSecretKeyForEncryption
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
public JWTParametersBuilder withSecretKeyForEncryption(JWK key) {
if (encoding != JWTEncoding.JWE) {
logger.warn("SecretKey value for encryption only needed for JWTEncoding.JWE");
}
secretKeyEncryption = key;
return this;
}
示例14: selectSecretKey
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
@Override
public <T extends Key> T selectSecretKey(String keyId) {
if (jwkManager.existsApiKey(keyId)) {
JWK jwk = jwkManager.getJWKForApiKey(keyId);
try {
if (jwk instanceof SecretJWK) {
return (T) ((SecretJWK) jwk).toSecretKey();
}
if (jwk instanceof AssymetricJWK) {
return (T) ((AssymetricJWK) jwk).toPublicKey();
}
throw new UnsupportedOperationException("JWK not supported " + jwk.getClass().getName());
} catch (JOSEException e) {
e.printStackTrace();
// FIXME
}
}
return null;
}
示例15: parse
import com.nimbusds.jose.jwk.JWK; //导入依赖的package包/类
public static OfflineToken parse(String token, String passPhrase) {
String localSecret = LocalSecretFactory.generateSecret(passPhrase);
JWTDecoder decode = new JWTDecoder();
JWK hmac = new HMACSecret(localSecret, LOCAL_SECRET_KEY_ID, true);
KeySelector selector = new SingleKeySelector(hmac);
JWTData<OfflineToken> jwtData = decode.decode(token, OfflineToken.class, selector, new OfflineTokenVerifier());
return jwtData.getData();
}