or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

compression.mdindex.mdjwk-support.mdjwt-building.mdjwt-parsing.mdsecurity-algorithms.mdutilities.md

security-algorithms.mddocs/

0

# Security Algorithms

1

2

The Security Algorithms functionality in JJWT Implementation provides comprehensive JWA (JSON Web Algorithms) compliant implementations for digital signatures, content encryption, key management, and related cryptographic operations. The implementation includes algorithm registries, key generation utilities, and JCA provider integration.

3

4

## Algorithm Registries

5

6

### StandardSecureDigestAlgorithms

7

8

Registry for JWS (JSON Web Signature) algorithms providing both MAC and digital signature operations.

9

10

```java { .api }

11

import io.jsonwebtoken.Jwts;

12

import io.jsonwebtoken.security.SecureDigestAlgorithm;

13

import io.jsonwebtoken.security.MacAlgorithm;

14

import io.jsonwebtoken.security.SignatureAlgorithm;

15

import javax.crypto.SecretKey;

16

import java.security.KeyPair;

17

import java.security.PrivateKey;

18

import java.security.PublicKey;

19

20

// Access signature algorithm registry

21

SecureDigestAlgorithm<?, ?> algorithm = Jwts.SIG.get("HS256");

22

23

// Get all available signature algorithms

24

Collection<SecureDigestAlgorithm<?, ?>> allAlgorithms = Jwts.SIG.values();

25

26

// Find algorithm by key type

27

SecretKey hmacKey = Jwts.SIG.HS256.key().build();

28

SecureDigestAlgorithm<?, ?> foundAlgorithm = Jwts.SIG.get().forKey(hmacKey);

29

```

30

31

### HMAC Algorithms

32

33

```java { .api }

34

// HMAC-SHA256 (HS256)

35

MacAlgorithm hs256 = Jwts.SIG.HS256;

36

SecretKey hs256Key = hs256.key().build();

37

38

// HMAC-SHA384 (HS384)

39

MacAlgorithm hs384 = Jwts.SIG.HS384;

40

SecretKey hs384Key = hs384.key().build();

41

42

// HMAC-SHA512 (HS512)

43

MacAlgorithm hs512 = Jwts.SIG.HS512;

44

SecretKey hs512Key = hs512.key().build();

45

46

// Key length requirements

47

int hs256MinLength = hs256.getKeyBitLength(); // 256 bits minimum

48

int hs384MinLength = hs384.getKeyBitLength(); // 384 bits minimum

49

int hs512MinLength = hs512.getKeyBitLength(); // 512 bits minimum

50

51

// Generate keys with specific lengths

52

SecretKey customHs256 = hs256.key()

53

.length(hs256MinLength)

54

.build();

55

```

56

57

### RSA Signature Algorithms

58

59

```java { .api }

60

// RSA with PKCS#1 v1.5 padding

61

SignatureAlgorithm rs256 = Jwts.SIG.RS256; // RSA-SHA256

62

SignatureAlgorithm rs384 = Jwts.SIG.RS384; // RSA-SHA384

63

SignatureAlgorithm rs512 = Jwts.SIG.RS512; // RSA-SHA512

64

65

// Generate RSA key pairs

66

KeyPair rs256Pair = rs256.keyPair().build();

67

KeyPair rs384Pair = rs384.keyPair().build();

68

KeyPair rs512Pair = rs512.keyPair().build();

69

70

// RSA-PSS (Probabilistic Signature Scheme)

71

SignatureAlgorithm ps256 = Jwts.SIG.PS256; // RSA-PSS with SHA-256

72

SignatureAlgorithm ps384 = Jwts.SIG.PS384; // RSA-PSS with SHA-384

73

SignatureAlgorithm ps512 = Jwts.SIG.PS512; // RSA-PSS with SHA-512

74

75

KeyPair ps256Pair = ps256.keyPair().build();

76

77

// Custom key sizes

78

KeyPair rsa2048 = rs256.keyPair()

79

.keySize(2048)

80

.build();

81

82

KeyPair rsa3072 = rs256.keyPair()

83

.keySize(3072)

84

.build();

85

86

KeyPair rsa4096 = rs256.keyPair()

87

.keySize(4096)

88

.build();

89

```

