Back to cheatsheets
Cryptography
Secret / API Key Generation
Generate secure API keys, tokens, and secrets of arbitrary length using CSPRNG.
What you'll learn
- Generate API key
- Prefixed key format
How to use these snippets
- Click the Copy button next to any snippet to copy it to your clipboard.
- Paste the code into your project, IDE, or terminal.
- Replace placeholder values (like
example.comoryour-secret) with your actual data. - Review the code comments for important security notes and caveats.
- Try the interactive related tool to see the concept in action.
Code Snippets
Copy-paste code snippets
2 ready-to-use snippets for secret / api key generation. Click copy and paste into your project.
Generate API key
function generateApiKey(bytes = 32) {
const arr = crypto.getRandomValues(new Uint8Array(bytes));
return Array.from(arr, b =>
b.toString(16).padStart(2, '0')
).join('');
}
// 32 bytes → 64-char hex string, 256 bits of entropy
Prefixed key format
function generatePrefixedKey(env = 'live') {
const bytes = crypto.getRandomValues(new Uint8Array(32));
const random = Array.from(bytes, b =>
b.toString(16).padStart(2, '0')
).join('');
return `sk_${env}_${random}`;
}
// Example: sk_live_a1b2c3d4e5f6...
// URL-safe Base64 format
function generateBase64Key(bytes = 32) {
const arr = crypto.getRandomValues(new Uint8Array(bytes));
return btoa(String.fromCharCode(...arr))
.replace(/\+/g, '-').replace(/\//g, '_')
.replace(/=+$/, '');
}
Tool
Related ShieldX tool
Try this concept hands-on with the interactive tool.
100% Free · No signup · No cost
Generate something unguessable right now
148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.
Part of the Toolly ecosystem · secure.toolly.site