or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration-management.mdcryptographic-operations.mdidentity-management.mdindex.mdjose-implementation.mdsecurity-context.mdtoken-management.mdtoken-representations.mdutility-functions.md

utility-functions.mddocs/

0

# Utility Functions

1

2

Essential utility functions for token processing, JSON serialization, basic authentication, and common operations. These utilities provide foundational support for Keycloak core functionality.

3

4

## Capabilities

5

6

### Token Utilities

7

8

Comprehensive token processing and manipulation utilities for OAuth2/OIDC operations.

9

10

```java { .api }

11

/**

12

* Token processing and manipulation utilities

13

*/

14

public class TokenUtil {

15

// Token type constants

16

/** Bearer token type constant */

17

public static final String TOKEN_TYPE_BEARER = "Bearer";

18

/** DPoP token type constant */

19

public static final String TOKEN_TYPE_DPOP = "DPoP";

20

/** ID token type constant */

21

public static final String TOKEN_TYPE_ID = "ID";

22

/** Refresh token type constant */

23

public static final String TOKEN_TYPE_REFRESH = "Refresh";

24

25

/**

26

* Attach OIDC scope parameter to query parameters

27

* @param queryParams Query parameters map

28

* @param formParams Form parameters map

29

*/

30

public static void attachOIDCScope(MultivaluedMap<String, String> queryParams,

31

MultivaluedMap<String, String> formParams);

32

33

/**

34

* Check if request contains OIDC scope

35

* @param scope Space-separated scope string

36

* @return true if OIDC scope is present

37

*/

38

public static boolean isOIDCRequest(String scope);

39

40

/**

41

* Check if offline token is requested in scope

42

* @param scope Space-separated scope string

43

* @return true if offline_access scope is present

44

*/

45

public static boolean isOfflineTokenRequested(String scope);

46

47

/**

48

* Check if specific scope is present in scope string

49

* @param scopes Space-separated scope string

50

* @param targetScope Scope to check for

51

* @return true if target scope is present

52

*/

53

public static boolean hasScope(String scopes, String targetScope);

54

55

/**

56

* Parse refresh token from token string

57

* @param refreshToken JWT refresh token string

58

* @return Parsed RefreshToken object

59

* @throws TokenVerificationException if parsing fails

60

*/

61

public static RefreshToken getRefreshToken(String refreshToken) throws TokenVerificationException;

62

63

/**

64

* Check if refresh token is an offline token

65

* @param refreshToken Parsed refresh token

66

* @return true if offline token

67

*/

68

public static boolean isOfflineToken(RefreshToken refreshToken);

69

70

/**

71

* Get token type from access token

72

* @param accessToken Access token instance

73

* @return Token type string

74

*/

75

public static String getTokenType(AccessToken accessToken);

76

77

/**

78

* Check if token has specific audience

79

* @param token JWT token

80

* @param audience Audience to check

81

* @return true if audience is present

82

*/

83

public static boolean hasAudience(JsonWebToken token, String audience);

84

85

/**

86

* Get token category from token instance

87

* @param token Token instance

88

* @return TokenCategory enum value

89

*/

90

public static TokenCategory getTokenCategory(Object token);

91

92

// JWE (JSON Web Encryption) utility methods

93

94

/**

95

* Encode object as JWE using direct encryption with shared key

96

* @param input Object to encrypt

97

* @param encryptionAlg Content encryption algorithm (e.g., "A256GCM")

98

* @param contentEncAlg Content encryption algorithm identifier

99

* @param encryptionKey Symmetric encryption key

100

* @return JWE token string

101

* @throws JWEException if encryption fails

102

*/

103

public static String jweDirectEncode(Object input, String encryptionAlg,

104

String contentEncAlg, SecretKey encryptionKey)

105

throws JWEException;

106

107

/**

108

* Verify and decode JWE token using direct decryption with shared key

109

* @param jweStr JWE token string

110

* @param encryptionKey Symmetric encryption key

111

* @return Decrypted object

112

* @throws JWEException if decryption fails

113

*/

114

public static <T> T jweDirectVerifyAndDecode(String jweStr, SecretKey encryptionKey)

115

throws JWEException;

116

117

/**

118

* Encode object as JWE using key encryption (RSA/ECDH)

119

* @param input Object to encrypt

120

* @param keyAlg Key management algorithm (e.g., "RSA-OAEP")

121

* @param encryptionAlg Content encryption algorithm (e.g., "A256GCM")

122

* @param contentEncAlg Content encryption algorithm identifier

123

* @param encryptionKey Public key for key encryption

124

* @return JWE token string

125

* @throws JWEException if encryption fails

126

*/

127

public static String jweKeyEncryptionEncode(Object input, String keyAlg,

128

String encryptionAlg, String contentEncAlg,

129

PublicKey encryptionKey)

130

throws JWEException;

131

132

/**

133

* Verify and decode JWE token using key decryption

134

* @param jweStr JWE token string

135

* @param decryptionKey Private key for key decryption

136

* @return Decrypted object

137

* @throws JWEException if decryption fails

138

*/

139

public static <T> T jweKeyEncryptionVerifyAndDecode(String jweStr, PrivateKey decryptionKey)

140

throws JWEException;

141

142

/**

143

* Create JWE encrypted with password-based key derivation

144

* @param input Object to encrypt

145

* @param password Password for key derivation

146

* @param salt Salt for key derivation

147

* @param iterations PBKDF2 iterations

148

* @return JWE token string

149

* @throws JWEException if encryption fails

150

*/

151

public static String jwePasswordEncode(Object input, String password, byte[] salt, int iterations)

152

throws JWEException;

153

154

/**

155

* Decrypt password-based JWE token

156

* @param jweStr JWE token string

157

* @param password Password for key derivation

158

* @return Decrypted object

159

* @throws JWEException if decryption fails

160

*/

161

public static <T> T jwePasswordVerifyAndDecode(String jweStr, String password)

162

throws JWEException;

163

}

164

```