90

91

### Elliptic Curve Signature Algorithms

92

93

```java { .api }

94

// ECDSA with different curves

95

SignatureAlgorithm es256 = Jwts.SIG.ES256; // P-256 curve (secp256r1)

96

SignatureAlgorithm es384 = Jwts.SIG.ES384; // P-384 curve (secp384r1)

97

SignatureAlgorithm es512 = Jwts.SIG.ES512; // P-521 curve (secp521r1)

98

99

// Generate EC key pairs

100

KeyPair p256Pair = es256.keyPair().build();

101

KeyPair p384Pair = es384.keyPair().build();

102

KeyPair p521Pair = es512.keyPair().build();

103

104

// EdDSA (Edwards-curve Digital Signature Algorithm)

105

SignatureAlgorithm eddsa = Jwts.SIG.EdDSA; // Ed25519 and Ed448 support

106

107

KeyPair ed25519Pair = eddsa.keyPair().build();

108

109

// Curve information

110

String es256CurveName = "P-256"; // Equivalent curve names

111

String es384CurveName = "P-384";

112

String es512CurveName = "P-521";

113

```

114

115

### StandardEncryptionAlgorithms

116

117

Registry for JWE (JSON Web Encryption) content encryption algorithms.

118

119

```java { .api }

120

import io.jsonwebtoken.security.AeadAlgorithm;

121

122

// AES-GCM algorithms

123

AeadAlgorithm a128gcm = Jwts.ENC.A128GCM; // AES-128-GCM

124

AeadAlgorithm a192gcm = Jwts.ENC.A192GCM; // AES-192-GCM

125

AeadAlgorithm a256gcm = Jwts.ENC.A256GCM; // AES-256-GCM

126

127

// Generate content encryption keys

128

SecretKey cek128 = a128gcm.key().build();

129

SecretKey cek192 = a192gcm.key().build();

130

SecretKey cek256 = a256gcm.key().build();

131

132

// AES-CBC with HMAC algorithms

133

AeadAlgorithm a128cbcHs256 = Jwts.ENC.A128CBC_HS256; // AES-128-CBC + HMAC-SHA256

134

AeadAlgorithm a192cbcHs384 = Jwts.ENC.A192CBC_HS384; // AES-192-CBC + HMAC-SHA384

135

AeadAlgorithm a256cbcHs512 = Jwts.ENC.A256CBC_HS512; // AES-256-CBC + HMAC-SHA512

136

137

// Key length requirements

138

int gcm128KeyLen = a128gcm.getKeyBitLength(); // 128 bits

139

int gcm256KeyLen = a256gcm.getKeyBitLength(); // 256 bits

140

int cbc256KeyLen = a256cbcHs512.getKeyBitLength(); // 512 bits (256 AES + 256 HMAC)

141

```

142

143

### StandardKeyAlgorithms

144

145

Registry for JWE key management algorithms.

146

147

