Crypto Reference
The crypto
object is available within Loadster Code Blocks and provides cryptographic functions for hashing, HMAC generation, and data integrity verification. These functions enable you to create secure signatures, verify data integrity, and implement authentication schemes programmatically.
Understanding Cryptographic Functions in Loadster
In Loadster, cryptographic functions are available for testing scenarios that require authentication signatures, data integrity checks, or custom security implementations. Most load testing scenarios don’t require manual cryptographic work, but Loadster provides these functions when you need them. You’ll most commonly need these functions when using Protocol Scripts to test APIs with HMAC authentication, webhook verification, or custom security schemes, though the crypto object is available in any type of Loadster script. In Browser Scripts, the browser typically handles standard authentication and security automatically, but you may still need crypto functions for custom API integrations or manual security implementations.
Common scenarios where you need cryptographic functions in load testing include:
- API Authentication - Many secure APIs require HMAC signatures to verify request authenticity
- Webhook Verification - Validating that incoming webhooks are from trusted sources
- Data Integrity - Ensuring data hasn’t been corrupted during transmission or storage
- Custom Security Schemes - Implementing proprietary authentication or encryption protocols
- Token Generation - Creating JWT-like tokens or session identifiers
- Cache Keys - Generating consistent, collision-resistant identifiers for caching systems
- Password Testing - Verifying password hashing and verification systems
Cryptographic functions fall into two main categories:
- Hash functions (MD5, SHA1, SHA256, SHA512) - Generate fixed-size digests from input data without requiring a secret key
- HMAC functions (Hash-based Message Authentication Code) - Generate authenticated hashes using both input data and a secret key for verification
All cryptographic methods are synchronous and return string results in either Base64 or hexadecimal encoding formats, making them suitable for use in HTTP headers, JSON payloads, and authentication tokens.
HMAC Functions
HMAC (Hash-based Message Authentication Code) functions generate authenticated hashes using both input data and a secret key. These are essential for API authentication, webhook verification, and ensuring data integrity in secure communications.
crypto.hmacsha512base64(input, secret)
Generate an HMAC-SHA512 hash encoded as Base64 from an input value.
crypto.hmacsha512base64("input", "secret");
// Returns: "Ksle03F+BCxwZKX6fDGCMM022F4G+P+Dc9BMoX42Fingn0a38VH/OCo/SMWxkSFEbkXCWI8P8d6fdLBADa74Hw=="
// Example with API request data
const requestData = JSON.stringify({userId: "123", action: "purchase"});
const signature = crypto.hmacsha512base64(requestData, bot.getVariable('apiSecret'));
Parameters:
input
- The data to be hashedsecret
- The secret key for HMAC generation
This method generates the strongest HMAC signature using SHA-512 hashing, encoded as Base64 for use in HTTP headers and JSON payloads.
Note: Base64 encoding is ideal for HTTP headers and JSON data as it contains only URL-safe characters.
crypto.hmacsha512hex(input, secret)
Generate an HMAC-SHA512 hash encoded as hexadecimal from an input value.
crypto.hmacsha512hex("input", "secret");
// Returns: "2ac95ed3717e042c7064a5fa7c318230cd36d85e06f8ff8373d04ca17e361629e09f46b7f151ff382a3f48c5b19121446e45c2588f0ff1de9f74b0400daef81f"
// Example with timestamp and method
const message = `POST/api/orders${Date.now()}`;
const signature = crypto.hmacsha512hex(message, bot.getVariable('webhookSecret'));
Parameters:
input
- The data to be hashedsecret
- The secret key for HMAC generation
This method generates HMAC-SHA512 signatures encoded as hexadecimal, useful for debugging and systems that expect hex-encoded signatures.
Note: Hexadecimal encoding produces longer strings but is more readable for debugging and logging purposes.
crypto.hmacsha384base64(input, secret)
Generate an HMAC-SHA384 hash encoded as Base64 from an input value.
crypto.hmacsha384base64("input", "secret");
// Returns: "is0XLFfl9kpaMnpDdiMkwOJ4eYP7ez481SOKgiu6p/mC4SXCJzeVtbuU0z6auD7F"
// Example with request payload
const payload = JSON.stringify({orderId: "456", status: "shipped"});
const signature = crypto.hmacsha384base64(payload, bot.getVariable('shippingSecret'));
Parameters:
input
- The data to be hashedsecret
- The secret key for HMAC generation
This method provides strong cryptographic security with SHA-384 hashing, offering a balance between security and performance.
crypto.hmacsha384hex(input, secret)
Generate an HMAC-SHA384 hash encoded as hexadecimal from an input value.
crypto.hmacsha384hex("input", "secret");
// Returns: "8acd172c57e5f64a5a327a43762324c0e2787983fb7b3e3cd5238a822bbaa7f982e125c2273795b5bb94d33e9ab83ec5"
// Example with user authentication
const authData = `${bot.getVariable('username')}:${Date.now()}`;
const authHash = crypto.hmacsha384hex(authData, bot.getVariable('userSecret'));
Parameters:
input
- The data to be hashedsecret
- The secret key for HMAC generation
This method generates HMAC-SHA384 signatures in hexadecimal format, suitable for systems requiring this specific encoding.
crypto.hmacsha256base64(input, secret)
Generate an HMAC-SHA256 hash encoded as Base64 from an input value.
crypto.hmacsha256base64("input", "secret");
// Returns: "jYmF0Et6vTLLqjd5o9qgGeDSaaIq7BWvjnKW9wLMaMY="
// Example with complete API signature
const method = "POST";
const path = "/api/payments";
const timestamp = Date.now().toString();
const body = JSON.stringify({amount: 100, currency: "USD"});
const message = `${method}${path}${timestamp}${body}`;
const signature = crypto.hmacsha256base64(message, bot.getVariable('paymentSecret'));
Parameters:
input
- The data to be hashedsecret
- The secret key for HMAC generation
HMAC-SHA256 is the most commonly used HMAC algorithm, providing excellent security with good performance. It’s widely supported across different systems and APIs.
Note: SHA-256 is the current industry standard for most authentication schemes and offers the best balance of security and compatibility.
crypto.hmacsha256hex(input, secret)
Generate an HMAC-SHA256 hash encoded as hexadecimal from an input value.
crypto.hmacsha256hex("input", "secret");
// Returns: "8d8985d04b7abd32cbaa3779a3daa019e0d269a22aec15af8e7296f702cc68c6"
// Example with webhook verification
const webhookPayload = response.string();
const expectedSignature = crypto.hmacsha256hex(webhookPayload, bot.getVariable('webhookSecret'));
const receivedSignature = response.headers['X-Hub-Signature-256'];
Parameters:
input
- The data to be hashedsecret
- The secret key for HMAC generation
This method generates HMAC-SHA256 signatures in hexadecimal format, commonly used by webhook systems and APIs that prefer hex encoding.
crypto.hmacsha224base64(input, secret)
Generate an HMAC-SHA224 hash encoded as Base64 from an input value.
crypto.hmacsha224base64("input", "secret");
// Returns: "LDdw8G3Ykt8vLV9+8gXABot+TCB01il0Hy5S8A=="
// Example with session token
const sessionData = `${bot.getVariable('sessionId')}:${Date.now()}`;
const sessionToken = crypto.hmacsha224base64(sessionData, bot.getVariable('sessionSecret'));
bot.setVariable('sessionToken', sessionToken);
Parameters:
input
- The data to be hashedsecret
- The secret key for HMAC generation
HMAC-SHA224 provides good security with shorter hash outputs than SHA-256, useful when bandwidth or storage space is a consideration.
crypto.hmacsha224hex(input, secret)
Generate an HMAC-SHA224 hash encoded as hexadecimal from an input value.
crypto.hmacsha224hex("input", "secret");
// Returns: "2c3770f06dd892df2f2d5f7ef205c0068b7e4c2074d629741f2e52f0"
// Example with cache invalidation
const cacheData = `${bot.getVariable('userId')}:${bot.getVariable('dataVersion')}`;
const cacheKey = crypto.hmacsha224hex(cacheData, bot.getVariable('cacheSecret'));
Parameters:
input
- The data to be hashedsecret
- The secret key for HMAC generation
This method generates HMAC-SHA224 signatures in hexadecimal format with shorter output length than SHA-256.
crypto.hmacsha1base64(input, secret)
Generate an HMAC-SHA1 hash encoded as Base64 from an input value.
crypto.hmacsha1base64("input", "secret");
// Returns: "MEQPNt3CgJu9TIsfN6boDXWIwwM="
// Example with legacy API compatibility
const legacyRequest = `${bot.getVariable('accountId')}:${bot.getVariable('action')}`;
const legacySignature = crypto.hmacsha1base64(legacyRequest, bot.getVariable('legacySecret'));
Parameters:
input
- The data to be hashedsecret
- The secret key for HMAC generation
HMAC-SHA1 is provided for compatibility with legacy systems. For new implementations, use SHA-256 or higher for better security.
Note: SHA-1 is considered cryptographically weak and should only be used when required for legacy system compatibility.
crypto.hmacsha1hex(input, secret)
Generate an HMAC-SHA1 hash encoded as hexadecimal from an input value.
crypto.hmacsha1hex("input", "secret");
// Returns: "30440f36ddc2809bbd4c8b1f37a6e80d7588c303"
// Example with older webhook systems
const webhookData = response.string();
const oldSignature = crypto.hmacsha1hex(webhookData, bot.getVariable('oldWebhookSecret'));
Parameters:
input
- The data to be hashedsecret
- The secret key for HMAC generation
This method provides HMAC-SHA1 in hexadecimal format for legacy systems that require this specific combination.
Hash Functions
Standard hash functions generate fixed-size message digests from input data without requiring a secret key. These are useful for data integrity checks, cache keys, and non-authenticated hashing scenarios.
crypto.md5(input)
Generate an MD5 hash from an input value.
crypto.md5("input");
// Returns: "a43c1b0aa53a0c908810c06ab1ff3967"
// Example with cache key generation
const userId = bot.getVariable('userId');
const cacheParams = `${userId}:products:page1`;
const cacheKey = crypto.md5(cacheParams);
bot.setVariable('cacheKey', cacheKey);
Parameters:
input
- The data to be hashed
MD5 generates a 128-bit hash value, commonly used for cache keys and non-security applications. MD5 is fast but not cryptographically secure.
Note: MD5 is not suitable for security purposes due to known vulnerabilities. Use it only for non-security applications like cache keys or checksums.
crypto.sha1(input)
Generate a SHA1 hash from an input value.
crypto.sha1("input");
// Returns: "140f86aae51ab9e1cda9b4254fe98a74eb54c1a1"
// Example with data fingerprinting
const requestData = JSON.stringify({user: bot.getVariable('userId'), timestamp: Date.now()});
const fingerprint = crypto.sha1(requestData);
console.log('Request fingerprint:', fingerprint);
Parameters:
input
- The data to be hashed
SHA-1 generates a 160-bit hash value. While stronger than MD5, SHA-1 is also considered cryptographically weak for security applications.
Note: SHA-1 is deprecated for security use but may still be required for legacy system compatibility or non-security applications.
crypto.sha256(input)
Generate a SHA256 hash from an input value.
crypto.sha256("input");
// Returns: "c96c6d5be8d08a12e7b5cdc1b207fa6b2430974c86803d8891675e76fd992c20"
// Example with data integrity verification
const originalData = bot.getVariable('originalData');
const dataHash = crypto.sha256(originalData);
bot.setVariable('dataIntegrityHash', dataHash);
// Example with password hashing (with salt)
const password = bot.getVariable('password');
const salt = formats.randomalphanumeric(16);
const hashedPassword = crypto.sha256(password + salt);
Parameters:
input
- The data to be hashed
SHA-256 is the current industry standard for cryptographic hashing, providing excellent security and wide compatibility across systems.
Note: SHA-256 is cryptographically secure and recommended for most applications requiring strong hash functions.
crypto.sha512(input)
Generate a SHA512 hash from an input value.
crypto.sha512("input");
// Returns: "dc6d6c30f2be9c976d6318c9a534d85e9a1c3f3608321a04b4678ef408124d45d7164f3e562e68c6c0b6c077340a785824017032fddfa924f4cf400e6cbb6adc"
// Example with high-security data verification
const sensitiveData = bot.getVariable('sensitiveData');
const secureHash = crypto.sha512(sensitiveData);
bot.setVariable('secureDataHash', secureHash);
// Example with document integrity
const documentContent = response.string();
const documentHash = crypto.sha512(documentContent);
console.log('Document SHA-512:', documentHash);
Parameters:
input
- The data to be hashed
SHA-512 provides the highest level of security among the available hash functions, generating a 512-bit hash value. Use this for applications requiring maximum security.
Note: SHA-512 offers the strongest security but requires more computational resources than SHA-256. Choose based on your security requirements.
Crypto Examples
These examples demonstrate typical cryptographic scenarios in load testing.
API Authentication with HMAC
Many secure APIs require HMAC signatures to verify the authenticity and integrity of requests. This example shows how to implement a typical API authentication scheme where you create a signature from the request method, path, timestamp, and body. This pattern is common in financial APIs, payment processors, and other high-security systems.
// Generate HMAC signature for API authentication
const timestamp = Math.floor(Date.now() / 1000);
const method = 'POST';
const path = '/api/v1/orders';
const body = JSON.stringify({ item: 'widget', quantity: 5 });
const message = `${method}${path}${timestamp}${body}`;
const signature = crypto.hmacsha256base64(message, bot.getVariable('apiSecret'));
const response = http.post('https://api.example.com/orders', body, {
headers: {
'Content-Type': 'application/json',
'X-API-Key': bot.getVariable('apiKey'),
'X-Timestamp': timestamp.toString(),
'X-Signature': signature
}
});
This authentication pattern ensures that requests cannot be tampered with or replayed by attackers. The timestamp prevents replay attacks, while the signature ensures data integrity. This approach is essential for testing APIs that require strong authentication mechanisms.
Webhook Signature Verification
Webhook systems often include signatures to verify that incoming requests actually came from the expected source and haven’t been tampered with. This example demonstrates how to verify webhook signatures, which is crucial when testing webhook endpoints that need to validate incoming data. This pattern is used by services like GitHub, Stripe, and other platforms that send webhooks.
// Verify webhook signature
const payload = response.string();
const receivedSignature = response.headers['X-Webhook-Signature'];
const expectedSignature = crypto.hmacsha256hex(payload, bot.getVariable('webhookSecret'));
if (receivedSignature === expectedSignature) {
console.log('Webhook signature is valid');
// Process webhook data
const webhookData = JSON.parse(payload);
bot.setVariable('webhookEventId', webhookData.eventId);
} else {
console.error('Webhook signature is invalid');
// Handle security violation
bot.setVariable('webhookVerificationFailed', 'true');
}
Webhook verification is critical for security testing as it ensures your application properly validates incoming data. This pattern helps test both positive cases (valid signatures) and negative cases (invalid or missing signatures) to ensure robust security handling.
Password Hashing and Salting
Secure password storage requires hashing passwords with unique salts to prevent rainbow table attacks. This example shows how to implement proper password hashing for testing authentication systems. While this demonstrates the concept, production systems should use specialized password hashing functions like bcrypt or scrypt.
// Hash password with salt
const password = bot.getVariable('password');
const salt = formats.randomalphanumeric(16);
const hashedPassword = crypto.sha256(password + salt);
bot.setVariable('salt', salt);
bot.setVariable('hashedPassword', hashedPassword);
// Example of verifying password later
const inputPassword = bot.getVariable('loginPassword');
const storedSalt = bot.getVariable('salt');
const storedHash = bot.getVariable('hashedPassword');
const inputHash = crypto.sha256(inputPassword + storedSalt);
if (inputHash === storedHash) {
console.log('Password verification successful');
} else {
console.log('Password verification failed');
}
This pattern is essential for testing authentication flows and password verification systems. The salt ensures that identical passwords produce different hashes, while the verification process demonstrates how to test password checking logic.
Cache Key Generation
Cache systems often need deterministic keys generated from multiple parameters. This example shows how to create consistent cache keys from user data and query parameters. Hashing ensures that cache keys are uniform in length and contain only safe characters, regardless of the input data complexity.
// Generate cache key from multiple parameters
const userId = bot.getVariable('userId');
const category = bot.getVariable('category');
const filters = bot.getVariable('filters');
const sortOrder = bot.getVariable('sortOrder') || 'default';
const pageSize = bot.getVariable('pageSize') || '20';
const cacheKeyData = `${userId}:${category}:${filters}:${sortOrder}:${pageSize}`;
const cacheKey = crypto.md5(cacheKeyData);
bot.setVariable('cacheKey', cacheKey);
// Use cache key in subsequent requests
const response = http.get(`https://api.example.com/products?cache_key=${cacheKey}`);
Cache key generation is useful for testing caching behavior and ensuring that different parameter combinations produce different cache keys. MD5 is sufficient for this non-security use case and provides fast, consistent results.
Request Integrity Checksums
Some APIs require checksums to verify that request data hasn’t been corrupted during transmission. This example demonstrates how to generate request checksums for data integrity verification. This pattern is common in financial systems, data synchronization APIs, and other scenarios where data corruption must be detected.
// Generate checksum for request integrity
const requestData = {
userId: bot.getVariable('userId'),
action: 'purchase',
amount: 29.99,
timestamp: Date.now(),
transactionId: formats.uuid()
};
const requestBody = JSON.stringify(requestData);
const checksum = crypto.sha256(requestBody);
const response = http.post('https://api.example.com/transaction', requestBody, {
headers: {
'Content-Type': 'application/json',
'X-Checksum': checksum,
'X-Client-Version': '1.0.0'
}
});
// Verify response integrity if API provides response checksum
const responseChecksum = response.headers['X-Response-Checksum'];
if (responseChecksum) {
const calculatedChecksum = crypto.sha256(response.string());
if (calculatedChecksum === responseChecksum) {
console.log('Response integrity verified');
} else {
console.error('Response integrity check failed');
}
}
Checksum verification helps test both request integrity (ensuring your data is sent correctly) and response integrity (ensuring the server’s response hasn’t been corrupted). This is crucial for testing mission-critical systems where data integrity is paramount.
JWT-like Token Generation
JSON Web Tokens (JWTs) are commonly used for authentication and authorization in modern APIs. This example shows how to create JWT-like tokens for testing purposes. While this is a simplified implementation, it demonstrates the core JWT structure and can be useful for testing systems that expect JWT-formatted tokens.
// Generate a simple token (not a full JWT implementation)
const header = formats.base64encode(JSON.stringify({
alg: 'HS256',
typ: 'JWT'
}));
const payload = formats.base64encode(JSON.stringify({
sub: bot.getVariable('userId'),
iss: 'loadster-test',
aud: 'api.example.com',
exp: Math.floor(Date.now() / 1000) + 3600, // 1 hour
iat: Math.floor(Date.now() / 1000),
jti: formats.uuid() // unique token ID
}));
const unsigned = `${header}.${payload}`;
const signature = crypto.hmacsha256base64(unsigned, bot.getVariable('jwtSecret'));
const token = `${unsigned}.${signature}`;
bot.setVariable('authToken', token);
// Use token in subsequent requests
const response = http.get('https://api.example.com/protected-resource', {
headers: {
'Authorization': `Bearer ${token}`
}
});
This token generation pattern is useful for testing JWT-based authentication systems. The token includes standard JWT claims and can be used to test both token generation and validation scenarios in your load tests.
Data Integrity Verification
Data integrity verification ensures that information hasn’t been corrupted or tampered with during storage or transmission. This example shows how to implement integrity checks in your load tests, which is crucial when testing systems that handle sensitive or critical data. This pattern helps verify that your application correctly detects and handles data corruption.
// Verify data integrity
const originalData = bot.getVariable('originalData');
const expectedHash = bot.getVariable('expectedHash');
const actualHash = crypto.sha256(originalData);
if (actualHash === expectedHash) {
console.log('Data integrity verified');
bot.setVariable('integrityCheckPassed', 'true');
// Continue with test flow
const response = http.post('https://api.example.com/process-data', originalData);
} else {
console.error('Data integrity check failed');
console.error(`Expected: ${expectedHash}`);
console.error(`Actual: ${actualHash}`);
bot.setVariable('integrityCheckPassed', 'false');
bot.setVariable('integrityFailureReason', 'Hash mismatch');
// Decide whether to continue or stop the test
if (bot.getVariable('strictIntegrityMode') === 'true') {
bot.exit(); // Stop the test if data is corrupted
}
}
Integrity verification is essential for testing data processing systems, file transfers, and any scenario where data corruption could have serious consequences. This pattern helps ensure your tests can detect and properly handle data integrity issues.