165

166

### JSON Serialization

167

168

JSON serialization and deserialization utilities using Jackson ObjectMapper.

169

170

```java { .api }

171

/**

172

* JSON serialization utilities using Jackson

173

*/

174

public class JsonSerialization {

175

/**

176

* Serialize object to JSON string

177

* @param obj Object to serialize

178

* @return JSON string representation

179

* @throws IOException if serialization fails

180

*/

181

public static String writeValueAsString(Object obj) throws IOException;

182

183

/**

184

* Serialize object to JSON byte array

185

* @param obj Object to serialize

186

* @return JSON byte array

187

* @throws IOException if serialization fails

188

*/

189

public static byte[] writeValueAsBytes(Object obj) throws IOException;

190

191

/**

192

* Write object to output stream as JSON

193

* @param out Output stream

194

* @param obj Object to serialize

195

* @throws IOException if serialization fails

196

*/

197

public static void writeValue(OutputStream out, Object obj) throws IOException;

198

199

/**

200

* Deserialize JSON string to object

201

* @param json JSON string

202

* @param type Target class type

203

* @return Deserialized object

204

* @throws IOException if deserialization fails

205

*/

206

public static <T> T readValue(String json, Class<T> type) throws IOException;

207

208

/**

209

* Deserialize JSON byte array to object

210

* @param json JSON byte array

211

* @param type Target class type

212

* @return Deserialized object

213

* @throws IOException if deserialization fails

214

*/

215

public static <T> T readValue(byte[] json, Class<T> type) throws IOException;

216

217

/**

218

* Deserialize JSON from input stream to object

219

* @param json JSON input stream

220

* @param type Target class type

221

* @return Deserialized object

222

* @throws IOException if deserialization fails

223

*/

224

public static <T> T readValue(InputStream json, Class<T> type) throws IOException;

225

226

/**

227

* Deserialize JSON to object with TypeReference for generic types

228

* @param json JSON string

229

* @param typeRef TypeReference for generic types

230

* @return Deserialized object

231

* @throws IOException if deserialization fails

232

*/

233

public static <T> T readValue(String json, TypeReference<T> typeRef) throws IOException;

234

235

/**

236

* Get the Jackson ObjectMapper instance

237

* @return Configured ObjectMapper

238

*/

239

public static ObjectMapper getMapper();

240

241

/**

242

* Configure ObjectMapper with custom settings

243

* @param mapper ObjectMapper to configure

244

*/

245

public static void configureMapper(ObjectMapper mapper);

246

247

/**

248

* Create a copy of an object through JSON serialization/deserialization

249

* @param obj Object to copy

250

* @param type Target class type

251

* @return Deep copy of the object

252

* @throws IOException if copy operation fails

253

*/

254

public static <T> T deepCopy(Object obj, Class<T> type) throws IOException;

255

256

/**

257

* Check if string is valid JSON

258

* @param json String to validate

259

* @return true if valid JSON

260

*/

261

public static boolean isValidJson(String json);

262

263

/**

264

* Pretty print JSON string

265

* @param json JSON string to format

266

* @return Formatted JSON string

267

* @throws IOException if formatting fails

268

*/

269

public static String prettyPrint(String json) throws IOException;

270

271

/**

272

* Convert object to JSON node for manipulation

273

* @param obj Object to convert

274

* @return JsonNode representation

275

*/

276

public static JsonNode toJsonNode(Object obj);

277

278

/**

279

* Convert JSON node to object

280

* @param node JsonNode to convert

281

* @param type Target class type

282

* @return Converted object

283

* @throws IOException if conversion fails

284

*/

285

public static <T> T fromJsonNode(JsonNode node, Class<T> type) throws IOException;

286

}

287

```

