crypto
The crypto extension provides hashing, HMAC, random byte generation, and UUID creation.
API
| Method | Description |
|---|---|
crypto.md5(str) | MD5 hash (hex string) |
crypto.sha1(str) | SHA-1 hash (hex string) |
crypto.sha256(str) | SHA-256 hash (hex string) |
crypto.sha512(str) | SHA-512 hash (hex string) |
crypto.hmac(algo, key, data) | HMAC signature (hex string) |
crypto.randomBytes(length) | Random bytes as hex string |
crypto.uuid() | Generate a v4 UUID |
Hashing
const hash = crypto.sha256("password123");
// "ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f"
// Password hashing
const passwordHash = crypto.sha256(userInput);
db.exec("INSERT INTO users (email, password) VALUES (?, ?)", [email, passwordHash]);
HMAC
// Supported algorithms: md5, sha1, sha256, sha512
const signature = crypto.hmac("sha256", "my-secret-key", request.body);
// Webhook verification
if (request.headers["x-signature"] !== crypto.hmac("sha256", SECRET, request.body)) {
response.setStatus(403);
print("Invalid signature");
}
Random Bytes
// Returns hex string (32 hex chars = 16 bytes)
const token = crypto.randomBytes(16);
// "a3f2b8c91d4e7f0612345678abcdef01"
// Generate a session token
const sessionToken = crypto.randomBytes(32);
UUID
const id = crypto.uuid();
// "550e8400-e29b-41d4-a716-446655440000"
// Use as database ID
db.exec("INSERT INTO items (id, name) VALUES (?, ?)", [crypto.uuid(), "New Item"]);
Common Patterns
API Key Generation
const apiKey = "jscgi_" + crypto.randomBytes(24);
Content Hashing (ETags)
const content = file.read("/var/www/data/page.html");
const etag = crypto.md5(content);
response.setHeader("ETag", etag);