```java { .api }

148

import io.jsonwebtoken.security.KeyAlgorithm;

149

150

// RSA key encryption

151

KeyAlgorithm rsa15 = Jwts.KEY.RSA1_5; // RSA-PKCS1-v1.5

152

KeyAlgorithm rsaOaep = Jwts.KEY.RSA_OAEP; // RSA-OAEP with SHA-1

153

KeyAlgorithm rsaOaep256 = Jwts.KEY.RSA_OAEP_256; // RSA-OAEP with SHA-256

154

155

// Generate RSA key pairs for encryption

156

KeyPair rsaEncPair = rsa15.keyPair().build();

157

KeyPair rsaOaepPair = rsaOaep.keyPair().build();

158

159

// AES Key Wrap

160

KeyAlgorithm a128kw = Jwts.KEY.A128KW; // AES-128 Key Wrap

161

KeyAlgorithm a192kw = Jwts.KEY.A192KW; // AES-192 Key Wrap

162

KeyAlgorithm a256kw = Jwts.KEY.A256KW; // AES-256 Key Wrap

163

164

// Generate key encryption keys

165

SecretKey kek128 = a128kw.key().build();

166

SecretKey kek192 = a192kw.key().build();

167

SecretKey kek256 = a256kw.key().build();

168

169

// Direct key agreement

170

KeyAlgorithm direct = Jwts.KEY.DIRECT; // Direct use of CEK

171

172

// ECDH-ES algorithms

173

KeyAlgorithm ecdhEs = Jwts.KEY.ECDH_ES; // Direct key agreement

174

KeyAlgorithm ecdhEs128 = Jwts.KEY.ECDH_ES_A128KW; // ECDH-ES + A128KW

175

KeyAlgorithm ecdhEs192 = Jwts.KEY.ECDH_ES_A192KW; // ECDH-ES + A192KW

176

KeyAlgorithm ecdhEs256 = Jwts.KEY.ECDH_ES_A256KW; // ECDH-ES + A256KW

177

178

KeyPair ecdhPair = ecdhEs.keyPair().build();

179

180

// AES-GCM Key Wrap

181

KeyAlgorithm a128gcmkw = Jwts.KEY.A128GCMKW; // AES-128-GCMKW

182

KeyAlgorithm a192gcmkw = Jwts.KEY.A192GCMKW; // AES-192-GCMKW

183

KeyAlgorithm a256gcmkw = Jwts.KEY.A256GCMKW; // AES-256-GCMKW

184

185

// PBES2 algorithms (Password-Based)

186

KeyAlgorithm pbes2Hs256A128kw = Jwts.KEY.PBES2_HS256_A128KW;

187

KeyAlgorithm pbes2Hs384A192kw = Jwts.KEY.PBES2_HS384_A192KW;

188

KeyAlgorithm pbes2Hs512A256kw = Jwts.KEY.PBES2_HS512_A256KW;

189

```

190

191

## Key Generation and Management

192

193

### Secret Key Generation

194

195

```java { .api }

196

import io.jsonwebtoken.impl.security.DefaultSecretKeyBuilder;

197

import io.jsonwebtoken.impl.security.RandomSecretKeyBuilder;

198

import java.security.SecureRandom;

199

import java.security.Provider;

200

201

// Generate HMAC keys

202

SecretKey hmacKey256 = Jwts.SIG.HS256.key().build();

203

SecretKey hmacKey384 = Jwts.SIG.HS384.key().build();

204

SecretKey hmacKey512 = Jwts.SIG.HS512.key().build();

205

206

// Custom key generation with specific parameters

207

SecretKey customKey = Jwts.SIG.HS256.key()

208

.length(256)

209

.algorithm("HmacSHA256")

210

.provider(myProvider)

211

.random(mySecureRandom)

212

.build();

213

214

// AES keys for encryption

215

SecretKey aes128 = Jwts.ENC.A128GCM.key().build();

216

SecretKey aes256 = Jwts.ENC.A256GCM.key().build();

217

218

// Key encryption keys

219

SecretKey kek = Jwts.KEY.A256KW.key().build();

220

```

221

222

### Asymmetric Key Generation

223

224

```java { .api }

225

import io.jsonwebtoken.impl.security.DefaultKeyPairBuilder;

226

227

// RSA key generation with different sizes

228

KeyPair rsa2048 = Jwts.SIG.RS256.keyPair()

229

.keySize(2048)

230

.build();

231

232

KeyPair rsa3072 = Jwts.SIG.RS256.keyPair()

233

.keySize(3072)

234

.build();

235

236

KeyPair rsa4096 = Jwts.SIG.RS256.keyPair()

237

.keySize(4096)

238

.build();

239

240

// EC key generation for different curves

241

KeyPair ecP256 = Jwts.SIG.ES256.keyPair().build(); // P-256

242

KeyPair ecP384 = Jwts.SIG.ES384.keyPair().build(); // P-384

243

KeyPair ecP521 = Jwts.SIG.ES512.keyPair().build(); // P-521

244

245

// EdDSA key generation

246

KeyPair ed25519 = Jwts.SIG.EdDSA.keyPair().build();

247

248

// Custom provider and random source

249

KeyPair customRsa = Jwts.SIG.RS256.keyPair()

250

.keySize(2048)

251

.provider(customProvider)

252

.random(customSecureRandom)

253

.build();

254

```