288

289

### Basic Authentication Helper

290

291

HTTP Basic authentication utilities for client authentication.

292

293

```java { .api }

294

/**

295

* HTTP Basic authentication utilities

296

*/

297

public class BasicAuthHelper {

298

/**

299

* Create HTTP Basic authentication header value

300

* @param username Username

301

* @param password Password

302

* @return Basic authentication header value (e.g., "Basic dXNlcjpwYXNz")

303

*/

304

public static String createHeader(String username, String password);

305

306

/**

307

* Parse HTTP Basic authentication header

308

* @param header Authorization header value

309

* @return Array containing username and password, or null if invalid

310

*/

311

public static String[] parseHeader(String header);

312

313

/**

314

* Extract username and password from Authorization header

315

* @param authHeader Full Authorization header value

316

* @return Array containing username and password, or null if invalid/not Basic

317

*/

318

public static String[] extractUsernamePassword(String authHeader);

319

320

/**

321

* Encode credentials for Basic authentication

322

* @param username Username

323

* @param password Password

324

* @return Base64 encoded credentials

325

*/

326

public static String encodeCredentials(String username, String password);

327

328

/**

329

* Decode Basic authentication credentials

330

* @param encodedCredentials Base64 encoded credentials

331

* @return Array containing username and password

332

* @throws IllegalArgumentException if credentials are invalid

333

*/

334

public static String[] decodeCredentials(String encodedCredentials);

335

336

/**

337

* Check if Authorization header is Basic authentication

338

* @param authHeader Authorization header value

339

* @return true if Basic authentication

340

*/

341

public static boolean isBasicAuth(String authHeader);

342

343

/**

344

* Create complete Authorization header for Basic authentication

345

* @param username Username

346

* @param password Password

347

* @return Complete Authorization header (e.g., "Authorization: Basic dXNlcjpwYXNz")

348

*/

349

public static String createAuthorizationHeader(String username, String password);

350

}

351

```

352

353

### JWK Set Utilities

354

355

JSON Web Key Set utilities for key management operations.

356

357

