Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/runtime/hashing.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,35 @@ console.log(arr);
// => Uint8Array(32) [ 185, 77, 39, 185, 147, ... ]
```

### Hash in one call with `Bun.CryptoHasher.hash`

`Bun.CryptoHasher.hash()` hashes one input without a hasher object. Pass the algorithm and the data. The third argument is optional.

- Without it, Bun returns the hash in a new `Buffer`.
- With an encoding, Bun returns the hash as a string.
- With a `TypedArray`, Bun writes the hash to the start of the array and returns the array. The array must hold at least as many bytes as the hash.

```ts
Bun.CryptoHasher.hash("sha256", "hello world");
// => <Buffer b9 4d 27 b9 93 ...>

Bun.CryptoHasher.hash("sha256", "hello world", "hex");
// => "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
```

The third argument can also be an object with the `outputEncoding` and `outputLength` options of [`crypto.hash()`](https://nodejs.org/api/crypto.html#cryptohashalgorithm-data-options) in `node:crypto`.

- `outputEncoding` is the encoding of the returned string. `"buffer"` returns a `Buffer`. With an options object the default is `"hex"`, as in Node.js.
- `outputLength` is the length in bytes of a `"shake128"` or `"shake256"` hash. Pass it for those two algorithms. Without it, their hashes are 16 and 32 bytes long. Node.js deprecates that default. A `TypedArray` third argument also receives 16 or 32 bytes.

```ts
Bun.CryptoHasher.hash("shake256", "hello world", { outputLength: 8 });
// => "369771bb2cb9d2b0"