255

256

### Key Wrapping and Providers

257

258

```java { .api }

259

import io.jsonwebtoken.impl.security.ProvidedSecretKeyBuilder;

260

import io.jsonwebtoken.impl.security.ProvidedPrivateKeyBuilder;

261

262

// Wrap existing keys

263

SecretKey existingSecret = getExistingSecretKey();

264

SecretKey wrappedSecret = new ProvidedSecretKeyBuilder(existingSecret).build();

265

266

PrivateKey existingPrivate = getExistingPrivateKey();

267

PrivateKey wrappedPrivate = new ProvidedPrivateKeyBuilder(existingPrivate).build();

268

269

// Key validation

270

boolean isValidForAlgorithm = Jwts.SIG.HS256.validateKey(secretKey, false);

271

```

272

273

## JCA Provider Integration

274

275

### Custom Provider Support

276

277

```java { .api }

278

import io.jsonwebtoken.impl.security.JcaTemplate;

279

import java.security.Provider;

280

import org.bouncycastle.jce.provider.BouncyCastleProvider;

281

282

// Use Bouncy Castle provider

283

Provider bcProvider = new BouncyCastleProvider();

284

285

// Algorithm with custom provider

286

SecretKey bcKey = Jwts.SIG.HS256.key()

287

.provider(bcProvider)

288

.build();

289

290

KeyPair bcKeyPair = Jwts.SIG.RS256.keyPair()

291

.provider(bcProvider)

292

.build();

293

294

// JCA Template usage

295

JcaTemplate jcaTemplate = new JcaTemplate("AES", bcProvider);

296

```

297

298

### Provider Fallback Handling

299

300

```java { .api }

301

// JJWT automatically handles provider fallbacks

302

// If specified provider doesn't support algorithm, falls back to default

303

304

SecretKey resilientKey = Jwts.SIG.HS256.key()

305

.provider(possiblyUnsupportedProvider) // Fallback if unsupported

306

.build();

307

308

// Check provider capabilities

309

boolean supportsAlgorithm = checkProviderSupport(provider, "HmacSHA256");

310

```

311

312

## Algorithm Validation and Selection

313

314

### Key Strength Validation

315

316

```java { .api }

317

// Automatic key strength validation

318

try {

319

// This will throw exception if key is too weak

320

SecretKey weakKey = createWeakHmacKey(); // e.g., 128 bits for HS256

321

String jwt = Jwts.builder()

322

.subject("user")

323

.signWith(weakKey, Jwts.SIG.HS256) // Will validate key strength

324

.compact();

325

} catch (SecurityException e) {

326

// Key doesn't meet algorithm requirements

327

handleWeakKey(e);

328

}

329

330

// Manual key validation

331

boolean isValidKey = Jwts.SIG.HS256.validateKey(secretKey, false);

332

if (!isValidKey) {

333

throw new SecurityException("Key does not meet HS256 requirements");

334

}

335

```

336

337

### Algorithm Discovery

338

339

```java { .api }

340

// Find appropriate algorithm for key

341

SecretKey someKey = getUnknownKey();

342

SecureDigestAlgorithm<?, ?> algorithm = Jwts.SIG.get().forKey(someKey);

343

344

String algorithmId = algorithm.getId();

345

int keyBitLength = algorithm.getKeyBitLength();

346

347

// Algorithm compatibility check

348

boolean compatible = algorithm.validateKey(someKey, false);

349

```

350

351

## Advanced Security Features

352

353

### Critical Header Parameter Validation

354

355