```java { .api }

358

/**

359

* JSON Web Key Set utilities

360

*/

361

public class JWKSUtils {

362

/**

363

* Fetch JWK Set from URL

364

* @param jwksUrl JWK Set endpoint URL

365

* @return JSONWebKeySet instance

366

* @throws IOException if fetch operation fails

367

*/

368

public static JSONWebKeySet fetchJWKS(String jwksUrl) throws IOException;

369

370

/**

371

* Fetch JWK Set from URL with timeout

372

* @param jwksUrl JWK Set endpoint URL

373

* @param timeoutMs Timeout in milliseconds

374

* @return JSONWebKeySet instance

375

* @throws IOException if fetch operation fails

376

*/

377

public static JSONWebKeySet fetchJWKS(String jwksUrl, int timeoutMs) throws IOException;

378

379

/**

380

* Parse JWK Set from JSON string

381

* @param jwksJson JWK Set JSON string

382

* @return JSONWebKeySet instance

383

* @throws IOException if parsing fails

384

*/

385

public static JSONWebKeySet parseJWKS(String jwksJson) throws IOException;

386

387

/**

388

* Convert JWK Set to JSON string

389

* @param jwks JWK Set instance

390

* @return JSON string representation

391

* @throws IOException if serialization fails

392

*/

393

public static String toJsonString(JSONWebKeySet jwks) throws IOException;

394

395

/**

396

* Find key by key ID in JWK Set

397

* @param jwks JWK Set to search

398

* @param kid Key ID to find

399

* @return JWK instance or null if not found

400

*/

401

public static JWK findKeyById(JSONWebKeySet jwks, String kid);

402

403

/**

404

* Find keys by algorithm in JWK Set

405

* @param jwks JWK Set to search

406

* @param algorithm Algorithm identifier

407

* @return List of matching JWK instances

408

*/

409

public static List<JWK> findKeysByAlgorithm(JSONWebKeySet jwks, String algorithm);

410

411

/**

412

* Find keys by key use in JWK Set

413

* @param jwks JWK Set to search

414

* @param use Key use identifier (sig, enc)

415

* @return List of matching JWK instances

416

*/

417

public static List<JWK> findKeysByUse(JSONWebKeySet jwks, String use);

418

419

/**

420

* Validate JWK Set structure and keys

421

* @param jwks JWK Set to validate

422

* @return true if valid

423

*/

424

public static boolean validateJWKS(JSONWebKeySet jwks);

425

426

/**

427

* Create JWK Set from individual JWKs

428

* @param jwks Individual JWK instances

429

* @return JSONWebKeySet containing all keys

430

*/

431

public static JSONWebKeySet createJWKS(JWK... jwks);

432

433

/**

434

* Filter JWK Set by key type

435

* @param jwks Original JWK Set

436

* @param keyType Key type to filter by (RSA, EC, oct, OKP)

437

* @return Filtered JWK Set

438

*/

439

public static JSONWebKeySet filterByKeyType(JSONWebKeySet jwks, String keyType);

440

441

/**

442

* Merge multiple JWK Sets into one

443

* @param jwksSets JWK Sets to merge

444

* @return Merged JWK Set

445

*/

446

public static JSONWebKeySet mergeJWKS(JSONWebKeySet... jwksSets);

447

448

/**

449

* Cache JWK Set with TTL

450

* @param jwksUrl JWK Set URL

451

* @param jwks JWK Set to cache

452

* @param ttlSeconds Time to live in seconds

453

*/

454

public static void cacheJWKS(String jwksUrl, JSONWebKeySet jwks, int ttlSeconds);

455

456

/**

457

* Get cached JWK Set

458

* @param jwksUrl JWK Set URL

459

* @return Cached JWK Set or null if not cached or expired

460

*/

461

public static JSONWebKeySet getCachedJWKS(String jwksUrl);

462

}

463

```

464

465

### Hash and Encoding Utilities

466

467

Cryptographic hash and encoding utilities for various operations.

468

469

