| 1 | import { createHash } from "node:crypto"; |
| 2 | import { toHex } from "./bytes.js"; |
| 3 | |
| 4 | /** SHA-1 using WebCrypto (available in Workers and Node 20+). */ |
| 5 | export async function sha1(data: Uint8Array): Promise<Uint8Array> { |
| 6 | const digest = await crypto.subtle.digest("SHA-1", data as BufferSource); |
| 7 | return new Uint8Array(digest); |
| 8 | } |
| 9 | |
| 10 | export async function sha1Hex(data: Uint8Array): Promise<string> { |
| 11 | return toHex(await sha1(data)); |
| 12 | } |
| 13 | |
| 14 | export async function sha256Hex(data: Uint8Array): Promise<string> { |
| 15 | return toHex(new Uint8Array(await crypto.subtle.digest("SHA-256", data as BufferSource))); |
| 16 | } |
| 17 | |
| 18 | /** |
| 19 | * Incremental SHA-1, for checksums over data that is never held whole (a pack streamed to a client). |
| 20 | * WebCrypto only hashes a complete buffer, so this is node:crypto's (native in Workers with |
| 21 | * nodejs_compat): a clone hashes its whole pack, and a hash in JavaScript was over a third of the time. |
| 22 | */ |
| 23 | export class Sha1 { |
| 24 | private h = createHash("sha1"); |
| 25 | |
| 26 | update(data: Uint8Array): this { |
| 27 | this.h.update(data); |
| 28 | return this; |
| 29 | } |
| 30 | |
| 31 | digest(): Uint8Array { |
| 32 | const d = this.h.digest(); |
| 33 | return new Uint8Array(d.buffer, d.byteOffset, d.byteLength); |
| 34 | } |
| 35 | } |