Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(node/crypto): add base64url encoding to hash.digest() #2740

Merged
merged 4 commits into from
Oct 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions node/crypto_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@ Deno.test("[node/crypto.Hash] basic usage - hex output", () => {
assertEquals(d, "1f8ac10f23c5b5bc1167bda84b833e5c057a77d2");
});

Deno.test("[node/crypto.Hash] basic usage - base64 output", () => {
const d = createHash("sha1").update("abc").update("def").digest("base64");
assertEquals(d, "H4rBDyPFtbwRZ72oS4M+XAV6d9I=");
});

Deno.test("[node/crypto.Hash] basic usage - base64url output", () => {
const d = createHash("sha1").update("abc").update("def").digest("base64url");
assertEquals(d, "H4rBDyPFtbwRZ72oS4M-XAV6d9I");
});

Deno.test("[node/crypto.Hash] streaming usage", async () => {
const source = Readable.from(["abc", "def"]);
const hash = createHash("sha1");
Expand Down
5 changes: 4 additions & 1 deletion node/internal/crypto/hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { Buffer } from "../../buffer.ts";
import { Transform } from "../../stream.ts";
import { encode as encodeToHex } from "../../../encoding/hex.ts";
import { encode as encodeToBase64 } from "../../../encoding/base64.ts";
import { encode as encodeToBase64Url } from "../../../encoding/base64url.ts";
import type { TransformOptions } from "../../_stream.d.ts";
import { validateString } from "../validators.mjs";
import { notImplemented } from "../../_utils.ts";
Expand Down Expand Up @@ -100,7 +101,7 @@ export class Hash extends Transform {
*
* If encoding is provided a string will be returned; otherwise a Buffer is returned.
*
* Supported encoding is currently 'hex', 'binary', 'base64'.
* Supported encodings are currently 'hex', 'binary', 'base64', 'base64url'.
*/
digest(encoding?: string): Buffer | string {
const digest = this.#context.digest(undefined);
Expand All @@ -115,6 +116,8 @@ export class Hash extends Transform {
return String.fromCharCode(...digest);
case "base64":
return encodeToBase64(digest);
case "base64url":
return encodeToBase64Url(digest);
default:
throw new Error(
`The output encoding for hash digest is not implemented: ${encoding}`,
Expand Down