or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-utilities.mdcryptography.mdfunctional-programming.mdgenerators.mdhttp-clients.mdindex.mdjwt-utilities.mdserialization.mdspecialized-utilities.mdspring-integration.mdtext-processing.md

generators.mddocs/

0

# Generators

1

2

Random string and numeric generators for creating secure tokens, identifiers, session IDs, and cryptographic material with multiple output formats and configurable algorithms.

3

4

## RandomStringGenerator Interface

5

6

Core interface for random string generation with configurable length and algorithms.

7

8

```java { .api }

9

public interface RandomStringGenerator {

10

11

// Default configuration

12

int DEFAULT_LENGTH = 36;

13

14

// Configuration methods

15

long getDefaultLength();

16

String getAlgorithm();

17

18

// String generation methods

19

String getNewString(int size);

20

String getNewString();

21

22

// Binary generation method

23

byte[] getNewStringAsBytes(int size);

24

}

25

```

26

27

### Usage Examples

28

29

**Basic string generation:**

30

```java

31

@Service

32

public class TokenService {

33

34

private final RandomStringGenerator generator;

35

36

public TokenService(RandomStringGenerator generator) {

37

this.generator = generator;

38

}

39

40

public String generateSessionToken() {

41

// Use default length (36 characters)

42

return generator.getNewString();

43

}

44

45

public String generateApiKey() {

46

// Custom length for API keys

47

return generator.getNewString(64);

48

}

49

50

public String generateShortCode() {

51

// Short codes for verification

52

return generator.getNewString(8);

53

}

54

55

public byte[] generateBinaryToken() {

56

// Generate as bytes for binary protocols

57

return generator.getNewStringAsBytes(32);

58

}

59

}

60

```

61

62

## AbstractRandomStringGenerator

63

64

Abstract base implementation providing common functionality for string generators.

65

66

```java { .api }

67

public abstract class AbstractRandomStringGenerator implements RandomStringGenerator {

68

69

// Protected fields

70

protected final SecureRandom randomizer;

71

protected final String algorithm;

72

protected final long defaultLength;

73

74

// Constructor

75

protected AbstractRandomStringGenerator(long defaultLength);

76

protected AbstractRandomStringGenerator(long defaultLength, String algorithm);

77

78

// Interface implementation

79

@Override

80

public long getDefaultLength();

81

82

@Override

83

public String getAlgorithm();

84

85

@Override

86

public String getNewString();

87

88

@Override

89

public byte[] getNewStringAsBytes(int size);

90

91

// Abstract methods for subclasses

92

protected abstract String convertBytesToString(byte[] bytes);

93

}

94

```

95

96

## DefaultRandomStringGenerator

97

98

Default implementation using alphanumeric characters with secure random generation.

99

100

```java { .api }

101

public class DefaultRandomStringGenerator extends AbstractRandomStringGenerator {

102

103

// Default character set (alphanumeric)

104

public static final String DEFAULT_CHARSET =

105

"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

106

107

// Constructors

108

public DefaultRandomStringGenerator();

109

public DefaultRandomStringGenerator(long defaultLength);

110

public DefaultRandomStringGenerator(long defaultLength, String charset);

111

112

// String generation implementation

113

@Override

114

public String getNewString(int size);

115

116

// Byte conversion implementation

117

@Override

118

protected String convertBytesToString(byte[] bytes);

119

}

120

```

121

122

### Usage Examples

123

124

**Default generator configuration:**

125

```java

126

@Configuration

127

public class GeneratorConfiguration {

128

129

@Bean

130

@Primary

131

public RandomStringGenerator defaultStringGenerator() {

132

return new DefaultRandomStringGenerator();

133

}

134

135

@Bean("shortCodeGenerator")

136

public RandomStringGenerator shortCodeGenerator() {

137

// Custom length for short codes

138

return new DefaultRandomStringGenerator(8);

139

}

140

141

@Bean("customCharsetGenerator")

142

public RandomStringGenerator customCharsetGenerator() {

143

// Custom character set (uppercase only)

144

String charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

145

return new DefaultRandomStringGenerator(12, charset);

146

}

147

}

148

```

149

150

**Usage in services:**

151

