Skip to main content

Crypto helpers in agent functions

crypto from "@yellow/bot" creates IDs, hashes and signs values, and encrypts and decrypts with AES. These helpers don't count towards any limit, and they return their result directly, so no await is needed.

import { crypto } from "@yellow/bot";
MethodUse it toReturns
crypto.randomUUID()Create a unique ID"327abc3f-e64a-43b8-a6b2-a3eb73022919"
crypto.hash(algorithm, value)Hash a value: md5, sha1, sha256, sha384 or sha512Hex text
crypto.hmac(algorithm, secret, value)Sign a value with a secret, for example a webhook payloadHex text
crypto.encrypt(cipher, value, { key, iv })Encrypt with AESBase64 text
crypto.decrypt(cipher, value, { key, iv })Decrypt a value encrypted with the same cipher, key and ivText
crypto.randomBytes(size)Generate up to 65,536 random bytesHex text

To get base64 instead of hex, pass { outputEncoding: "base64" } as the last argument to hash or hmac, or "base64" as the second argument to randomBytes.

Encryption​

The cipher is aes-128, aes-192 or aes-256 in cbc, ecb or ctr mode, for example "aes-256-cbc". The key length must match the cipher. cbc and ctr need a 16-byte iv; ecb doesn't take one. The output matches Node.js createCipheriv for the same settings, so your own systems can decrypt it.

const encrypted = crypto.encrypt("aes-256-cbc", cardNumber, { key, iv });
const original = crypto.decrypt("aes-256-cbc", encrypted, { key, iv });

Example: sign a webhook​

import { apis, crypto, variables } from "@yellow/bot";

export default async function ({ orderId, amount }) {
const { partnerSecret } = await variables.global.get(["partnerSecret"]);

const payload = JSON.stringify({ orderId, amount });
const signature = crypto.hmac("sha256", partnerSecret, payload);

const response = await apis.execute("partnerWebhook", {
payload,
signature,
requestId: crypto.randomUUID(),
});
return { delivered: response.status === 200 };
}