Crypto & Encoding

Hashing, HMAC, and base64 encoding utilities

Hashing

Generate cryptographic hashes using the crypto global. All hash functions return lowercase hex strings.

crypto.md5(data)

MD5 hash as hex string (32 chars)

crypto.sha1(data)

SHA-1 hash as hex string (40 chars)

crypto.sha256(data)

SHA-256 hash as hex string (64 chars)

export default function() {
  const payload = JSON.stringify({ user: 'test', ts: Date.now() });

  // Generate content hashes
  const md5Hash = crypto.md5(payload);
  const sha1Hash = crypto.sha1(payload);
  const sha256Hash = crypto.sha256(payload);

  // Use hash for content integrity
  http.post('https://api.example.com/data', payload, {
    headers: {
      'Content-Type': 'application/json',
      'X-Content-SHA256': sha256Hash
    }
  });
}

HMAC

Generate HMAC (Hash-based Message Authentication Code) signatures for API authentication.

crypto.hmac(algorithm, key, data)

HMAC signature as hex string. Algorithm: "md5", "sha1", or "sha256"

export default function() {
  const secret = __ENV.API_SECRET;
  const payload = JSON.stringify({ action: 'transfer', amount: 100 });

  // Sign request with HMAC-SHA256
  const signature = crypto.hmac('sha256', secret, payload);

  http.post('https://api.example.com/secure', payload, {
    headers: {
      'Content-Type': 'application/json',
      'X-Signature': signature
    }
  });
}

Base64 Encoding

Encode and decode data using the encoding global.

encoding.b64encode(data)

Encode string to base64

encoding.b64decode(data)

Decode base64 string back to UTF-8

export default function() {
  // Basic Auth header
  const credentials = encoding.b64encode('username:password');
  http.get('https://api.example.com/protected', {
    headers: { 'Authorization': 'Basic ' + credentials }
  });

  // Encode/decode round-trip
  const encoded = encoding.b64encode('Hello, World!');
  const decoded = encoding.b64decode(encoded);
  // decoded === 'Hello, World!'
}

# Binary data with WebSocket

export default function() {
  const socket = ws.connect('wss://example.com/binary');

  // Send binary data as base64
  const binaryPayload = encoding.b64encode('binary content here');
  socket.sendBinary(binaryPayload);

  // Receive binary response
  const msg = socket.recv();
  if (msg && msg.type === 'binary') {
    const decoded = encoding.b64decode(msg.data);
    print('Received: ' + decoded);
  }

  socket.close();
}