```java

152

@Service

153

public class UserRegistrationService {

154

155

private final RandomStringGenerator defaultGenerator;

156

private final RandomStringGenerator shortCodeGenerator;

157

158

public UserRegistrationService(

159

@Qualifier("defaultStringGenerator") RandomStringGenerator defaultGenerator,

160

@Qualifier("shortCodeGenerator") RandomStringGenerator shortCodeGenerator) {

161

this.defaultGenerator = defaultGenerator;

162

this.shortCodeGenerator = shortCodeGenerator;

163

}

164

165

public User createUser(String email, String password) {

166

User user = new User();

167

user.setEmail(email);

168

user.setPasswordHash(hashPassword(password));

169

170

// Generate unique user ID

171

user.setUserId(defaultGenerator.getNewString(32));

172

173

// Generate verification code

174

user.setVerificationCode(shortCodeGenerator.getNewString());

175

176

return userRepository.save(user);

177

}

178

}

179

```

180

181

## Base64RandomStringGenerator

182

183

Generator producing Base64-encoded random strings for URL-safe tokens and identifiers.

184

185

```java { .api }

186

public class Base64RandomStringGenerator extends AbstractRandomStringGenerator {

187

188

// Constructors

189

public Base64RandomStringGenerator();

190

public Base64RandomStringGenerator(long defaultLength);

191

192

// String generation with Base64 encoding

193

@Override

194

public String getNewString(int size);

195

196

// Byte conversion to Base64

197

@Override

198

protected String convertBytesToString(byte[] bytes);

199

}

200

```

201

202

## HexRandomStringGenerator

203

204

Generator producing hexadecimal random strings for cryptographic applications and debugging.

205

206

```java { .api }

207

public class HexRandomStringGenerator extends AbstractRandomStringGenerator {

208

209

// Constructors

210

public HexRandomStringGenerator();

211

public HexRandomStringGenerator(long defaultLength);

212

213

// String generation with hex encoding

214

@Override

215

public String getNewString(int size);

216

217

// Byte conversion to hexadecimal

218

@Override

219

protected String convertBytesToString(byte[] bytes);

220

}

221

```

222

223

### Usage Examples

224

225

**Specialized generators for different use cases:**

226

```java

227

@Component

228

public class CryptographicTokenService {

229

230

private final Base64RandomStringGenerator base64Generator;

231

private final HexRandomStringGenerator hexGenerator;

232

233

public CryptographicTokenService() {

234

this.base64Generator = new Base64RandomStringGenerator(32);

235

this.hexGenerator = new HexRandomStringGenerator(16);

236

}

237

238

public String generateJwtSecret() {

239

// Base64 for JWT secrets (URL-safe)

240

return base64Generator.getNewString(64);

241

}

242

243

public String generateCsrfToken() {

244

// Base64 for CSRF tokens

245

return base64Generator.getNewString(32);

246

}

247

248

public String generateSalt() {

249

// Hex for password salts

250

return hexGenerator.getNewString(32);

251

}

252

253

public String generateKeyId() {

254

// Hex for key identifiers

255

return hexGenerator.getNewString(8);

256

}

257

258

public String generateNonce() {

259

// Base64 for cryptographic nonces

260

return base64Generator.getNewString(16);

261

}

262

}

263

```

264

265

## Numeric Generators

266

267

### NumericGenerator Interface

268

269

Interface for generating numeric identifiers and sequences.

270

271

```java { .api }

272

public interface NumericGenerator {

273

274

// Numeric generation methods

275

long getNextLong();

276

int getNextInt();

277

278

// Configuration

279

long getMinValue();

280

long getMaxValue();

281

}

282

```

283

284

### LongNumericGenerator Interface

285

286

Specialized interface for long numeric generation with extended range support.

287

288

```java { .api }

289

public interface LongNumericGenerator extends NumericGenerator {

290

291

// Extended long generation

292

long getNextLongValue();

293

long getNextLongValue(long min, long max);

294

295

// Range configuration

296

void setRange(long min, long max);

297

}

298

```

299

300

### DefaultLongNumericGenerator

301

302

Default implementation for long numeric generation with configurable ranges.

303

304