Bun.CryptoHasher.hash("shake256", "hello world", { outputLength: 8, outputEncoding: "buffer" });
// => <Buffer 36 97 71 bb 2c b9 d2 b0>
```

### HMAC in `Bun.CryptoHasher`

`Bun.CryptoHasher` can compute HMAC digests. Pass the key to the constructor.
Expand Down
67 changes: 67 additions & 0 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6330,6 +6330,49 @@ declare module "bun" {
hashInto: NodeJS.TypedArray,
): NodeJS.TypedArray;

/**
* Run the hash over the given data, with the `outputEncoding` and `outputLength` options of `hash()` in
* `node:crypto`
*
* @param input `string`, `Uint8Array`, or `ArrayBuffer` to hash. `Uint8Array` or `ArrayBuffer` is faster.
*
* @param options `outputEncoding: "buffer"` returns the hash in a new `Buffer`
*/
static hash(
algorithm: SupportedCryptoAlgorithms,
input: Bun.BlobOrStringOrBuffer,
options: CryptoHasherHashOptions & { outputEncoding: "buffer" },
): Buffer;

/**
* Run the hash over the given data, with the `outputEncoding` and `outputLength` options of `hash()` in
* `node:crypto`
*
* @param input `string`, `Uint8Array`, or `ArrayBuffer` to hash. `Uint8Array` or `ArrayBuffer` is faster.
*
* @param options Without `outputEncoding` the hash is a hex string, as in `node:crypto`. A call without a third
* argument returns a `Buffer` instead
*/
static hash(
algorithm: SupportedCryptoAlgorithms,
input: Bun.BlobOrStringOrBuffer,
options: CryptoHasherHashOptions & { outputEncoding?: DigestEncoding | null | undefined },
): string;

/**
* Run the hash over the given data, with the `outputEncoding` and `outputLength` options of `hash()` in
* `node:crypto`
*
* @param input `string`, `Uint8Array`, or `ArrayBuffer` to hash. `Uint8Array` or `ArrayBuffer` is faster.
*
* @param options The hash is a `Buffer` when `outputEncoding` is `"buffer"`, and a string otherwise
*/
static hash(
algorithm: SupportedCryptoAlgorithms,
input: Bun.BlobOrStringOrBuffer,
options: CryptoHasherHashOptions,
): string | Buffer;

/**
* Run the hash over the given data
*
Expand All @@ -6351,6 +6394,30 @@ declare module "bun" {
static readonly algorithms: SupportedCryptoAlgorithms[];
}

/**
* What {@link CryptoHasher.hash} takes in place of an encoding: the `outputEncoding` and `outputLength` options of
* `hash()` in `node:crypto`.
*
* Node.js also has `functionName` and `customization`, for cSHAKE. Bun does not support them, and throws when
* either is set.
*/
interface CryptoHasherHashOptions {
/**
* The encoding of the string that holds the hash. `"buffer"` returns the hash in a new `Buffer` instead.
*
* @default "hex"
*/
outputEncoding?: DigestEncoding | "buffer" | null | undefined;

/**
* The length of the hash in bytes, for `"shake128"` and `"shake256"`. Pass it for those two. Without it their
* hashes are 16 and 32 bytes long, a default that Node.js deprecates (DEP0198).
*
* The hashes of every other algorithm have one length. For those, any other number throws.
*/
outputLength?: number | undefined;
}

/**
* Returns a `Promise` that resolves after the given number of milliseconds,
* or at the given {@link Date}. Like {@link setTimeout}, except it returns a
Expand Down
4 changes: 2 additions & 2 deletions src/js/node/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,8 @@ crypto_exports.createPrivateKey = createPrivateKey;
var webcrypto = crypto;
var _subtle = webcrypto.subtle;

crypto_exports.hash = function hash(algorithm, input, outputEncoding: import("bun").DigestEncoding = "hex") {
return CryptoHasher.hash(algorithm, input, outputEncoding);
crypto_exports.hash = function hash(algorithm, input, options) {
return CryptoHasher.hash(algorithm, input, options === undefined ? "hex" : options);
};

crypto_exports.pbkdf2 = pbkdf2;
Expand Down
39 changes: 33 additions & 6 deletions src/runtime/crypto/CryptoHasher.bind.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,42 @@ export const DigestOutput = b.union({
into: b.bufferSource.allowShared,
});

/** The third argument of node's `crypto.hash`: https://github.com/nodejs/node/blob/v26.12.1/lib/internal/crypto/hash.js#L341-L378 */
export const HashOptions = b.dictionary(
{
/** `"hex"` without one. node reads `outputLength` before it. It stands first here so that its wrong type is reported first, as in node. */
outputEncoding: { type: b.string.nullable, expected: ["string"] },
/** How long a digest of shake128 or shake256 is. For any other algorithm, the length its digests have. */
outputLength: b.u32.validateInteger().optional,
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
/** cSHAKE, which Bun does not have: the body refuses anything but `undefined`. */
functionName: b.any,
customization: b.any,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
},
{ reportedAs: "" },
);

/** `DigestOutput`, and for the static `CryptoHasher.hash` alone what `crypto.hash` takes in its place. */
export const HashOutput = b.union({
encoding: b.string.utf8,
into: b.bufferSource.allowShared,
/** node refuses a function, which has members as any object does: https://github.com/nodejs/node/blob/v26.12.1/lib/internal/validators.js#L252-L261 */
function: b.callable,
/** And an array, in words that name the argument. */
array: b.jsArray,
options: HashOptions,
});

/** A string for an encoding, the buffer that was given, or else a new one of the class. */
const digestIn = (newBuffer: "Buffer" | "Uint8Array") =>
const digestIn = (newBuffer: "Buffer" | "Uint8Array", operand = "output") =>
b.any.returning(
{ type: "Primitive", primitive: "String" },
{ type: "Operand", operand: "output" },
{ type: "Operand", operand },
{ type: "Instance", class: newBuffer, isOfClassItself: true },
);

const method = { capability: "heap", throws: true } as const;
const uses = { output: [...table.handedOver, table.writesContents()] };
const usesOf = (operand: string) => ({ [operand]: [...table.handedOver, table.writesContents()] });
const uses = usesOf("output");
const update = { ...method, returns: b.self, passThis: true, mutates: true } as const;
const digestOf = (newBuffer: "Buffer" | "Uint8Array") =>
({ ...method, args: { output: DigestOutput.nullable }, returns: digestIn(newBuffer), mutates: true, uses }) as const;
Expand Down Expand Up @@ -53,9 +79,10 @@ export const CryptoHasher = b.class({
algorithms: { getter: b.array(b.string.utf8) },
hash: {
...method,
args: { algorithm: b.string, input, output: DigestOutput.optional },
returns: digestIn("Buffer"),
uses,
args: { algorithm: b.string, input, options: HashOutput.optional },
expected: { options: ["object"] },
returns: digestIn("Buffer", "options"),
uses: usesOf("options"),
},
},
});
Expand Down
Loading
Loading