```java { .api }

356

// Critical header parameters require explicit handling

357

Map<String, Object> criticalParams = Map.of(

358

"security-level", "high",

359

"custom-validation", "required"

360

);

361

362

String tokenWithCritical = Jwts.builder()

363

.subject("user")

364

.header()

365

.critical().add("security-level").add("custom-validation").and()

366

.add("security-level", "high")

367

.add("custom-validation", "required")

368

.and()

369

.signWith(secretKey)

370

.compact();

371

372

// Parser must handle critical parameters

373

JwtParser criticalParser = Jwts.parser()

374

.verifyWith(secretKey)

375

.critical()

376

.add("security-level")

377

.add("custom-validation")

378

.and()

379

.build();

380

```

381

382

### X.509 Certificate Support

383

384

```java { .api }

385

import io.jsonwebtoken.impl.security.X509BuilderSupport;

386

import java.security.cert.X509Certificate;

387

388

// X.509 certificate chain building

389

X509Certificate[] certChain = getCertificateChain();

390

391

String certJwt = Jwts.builder()

392

.subject("certified-user")

393

.header()

394

.x509CertChain(Arrays.asList(certChain))

395

.and()

396

.signWith(privateKeyFromCert)

397

.compact();

398

```

399

400

### Algorithm-Specific Features

401

402

```java { .api }

403

// ECDH-ES key agreement with additional parameters

404

KeyPair ecdhPair = Jwts.KEY.ECDH_ES.keyPair().build();

405

406

// PBES2 with custom iteration count and salt

407

Map<String, Object> pbes2Params = Map.of(

408

"p2s", "custom-salt".getBytes(),

409

"p2c", 4096 // iteration count

410

);

411

412

// AES-GCM with authentication data

413

byte[] additionalAuthenticatedData = "additional-data".getBytes();

414

```

415

416

## Performance Considerations

417

418

### Algorithm Registry Caching

419

420

```java { .api }

421

// Registries are cached for performance

422

SecureDigestAlgorithm<?, ?> cachedAlg1 = Jwts.SIG.get("HS256");

423

SecureDigestAlgorithm<?, ?> cachedAlg2 = Jwts.SIG.get("HS256");

424

// cachedAlg1 == cachedAlg2 (same instance)

425

426

// Efficient algorithm lookup

427

boolean hasAlgorithm = Jwts.SIG.get().containsKey("HS256");

428

Set<String> availableAlgorithms = Jwts.SIG.get().keySet();

429

```

430

431

### Key Generation Optimization

432

433

```java { .api }

434

// Reuse SecureRandom for multiple operations

435

SecureRandom sharedRandom = SecureRandom.getInstanceStrong();

436

437

SecretKey key1 = Jwts.SIG.HS256.key().random(sharedRandom).build();

438

SecretKey key2 = Jwts.SIG.HS256.key().random(sharedRandom).build();

439

KeyPair pair1 = Jwts.SIG.RS256.keyPair().random(sharedRandom).build();

440

441

// Provider reuse

442

Provider sharedProvider = new BouncyCastleProvider();

443

SecretKey bcKey1 = Jwts.SIG.HS256.key().provider(sharedProvider).build();

444

SecretKey bcKey2 = Jwts.SIG.HS384.key().provider(sharedProvider).build();

445

```

446

447

## Custom Algorithm Implementation

448

449

### Extending Algorithm Registries

450

451

```java { .api }

452

import io.jsonwebtoken.impl.lang.DefaultRegistry;

453

454

// Custom algorithm registration (for extensions)

455

// Note: This requires implementing the appropriate algorithm interfaces

456

457

// Add custom signature algorithm to registry

458

DefaultRegistry<SecureDigestAlgorithm<?, ?>> customSigRegistry =

459

new DefaultRegistry<>("Custom Signature Algorithms");

460

461

customSigRegistry.add(customSignatureAlgorithm);

462

463

// Add to parser

464

JwtParser customParser = Jwts.parser()

465

.verifyWith(secretKey)

466

.sig()

467

.add(customSignatureAlgorithm)

468

.and()

469

.build();

470

```

471

472

The Security Algorithms implementation provides production-ready, JWA-compliant cryptographic operations with comprehensive key management, validation, and performance optimization features.