本文整理汇总了Java中org.jose4j.jwk.JsonWebKey类的典型用法代码示例。如果您正苦于以下问题:Java JsonWebKey类的具体用法?Java JsonWebKey怎么用?Java JsonWebKey使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
JsonWebKey类属于org.jose4j.jwk包,在下文中一共展示了JsonWebKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: generate
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
/**
* Generate.
*/
@PostConstruct
public void generate() {
try {
final File file = oidcProperties.getJwksFile().getFile();
if (!file.exists()) {
final RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
final JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(rsaJsonWebKey);
final String data = jsonWebKeySet.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);
FileUtils.write(file, data, StandardCharsets.UTF_8);
LOGGER.debug("Generated JSON web keystore at [{}]", file);
} else {
LOGGER.debug("Located JSON web keystore at [{}]", file);
}
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
示例2: buildJwks
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
/**
* Builds JWKS if necessary after 60 seconds, but only builds
* {@value #MIN_NUMBER_OF_KEYS} at a time.
*/
@Scheduled(fixedDelay = 60000)
public void buildJwks() {
int nCreated = 0;
for (int i = 0; i < MAX_NUMBER_OF_KEYS; ++i) {
final String cacheKey = String.valueOf(i);
final JsonWebKey jwk = jwksCache.get(cacheKey, JsonWebKey.class);
if (jwk == null && nCreated < MIN_NUMBER_OF_KEYS) {
final RsaJsonWebKey newJwk = buildNewRsaKey();
jwksCache.putIfAbsent(cacheKey, newJwk);
++nCreated;
LOG.debug("Created new JWK kid={}", newJwk.getKeyId());
}
}
}
示例3: extractX509Certificate
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
private JsonWebKeySet extractX509Certificate(String json) {
Map<String, String> certificates = parse(json, new TypeReference<Map<String, String>>() {});
ImmutableList.Builder<JsonWebKey> jwkBuilder = ImmutableList.builder();
X509Util x509Util = new X509Util();
for (Entry<String, String> entry : certificates.entrySet()) {
try {
String cert = entry.getValue().trim()
.replace(X509_CERT_PREFIX, "")
.replace(X509_CERT_SUFFIX, "");
X509Certificate x509Certificate = x509Util.fromBase64Der(cert);
PublicKey publicKey = x509Certificate.getPublicKey();
JsonWebKey jwk = toJsonWebKey(publicKey);
jwk.setKeyId(entry.getKey());
jwkBuilder.add(jwk);
} catch (JoseException exception) {
throw new UnauthenticatedException("Failed to parse public key", exception);
}
}
return new JsonWebKeySet(jwkBuilder.build());
}
示例4: verify
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
@Override
public boolean verify(String authToken, String issuer) {
Preconditions.checkNotNull(authToken);
Preconditions.checkNotNull(issuer);
try {
JsonWebKeySet jwks = this.jwksSupplier.supply(issuer);
JsonWebSignature jws = new JsonWebSignature();
jws.setCompactSerialization(authToken);
for (JsonWebKey jwk : this.jwkSelector.selectList(jws, jwks.getJsonWebKeys())) {
jws.setKey(jwk.getKey());
if (jws.verifySignature()) {
return true;
}
}
} catch (JoseException exception) {
throw new UnauthenticatedException("Cannot verify the signature", exception);
}
return false;
}
示例5: testSupplyJwksFromX509Certificate
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
@Test
public void testSupplyJwksFromX509Certificate() throws
NoSuchAlgorithmException, JsonProcessingException {
RsaJsonWebKey rsaJsonWebKey = TestUtils.generateRsaJsonWebKey("key-id");
String cert = TestUtils.generateX509Cert(rsaJsonWebKey);
String keyId = "key-id";
String json = OBJECT_WRITER.writeValueAsString(ImmutableMap.of(keyId, cert));
HttpTransport httpTransport = new TestingHttpTransport(json, null);
DefaultJwksSupplier jwksSupplier =
new DefaultJwksSupplier(httpTransport.createRequestFactory(), keyUriSupplier);
JsonWebKeySet jsonWebKeySet = jwksSupplier.supply(ISSUER);
JsonWebKey jsonWebKey = Iterables.getOnlyElement(jsonWebKeySet.getJsonWebKeys());
assertEquals(keyId, jsonWebKey.getKeyId());
assertKeysEqual(rsaJsonWebKey.getPublicKey(), jsonWebKey.getKey());
}
示例6: jwtBadSig
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
@Test (expected = InvalidJwtSignatureException.class)
public void jwtBadSig() throws Exception
{
String jwt = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9." +
"eyJpc3MiOiJqb2UiLAogImV4cCI6MTkwMDgxOTM4MCwKICJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZX0." +
"dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
String jwk = "{\"kty\":\"oct\",\"k\":\"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow\"}";
JwtConsumer consumer = new JwtConsumerBuilder()
.setVerificationKey(JsonWebKey.Factory.newJwk(jwk).getKey())
.setEvaluationTime(NumericDate.fromSeconds(1900000380))
.setExpectedIssuer("joe")
.setRequireExpirationTime()
.build();
consumer.process(jwt);
}
示例7: encOnlyWithIntegrityIssues
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
@Test
public void encOnlyWithIntegrityIssues() throws Exception
{
String jwt = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..zWNzKpA-QA0BboVl02nz-A.oSy4V6cQ6EnuIMyazDCqc9jEZMC7k8LwLKkrC12Pf-wpFRyDtQjGdIZ_Ndq9JMAnrCbx0bgFSxjKISbXbcnHiA.QsGX3JhHP1Pwy4zQ8Ha9FQ";
JsonWebKey jsonWebKey = JsonWebKey.Factory.newJwk("{\"kty\":\"oct\",\"k\":\"30WEMkbhwHPBkg_fIfm_4GuzIz5pPZB7_BSfI3dHbbQ\"}");
DecryptionKeyResolver decryptionKeyResolver = new JwksDecryptionKeyResolver(Collections.singletonList(jsonWebKey));
JwtConsumer consumer = new JwtConsumerBuilder()
.setDecryptionKeyResolver(decryptionKeyResolver)
.setEvaluationTime(NumericDate.fromSeconds(1420230888))
.setExpectedAudience("me")
.setExpectedIssuer("me")
.setRequireExpirationTime()
.setDisableRequireSignature()
.build();
JwtClaims jwtClaims = consumer.processToClaims(jwt);
Assert.assertThat("value", equalTo(jwtClaims.getStringClaimValue("name")));
// change some things and make sure it fails
jwt = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..zWNzKpA-QA0BboVl02nz-A.eyJpc3MiOiJtZSIsImF1ZCI6Im1lIiwiZXhwIjoxNDIwMjMxNjA2LCJuYW1lIjoidmFsdWUifQ.QsGX3JhHP1Pwy4zQ8Ha9FQ";
SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, consumer);
jwt = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..zWNzKpA-QA0BboVl02nz-A.u1D7JCpDFeRl69G1L-h3IRrmcOXiWLnhr23ugO2kkDqKVNcO1YQ4Xvl9Sag4aYOnkqUbqe6Wdz8KK3d9q178tA.QsGX3JhHP1Pwy4zQ8Ha9FQ";
SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, consumer);
}
示例8: testJweExampleA3
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
@Test
public void testJweExampleA3() throws JoseException
{
// http://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-14#appendix-A.3
String jweCsFromAppdxA3 = "eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0." +
"6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ." +
"AxY8DCtDaGlsbGljb3RoZQ." +
"KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY." +
"U0m_YmjN04DJvceFICbCVQ";
JsonWebEncryption jwe = new JsonWebEncryption();
JsonWebKey jsonWebKey = JsonWebKey.Factory.newJwk("\n" +
"{\"kty\":\"oct\",\n" +
" \"k\":\"GawgguFyGrWKav7AX4VKUg\"\n" +
"}");
jwe.setCompactSerialization(jweCsFromAppdxA3);
jwe.setKey(new AesKey(jsonWebKey.getKey().getEncoded()));
String plaintextString = jwe.getPlaintextString();
assertEquals("Live long and prosper.", plaintextString);
}
示例9: testJwBadZipValueConsume
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
public void testJwBadZipValueConsume() throws JoseException
{
String cs = "eyJ6aXAiOiJiYWQiLCJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.." +
"ZZZ0nR5f80ikJtaPot4RpQ." +
"BlDAYKzn9oLH1fhZcR60ZKye7UHslg7s0h7s1ecNZ5A1Df1pq2pBWUwdRKjJRxJAEFbDFoXTFYjV-cLCCE2Uxw." +
"zasDvsZ3U4YkTDgIUchjiA";
JsonWebKey jsonWebKey = JsonWebKey.Factory.newJwk("{\"kty\":\"oct\",\"k\":\"q1qm8z2sLFt_CPqwpLuGm-fX6ZKQKnukPHpoJOeykCw\"}");
JsonWebEncryption jwe = new JsonWebEncryption();
jwe.setKey(jsonWebKey.getKey());
jwe.setCompactSerialization(cs);
try
{
String plaintextString = jwe.getPlaintextString();
fail("Should fail with invalid zip header value but gave: " + plaintextString);
}
catch (InvalidAlgorithmException e)
{
// just see if the exception message says something about the header name
assertTrue(e.getMessage().contains(HeaderParameterNames.ZIP));
}
}
示例10: testSuccessClientGeneratedECKeys
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
@Test
public void testSuccessClientGeneratedECKeys() throws Exception {
JsonWebKey popKey = EcJwkGenerator.generateJwk(EllipticCurves.P256);
popKey.setKeyId("testkid");
TokenRequest req = new TokenRequest();
req.setGrantType("client_credentials");
req.setAud(config.getResourceServers().get(0).getAud());
req.setClientID(config.getClients().get(0).getClient_id());
req.setClientSecret(config.getClients().get(0).getClient_secret());
req.setScopes(config.getResourceServers().get(0).getScopes());
req.setKey(popKey);
Response response = DTLSUtils.dtlsPSKRequest("coaps://localhost:"+config.getCoapsPort()+"/"+Constants.TOKEN_RESOURCE, "POST", req.toPayload(MediaTypeRegistry.APPLICATION_JSON), MediaTypeRegistry.APPLICATION_JSON, config.getPskIdentity(), config.getPskKey().getBytes());
Assert.assertEquals(ResponseCode.CONTENT, response.getCode());
TokenResponse tokenResponse = new TokenResponse(response.getPayload(), MediaTypeRegistry.APPLICATION_JSON);
TestUtils.validateToken(tokenResponse.getAccessToken().getBytes(), config.getResourceServers().get(0).getAud(), MediaTypeRegistry.APPLICATION_JSON);
}
示例11: testSuccessClientGeneratedRSAKeys
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
@Test
public void testSuccessClientGeneratedRSAKeys() throws Exception {
JsonWebKey popKey = RsaJwkGenerator.generateJwk(2048);
popKey.setKeyId("testkid");
TokenRequest req = new TokenRequest();
req.setGrantType("client_credentials");
req.setAud(config.getResourceServers().get(0).getAud());
req.setClientID(config.getClients().get(0).getClient_id());
req.setClientSecret(config.getClients().get(0).getClient_secret());
req.setScopes(config.getResourceServers().get(0).getScopes());
req.setKey(popKey);
Response response = DTLSUtils.dtlsPSKRequest("coaps://localhost:"+config.getCoapsPort()+"/"+Constants.TOKEN_RESOURCE, "POST", req.toPayload(MediaTypeRegistry.APPLICATION_JSON), MediaTypeRegistry.APPLICATION_JSON, config.getPskIdentity(), config.getPskKey().getBytes());
Assert.assertEquals(ResponseCode.CONTENT, response.getCode());
TokenResponse tokenResponse = new TokenResponse(response.getPayload(), MediaTypeRegistry.APPLICATION_JSON);
TestUtils.validateToken(tokenResponse.getAccessToken().getBytes(), config.getResourceServers().get(0).getAud(), MediaTypeRegistry.APPLICATION_JSON);
}
示例12: testScopes
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
@Test
public void testScopes() throws Exception {
JsonWebKey jwk;
jwk = EcJwkGenerator.generateJwk(EllipticCurves.P256);
jwk.setKeyId("testkid");
TokenRequest req = new TokenRequest();
req.setGrantType("client_credentials");
req.setAud(config.getResourceServers().get(0).getAud());
req.setClientID(config.getClients().get(0).getClient_id());
req.setClientSecret(config.getClients().get(0).getClient_secret());
req.setScopes(config.getResourceServers().get(0).getScopes());
req.setKey(jwk);
Response response = DTLSUtils.dtlsPSKRequest("coaps://localhost:"+config.getCoapsPort()+"/"+Constants.TOKEN_RESOURCE, "POST", req.toPayload(MediaTypeRegistry.APPLICATION_JSON), MediaTypeRegistry.APPLICATION_JSON, config.getPskIdentity(), config.getPskKey().getBytes());
TokenResponse tokenResponse = new TokenResponse(response.getPayload(), MediaTypeRegistry.APPLICATION_JSON);
TestUtils.validateToken(tokenResponse.getAccessToken().getBytes(), config.getResourceServers().get(0).getAud(), MediaTypeRegistry.APPLICATION_JSON);
}
示例13: generateJWT
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
public void generateJWT() throws Exception {
// Generate a new RSA key pair wrapped in a JWK
PublicJsonWebKey rsaJwk = RsaJwkGenerator.generateJwk(2048);
// or an EC key, if you prefer
PublicJsonWebKey ecJwk = EcJwkGenerator.generateJwk(EllipticCurves.P256);
// A JSON string with only the public key info
String publicKeyJwkString = rsaJwk.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY);
System.out.println(publicKeyJwkString);
// A JSON string with both the public and private key info
String keyPairJwkString = rsaJwk.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);
System.out.println(keyPairJwkString);
// parse and convert into PublicJsonWebKey/JsonWebKey objects
PublicJsonWebKey parsedPublicKeyJwk = PublicJsonWebKey.Factory.newPublicJwk(publicKeyJwkString);
PublicJsonWebKey parsedKeyPairJwk = PublicJsonWebKey.Factory.newPublicJwk(keyPairJwkString);
// the private key can be used to sign (JWS) or decrypt (JWE)
PrivateKey privateKey = parsedKeyPairJwk.getPrivateKey();
// the public key can be used to verify (JWS) or encrypt (JWE)
PublicKey publicKey = parsedPublicKeyJwk.getPublicKey();
}
示例14: main
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
/**
* Generates a new keypair for unit tests, and return its N, E, KTY and THUMBPRINT
* parameters to be set in the {@link TestUtils} class.
*/
public static void main(String... args) throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
try (FileOutputStream out = new FileOutputStream("public.key")) {
out.write(keyPair.getPublic().getEncoded());
}
try (FileOutputStream out = new FileOutputStream("private.key")) {
out.write(keyPair.getPrivate().getEncoded());
}
final JsonWebKey jwk = JsonWebKey.Factory.newJwk(keyPair.getPublic());
Map<String, Object> params = new TreeMap<>(jwk.toParams(OutputControlLevel.PUBLIC_ONLY));
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(JsonUtil.toJson(params).getBytes("UTF-8"));
byte[] thumbprint = md.digest();
System.out.println("N = " + params.get("n"));
System.out.println("E = " + params.get("e"));
System.out.println("KTY = " + params.get("kty"));
System.out.println("THUMBPRINT = " + Base64Url.encode(thumbprint));
}
示例15: prepareJsonWebTokenKey
import org.jose4j.jwk.JsonWebKey; //导入依赖的package包/类
/**
* Prepare json web token key.
*
* @param secret the secret
* @return the key
*/
private Key prepareJsonWebTokenKey(final String secret) {
try {
final Map<String, Object> keys = new HashMap<>(2);
keys.put("kty", "oct");
keys.put("k", secret);
final JsonWebKey jwk = JsonWebKey.Factory.newJwk(keys);
return jwk.getKey();
} catch (final Exception e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}