Overview
Theant:crypto module provides cryptographic operations powered by libsodium. It includes secure random number generation, UUID creation, and cryptographically strong randomness.
Importing
Random Number Generation
Random Integer
Generate a random 32-bit unsigned integer:Random Bytes
Generate an array of random bytes:Random Buffer
Fill a TypedArray with random values:UUID Generation
Random UUID (v4)
Generate a random UUID v4:UUID v7 (Time-Ordered)
Generate a time-ordered UUID v7:UUID v7 Benefits
- Time-ordered (lexicographically sortable)
- Better database index performance
- Includes creation timestamp
- Still globally unique
Practical Examples
Session Tokens
Random Passwords
Cryptographic Nonces
API Keys
Random Selection
Shuffling Arrays
Random Delays
Database IDs
Web Crypto Compatibility
The module follows Web Crypto API conventions:Security Considerations
- Use randomBytes for secrets - Never use Math.random() for security
- Sufficient entropy - Use at least 16 bytes for tokens
- Token encoding - Hex or base64 for text representation
- UUID v7 for databases - Better performance than v4
- Nonce uniqueness - Never reuse nonces in encryption
Performance Tips
Limitations
- Maximum byte array size: 65536 bytes
- TypedArray byte length must not exceed 65536
- Powered by libsodium - very secure
Best Practices
- Use
randomUUIDv7()for database primary keys - Use
randomUUID()for request IDs and correlation - Use
randomBytes()for tokens and secrets - Use
getRandomValues()for filling buffers - Never use for cryptographic key derivation (use proper KDF)
- Store random values securely
- Don’t log or expose random tokens
- Use sufficient length (32+ bytes for high security)