```java { .api }

305

public class DefaultLongNumericGenerator implements LongNumericGenerator {

306

307

// Default range constants

308

public static final long DEFAULT_MIN_VALUE = 1L;

309

public static final long DEFAULT_MAX_VALUE = Long.MAX_VALUE;

310

311

// Constructors

312

public DefaultLongNumericGenerator();

313

public DefaultLongNumericGenerator(long minValue, long maxValue);

314

315

// NumericGenerator implementation

316

@Override

317

public long getNextLong();

318

319

@Override

320

public int getNextInt();

321

322

@Override

323

public long getMinValue();

324

325

@Override

326

public long getMaxValue();

327

328

// LongNumericGenerator implementation

329

@Override

330

public long getNextLongValue();

331

332

@Override

333

public long getNextLongValue(long min, long max);

334

335

@Override

336

public void setRange(long min, long max);

337

}

338

```

339

340

### DefaultRandomNumberGenerator

341

342

General-purpose random number generator for various numeric types.

343

344

```java { .api }

345

public class DefaultRandomNumberGenerator implements NumericGenerator {

346

347

// Constructors

348

public DefaultRandomNumberGenerator();

349

public DefaultRandomNumberGenerator(SecureRandom random);

350

351

// NumericGenerator implementation

352

@Override

353

public long getNextLong();

354

355

@Override

356

public int getNextInt();

357

358

@Override

359

public long getMinValue();

360

361

@Override

362

public long getMaxValue();

363

364

// Additional random methods

365

public double getNextDouble();

366

public float getNextFloat();

367

public boolean getNextBoolean();

368

public byte[] getNextBytes(int count);

369

}

370

```

371

372

### Usage Examples

373

374

**Numeric ID generation:**

375

```java

376

@Service

377

public class IdentifierService {

378

379

private final LongNumericGenerator longGenerator;

380

private final NumericGenerator randomGenerator;

381

382

public IdentifierService() {

383

// Sequential IDs in a specific range

384

this.longGenerator = new DefaultLongNumericGenerator(100000L, 999999L);

385

386

// Random numbers

387

this.randomGenerator = new DefaultRandomNumberGenerator();

388

}

389

390

public Long generateUserId() {

391

// Generate user IDs in range

392

return longGenerator.getNextLongValue();

393

}

394

395

public String generateOrderNumber() {

396

// Combine timestamp with random number

397

long timestamp = System.currentTimeMillis();

398

int random = randomGenerator.getNextInt();

399

return String.format("ORD-%d-%06d", timestamp, Math.abs(random % 1000000));

400

}

401

402

public Long generateSessionId() {

403

// Random session ID

404

return randomGenerator.getNextLong();

405

}

406

}

407

```

408

409

## Complete Integration Example

410

411

### Multi-Format Token Service

412

413