```java { .api }

470

/**

471

* Hash and encoding utilities

472

*/

473

public class HashUtils {

474

/**

475

* Compute SHA-256 hash of input data

476

* @param data Input data

477

* @return SHA-256 hash bytes

478

* @throws HashException if hash computation fails

479

*/

480

public static byte[] sha256(byte[] data) throws HashException;

481

482

/**

483

* Compute SHA-256 hash of string

484

* @param data Input string

485

* @return SHA-256 hash bytes

486

* @throws HashException if hash computation fails

487

*/

488

public static byte[] sha256(String data) throws HashException;

489

490

/**

491

* Compute SHA-384 hash of input data

492

* @param data Input data

493

* @return SHA-384 hash bytes

494

* @throws HashException if hash computation fails

495

*/

496

public static byte[] sha384(byte[] data) throws HashException;

497

498

/**

499

* Compute SHA-512 hash of input data

500

* @param data Input data

501

* @return SHA-512 hash bytes

502

* @throws HashException if hash computation fails

503

*/

504

public static byte[] sha512(byte[] data) throws HashException;

505

506

/**

507

* Encode bytes as Base64

508

* @param data Bytes to encode

509

* @return Base64 encoded string

510

*/

511

public static String encodeBase64(byte[] data);

512

513

/**

514

* Decode Base64 string to bytes

515

* @param base64 Base64 encoded string

516

* @return Decoded bytes

517

* @throws IllegalArgumentException if invalid Base64

518

*/

519

public static byte[] decodeBase64(String base64);

520

521

/**

522

* Encode bytes as Base64URL (URL-safe Base64)

523

* @param data Bytes to encode

524

* @return Base64URL encoded string

525

*/

526

public static String encodeBase64Url(byte[] data);

527

528

/**

529

* Decode Base64URL string to bytes

530

* @param base64Url Base64URL encoded string

531

* @return Decoded bytes

532

* @throws IllegalArgumentException if invalid Base64URL

533

*/

534

public static byte[] decodeBase64Url(String base64Url);

535

536

/**

537

* Generate secure random bytes

538

* @param length Number of bytes to generate

539

* @return Random bytes

540

*/

541

public static byte[] generateRandomBytes(int length);

542

543

/**

544

* Generate secure random string

545

* @param length String length

546

* @return Random string

547

*/

548

public static String generateRandomString(int length);

549

550

/**

551

* Compute HMAC-SHA256

552

* @param key HMAC key

553

* @param data Data to authenticate

554

* @return HMAC bytes

555

* @throws HashException if HMAC computation fails

556

*/

557

public static byte[] hmacSha256(byte[] key, byte[] data) throws HashException;

558

559

/**

560

* Verify HMAC-SHA256

561

* @param key HMAC key

562

* @param data Original data

563

* @param hmac HMAC to verify

564

* @return true if HMAC is valid

565

* @throws HashException if verification fails

566

*/

567

public static boolean verifyHmacSha256(byte[] key, byte[] data, byte[] hmac) throws HashException;

568

}

569

```

570

571

## Usage Examples

572

573

