Skip to main content

Scripting ›Crypto & Utils

Auf GitHub bearbeiten

Diese Dokumentation ist auf Englisch verfügbar.

Crypto & Utils

dotfetch.crypto covers what most signed or authenticated APIs need: hashes, HMAC signatures, UUIDs, and random values. dotfetch.utils adds Base64 that handles any language. Both work in Pre-Request and Post-Response scripts, and every function returns a plain string.

FunctionReturns
crypto.sha256(data, encoding?)SHA-256 hash
crypto.hash(algorithm, data, encoding?)Hash with any supported algorithm
crypto.hmac(algorithm, key, data, options?)HMAC signature
crypto.uuid()Random UUID v4
crypto.randomHex(bytes?)Random hex string
utils.base64Encode(text)Base64 of UTF-8 text
utils.base64Decode(text)UTF-8 text from Base64

Supported values

OptionValuesDefault
algorithmmd5, sha1, sha256, sha384, sha512—
encoding (output)hex, base64, base64urlhex
keyEncoding (HMAC key)utf8, hex, base64, base64urlutf8

Anything else throws, for example Unsupported algorithm 'sha3'. Use one of: md5, sha1, sha256, sha384, sha512. A typo fails loudly instead of quietly sending a wrong signature.

Text input is always read as UTF-8.

sha256

JS
dotfetch.crypto.sha256(data, encoding = 'hex')
JS
dotfetch.crypto.sha256('abc');
// 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'

dotfetch.crypto.sha256('abc', 'base64');
// 'ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0='

Example: send a hash of the body so the server can detect tampering.

JS
const body = dotfetch.env.resolve(dotfetch.request.body);
dotfetch.request.headers['X-Content-SHA256'] = dotfetch.crypto.sha256(body);

hash

JS
dotfetch.crypto.hash(algorithm, data, encoding = 'hex')
JS
dotfetch.crypto.hash('md5', 'abc');      // '900150983cd24fb0d6963f7d28e17f72'
dotfetch.crypto.hash('sha1', 'abc');     // 'a9993e364706816aba3e25717850c26c9cd0d89d'
dotfetch.crypto.hash('sha512', 'abc', 'base64url');

md5 and sha1 are there for older APIs that require them. Don't choose them for anything new.

hmac

JS
dotfetch.crypto.hmac(algorithm, key, data, { encoding = 'hex', keyEncoding = 'utf8' } = {})

HMAC is how most webhook and partner APIs (Stripe-style, Shopify-style, and many internal APIs) check that a request really came from you.

JS
dotfetch.crypto.hmac('sha256', 'key', 'The quick brown fox jumps over the lazy dog');
// 'f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8'

dotfetch.crypto.hmac('sha256', 'key', 'The quick brown fox jumps over the lazy dog', { encoding: 'base64' });
// '97yD9DBThCSxMpjmqm+xQ+9NWaFJRhdZl0edvC0aPNg='

Sign the body

JS
const secret = dotfetch.env.get('API_SECRET');
const body = dotfetch.env.resolve(dotfetch.request.body);   // the exact bytes that will be sent
dotfetch.request.headers['X-Signature'] = dotfetch.crypto.hmac('sha256', secret, body);

Sign a timestamp and the body

Many APIs sign timestamp + "." + body so an old request can't be replayed:

JS
const ts = String(Math.floor(Date.now() / 1000));
const body = dotfetch.env.resolve(dotfetch.request.body);
const sig = dotfetch.crypto.hmac('sha256', dotfetch.env.get('API_SECRET'), `${ts}.${body}`);

dotfetch.request.headers['X-Timestamp'] = ts;
dotfetch.request.headers['X-Signature'] = `t=${ts},v1=${sig}`;

Keys that aren't plain text

If your API gives you the secret as hex or Base64, say so with keyEncoding and the raw bytes are used:

JS
dotfetch.crypto.hmac('sha256', dotfetch.env.get('SECRET_B64'), body, { keyEncoding: 'base64' });

Chained HMACs (AWS Signature V4 style)

Some schemes derive a signing key in steps, where each step's output (hex) is the next step's key. Pass keyEncoding: 'hex' for every step after the first:

JS
const h = (key, data, keyEncoding) => dotfetch.crypto.hmac('sha256', key, data, { keyEncoding });

const date = '20260101';
const kDate    = h('AWS4' + dotfetch.env.get('AWS_SECRET'), date);
const kRegion  = h(kDate,   'eu-west-1',    'hex');
const kService = h(kRegion, 's3',           'hex');
const kSigning = h(kService, 'aws4_request', 'hex');
// sign your string-to-sign with kSigning, again using keyEncoding: 'hex'

uuid

JS
dotfetch.crypto.uuid()

Returns a random UUID v4, like '3b241101-e2bb-4255-8caf-4136c566a962'. Use it for idempotency keys and request IDs:

JS
dotfetch.request.headers['Idempotency-Key'] = dotfetch.crypto.uuid();

randomHex

JS
dotfetch.crypto.randomHex(bytes = 16)

Returns bytes cryptographically random bytes as hex, so the string is twice as long as bytes. bytes must be between 1 and 1024.

JS
dotfetch.crypto.randomHex();     // 32 hex chars, e.g. '9f86d081884c7d659a2feaa0c55ad015'
dotfetch.crypto.randomHex(8);    // 16 hex chars

Use it for nonces:

JS
dotfetch.request.headers['X-Nonce'] = dotfetch.crypto.randomHex(12);

base64Encode and base64Decode

JS
dotfetch.utils.base64Encode(text)
dotfetch.utils.base64Decode(base64)

UTF-8 safe Base64. Unlike the browser's btoa, these work with Arabic, emoji, and any other text:

JS
dotfetch.utils.base64Encode('مرحبا 👋');                // '2YXYsdit2KjYpyDwn5GL'
dotfetch.utils.base64Decode('2YXYsdit2KjYpyDwn5GL');    // 'مرحبا 👋'

Example: build a Basic header yourself, with Auth set to No Auth.

JS
const user = dotfetch.env.get('USER');
const pass = dotfetch.env.get('PASS');
dotfetch.request.headers['Authorization'] = 'Basic ' + dotfetch.utils.base64Encode(`${user}:${pass}`);

Example: read the payload of a JWT (without verifying it) in a Post-Response script.

JS
const token = dotfetch.response.json().access_token;
const payloadPart = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
const claims = JSON.parse(dotfetch.utils.base64Decode(payloadPart));
console.log('token expires at', new Date(claims.exp * 1000).toISOString());
Crypto & Utils · DotFetch Docs | dotsuite