```java

414

@Service

415

@Slf4j

416

public class TokenGenerationService {

417

418

private final RandomStringGenerator alphanumericGenerator;

419

private final RandomStringGenerator base64Generator;

420

private final RandomStringGenerator hexGenerator;

421

private final LongNumericGenerator sequentialGenerator;

422

private final NumericGenerator randomNumericGenerator;

423

424

public TokenGenerationService() {

425

// Initialize different generators

426

this.alphanumericGenerator = new DefaultRandomStringGenerator(32);

427

this.base64Generator = new Base64RandomStringGenerator(24);

428

this.hexGenerator = new HexRandomStringGenerator(16);

429

this.sequentialGenerator = new DefaultLongNumericGenerator(1000000L, 9999999L);

430

this.randomNumericGenerator = new DefaultRandomNumberGenerator();

431

}

432

433

public AuthenticationToken generateAuthToken(String userId) {

434

AuthenticationToken token = new AuthenticationToken();

435

436

// Primary token (Base64 for URL safety)

437

token.setAccessToken(base64Generator.getNewString(32));

438

439

// Refresh token (longer alphanumeric)

440

token.setRefreshToken(alphanumericGenerator.getNewString(64));

441

442

// Token ID (sequential for tracking)

443

token.setTokenId(sequentialGenerator.getNextLongValue());

444

445

// CSRF token (hex for web forms)

446

token.setCsrfToken(hexGenerator.getNewString(32));

447

448

// Expiration (current time + random offset)

449

long baseExpiry = System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1);

450

long randomOffset = randomNumericGenerator.getNextInt() % TimeUnit.MINUTES.toMillis(5);

451

token.setExpiresAt(baseExpiry + randomOffset);

452

453

log.info("Generated authentication token {} for user {}", token.getTokenId(), userId);

454

return token;

455

}

456

457

public SessionData generateSession(String username) {

458

SessionData session = new SessionData();

459

460

// Session ID (Base64 encoded)

461

session.setSessionId(base64Generator.getNewString(48));

462

463

// CSRF protection token

464

session.setCsrfToken(hexGenerator.getNewString(24));

465

466

// Random session timeout (base + jitter)

467

int baseTimeout = 1800; // 30 minutes

468

int jitter = randomNumericGenerator.getNextInt() % 300; // ±5 minutes

469

session.setTimeoutSeconds(baseTimeout + jitter);

470

471

log.info("Generated session {} for user {}", session.getSessionId(), username);

472

return session;

473

}

474

475

public VerificationCode generateVerificationCode(VerificationCodeType type) {

476

VerificationCode code = new VerificationCode();

477

478

switch (type) {

479

case EMAIL_VERIFICATION:

480

// 6-digit numeric code

481

code.setCode(String.format("%06d",

482

Math.abs(randomNumericGenerator.getNextInt() % 1000000)));

483

code.setExpiryMinutes(15);

484

break;

485

486

case SMS_VERIFICATION:

487

// 4-digit numeric code

488

code.setCode(String.format("%04d",

489

Math.abs(randomNumericGenerator.getNextInt() % 10000)));

490

code.setExpiryMinutes(5);

491

break;

492

493

case PASSWORD_RESET:

494

// Long alphanumeric token

495

code.setCode(alphanumericGenerator.getNewString(48));

496

code.setExpiryMinutes(60);

497

break;

498

499

case API_KEY:

500

// Base64 API key with prefix

501

String apiKey = base64Generator.getNewString(32);

502

code.setCode("cas_" + apiKey.replace("+", "-").replace("/", "_"));

503

code.setExpiryMinutes(0); // No expiry for API keys

504

break;

505

}

506

507

return code;

508

}

509

510

public String generateTraceId() {

511

// Hex trace ID for distributed tracing

512

return hexGenerator.getNewString(16);

513

}

514

515

public String generateCorrelationId() {

516

// UUID-like correlation ID

517

String hex32 = hexGenerator.getNewString(32);

518

return String.format("%s-%s-%s-%s-%s",

519

hex32.substring(0, 8),

520

hex32.substring(8, 12),

521

hex32.substring(12, 16),

522

hex32.substring(16, 20),

523

hex32.substring(20, 32));

524

}

525

}

526

527

enum VerificationCodeType {

528

EMAIL_VERIFICATION,

529

SMS_VERIFICATION,

530

PASSWORD_RESET,

531

API_KEY

532

}

533

```

534

535

**Configuration for production use:**

536

```java

537

@Configuration

538

@EnableConfigurationProperties(GeneratorProperties.class)

539

public class ProductionGeneratorConfiguration {

540

541

@Bean

542

@ConditionalOnMissingBean

543

public RandomStringGenerator secureStringGenerator(GeneratorProperties properties) {

544

return new DefaultRandomStringGenerator(

545

properties.getDefaultStringLength(),

546

properties.getCharacterSet()

547

);

548

}

549

550

@Bean

551

@ConditionalOnMissingBean

552

public LongNumericGenerator sequentialIdGenerator(GeneratorProperties properties) {

553

return new DefaultLongNumericGenerator(

554

properties.getSequentialMinValue(),

555

properties.getSequentialMaxValue()

556

);

557

}

558

559

@ConfigurationProperties(prefix = "cas.generator")

560

@Data

561

public static class GeneratorProperties {

562

private int defaultStringLength = 32;

563

private String characterSet = DefaultRandomStringGenerator.DEFAULT_CHARSET;

564

private long sequentialMinValue = 1000000L;

565

private long sequentialMaxValue = Long.MAX_VALUE;

566

}

567

}

568

```

569

570

This generator library provides secure, configurable, and efficient random generation capabilities for all types of identifiers and tokens needed in CAS authentication systems.