```java

574

import org.keycloak.util.*;

575

import org.keycloak.representations.*;

576

import org.keycloak.jose.jwk.*;

577

import javax.crypto.SecretKey;

578

import java.security.PublicKey;

579

import java.security.PrivateKey;

580

581

// Token utility usage

582

public class TokenUtilExample {

583

584

public void processTokenRequest(String scope, String tokenString) {

585

// Check for OIDC request

586

if (TokenUtil.isOIDCRequest(scope)) {

587

System.out.println("This is an OIDC request");

588

}

589

590

// Check for offline access

591

if (TokenUtil.isOfflineTokenRequested(scope)) {

592

System.out.println("Offline access requested");

593

}

594

595

// Check specific scope

596

if (TokenUtil.hasScope(scope, "profile")) {

597

System.out.println("Profile scope requested");

598

}

599

600

// Parse refresh token

601

try {

602

RefreshToken refreshToken = TokenUtil.getRefreshToken(tokenString);

603

if (TokenUtil.isOfflineToken(refreshToken)) {

604

System.out.println("This is an offline token");

605

}

606

} catch (TokenVerificationException e) {

607

System.err.println("Invalid refresh token: " + e.getMessage());

608

}

609

}

610

611

public void encryptSensitiveData(Object data, SecretKey key) {

612

try {

613

// Direct JWE encryption

614

String jwe = TokenUtil.jweDirectEncode(data, "A256GCM", "A256GCM", key);

615

System.out.println("Encrypted data: " + jwe);

616

617

// Decrypt data

618

Object decrypted = TokenUtil.jweDirectVerifyAndDecode(jwe, key);

619

System.out.println("Decrypted data: " + decrypted);

620

621

} catch (JWEException e) {

622

System.err.println("JWE operation failed: " + e.getMessage());

623

}

624

}

625

626

public void encryptWithPublicKey(Object data, PublicKey publicKey, PrivateKey privateKey) {

627

try {

628

// Key-encrypted JWE

629

String jwe = TokenUtil.jweKeyEncryptionEncode(data, "RSA-OAEP", "A256GCM", "A256GCM", publicKey);

630

System.out.println("Encrypted with public key: " + jwe);

631

632

// Decrypt with private key

633

Object decrypted = TokenUtil.jweKeyEncryptionVerifyAndDecode(jwe, privateKey);

634

System.out.println("Decrypted data: " + decrypted);

635

636

} catch (JWEException e) {

637

System.err.println("Key encryption failed: " + e.getMessage());

638

}

639

}

640

}

641

642

// JSON serialization usage

643

public class JsonSerializationExample {

644

645

public void serializeUserData() {

646

try {

647

// Create user object

648

UserRepresentation user = new UserRepresentation();

649

user.setUsername("john.doe");

650

user.setEmail("john@example.com");

651

user.setEnabled(true);

652

653

// Serialize to JSON

654

String json = JsonSerialization.writeValueAsString(user);

655

System.out.println("User JSON: " + json);

656

657

// Pretty print

658

String prettyJson = JsonSerialization.prettyPrint(json);

659

System.out.println("Pretty JSON:\n" + prettyJson);

660

661

// Deserialize back

662

UserRepresentation deserializedUser = JsonSerialization.readValue(json, UserRepresentation.class);

663

System.out.println("Deserialized username: " + deserializedUser.getUsername());

664

665

// Deep copy

666

UserRepresentation copy = JsonSerialization.deepCopy(user, UserRepresentation.class);

667

System.out.println("Copy email: " + copy.getEmail());

668

669

} catch (IOException e) {

670

System.err.println("JSON operation failed: " + e.getMessage());

671

}

672

}

673

674

public void handleGenericTypes() {

675

try {

676

// Working with generic types

677

Map<String, List<String>> attributes = new HashMap<>();

678

attributes.put("roles", Arrays.asList("admin", "user"));

679

attributes.put("groups", Arrays.asList("developers", "managers"));

680

681

String json = JsonSerialization.writeValueAsString(attributes);

682

683

// Deserialize with TypeReference

684

TypeReference<Map<String, List<String>>> typeRef = new TypeReference<Map<String, List<String>>>() {};

685

Map<String, List<String>> deserializedAttributes = JsonSerialization.readValue(json, typeRef);

686

687

System.out.println("Roles: " + deserializedAttributes.get("roles"));

688

689

} catch (IOException e) {

690

System.err.println("Generic type handling failed: " + e.getMessage());

691

}

692

}

693

}

694

695

// Basic authentication usage

696

public class BasicAuthExample {

697

698

public void handleBasicAuth(String username, String password) {

699

// Create Basic auth header

700

String authHeader = BasicAuthHelper.createHeader(username, password);

701

System.out.println("Authorization header: " + authHeader);

702

703

// Create complete header

704

String completeHeader = BasicAuthHelper.createAuthorizationHeader(username, password);

705

System.out.println("Complete header: " + completeHeader);

706

707

// Parse header

708

String[] credentials = BasicAuthHelper.parseHeader(authHeader);

709

if (credentials != null) {

710

System.out.println("Username: " + credentials[0]);

711

System.out.println("Password: " + credentials[1]);

712

}

713

}

714

715

public void processIncomingRequest(String authorizationHeader) {

716

if (BasicAuthHelper.isBasicAuth(authorizationHeader)) {

717

String[] credentials = BasicAuthHelper.extractUsernamePassword(authorizationHeader);

718

if (credentials != null) {

719

String username = credentials[0];

720

String password = credentials[1];

721

722

// Validate credentials

723

if (validateCredentials(username, password)) {

724

System.out.println("Authentication successful for: " + username);

725

} else {

726

System.out.println("Authentication failed");

727

}

728

}

729

}

730

}

731

732

private boolean validateCredentials(String username, String password) {

733

// Implementation would validate against user store

734

return true;

735

}

736

}

737

738

// JWK Set utilities usage

739

public class JWKSUtilsExample {

740

741

public void manageJWKS() {

742

try {

743

// Fetch JWK Set from URL

744

JSONWebKeySet jwks = JWKSUtils.fetchJWKS("https://auth.example.com/jwks", 5000);

745

System.out.println("Fetched " + jwks.getKeys().size() + " keys");

746

747

// Find key by ID

748

JWK signingKey = JWKSUtils.findKeyById(jwks, "rsa-key-1");

749

if (signingKey != null) {

750

System.out.println("Found signing key: " + signingKey.getKeyId());

751

}

752

753

// Find keys by algorithm

754

List<JWK> rsaKeys = JWKSUtils.findKeysByAlgorithm(jwks, "RS256");

755

System.out.println("Found " + rsaKeys.size() + " RSA keys");

756

757

// Filter by key type

758

JSONWebKeySet ecKeys = JWKSUtils.filterByKeyType(jwks, "EC");

759

System.out.println("EC keys: " + ecKeys.getKeys().size());

760

761

// Convert to JSON

762

String jwksJson = JWKSUtils.toJsonString(jwks);

763

System.out.println("JWK Set JSON length: " + jwksJson.length());

764

765

// Cache JWK Set

766

JWKSUtils.cacheJWKS("https://auth.example.com/jwks", jwks, 3600);

767

768

// Retrieve from cache

769

JSONWebKeySet cachedJWKS = JWKSUtils.getCachedJWKS("https://auth.example.com/jwks");

770

if (cachedJWKS != null) {

771

System.out.println("Retrieved from cache: " + cachedJWKS.getKeys().size() + " keys");

772

}

773

774

} catch (IOException e) {

775

System.err.println("JWK Set operation failed: " + e.getMessage());

776

}

777

}

778

}

779

780

// Hash utilities usage

781

public class HashUtilsExample {

782

783

public void performHashOperations() {

784

try {

785

String data = "Hello, Keycloak!";

786

787

// Compute hashes

788

byte[] sha256Hash = HashUtils.sha256(data);

789

byte[] sha384Hash = HashUtils.sha384(data.getBytes());

790

byte[] sha512Hash = HashUtils.sha512(data.getBytes());

791

792

// Encode as Base64

793

String sha256Base64 = HashUtils.encodeBase64(sha256Hash);

794

System.out.println("SHA-256 (Base64): " + sha256Base64);

795

796

// Encode as Base64URL

797

String sha256Base64Url = HashUtils.encodeBase64Url(sha256Hash);

798

System.out.println("SHA-256 (Base64URL): " + sha256Base64Url);

799

800

// Generate random data

801

byte[] randomBytes = HashUtils.generateRandomBytes(32);

802

String randomString = HashUtils.generateRandomString(16);

803

System.out.println("Random string: " + randomString);

804

805

// HMAC operations

806

byte[] key = HashUtils.generateRandomBytes(32);

807

byte[] hmac = HashUtils.hmacSha256(key, data.getBytes());

808

boolean valid = HashUtils.verifyHmacSha256(key, data.getBytes(), hmac);

809

System.out.println("HMAC valid: " + valid);

810

811

} catch (HashException e) {

812

System.err.println("Hash operation failed: " + e.getMessage());

813

}

814

}

815

}

816

```