-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #600 from snyk/fix/hash-large-files
fix: compute sha1 on .jar files of size up to buffer.constants.MAX_LENGTH
- Loading branch information
Showing
3 changed files
with
15 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,24 @@ | ||
import * as crypto from "crypto"; | ||
import { Readable } from "stream"; | ||
import { HashAlgorithm } from "./types"; | ||
|
||
const HASH_ENCODING = "hex"; | ||
|
||
export async function bufferToSha1(buffer: Buffer): Promise<string> { | ||
const stream = Readable.from(buffer); | ||
const hash = crypto.createHash(HashAlgorithm.Sha1); | ||
const chunkSize = 100 * 1024 * 1024; // 100 MB | ||
|
||
return new Promise((resolve, reject) => { | ||
stream | ||
.pipe(hash) | ||
.on("finish", () => { | ||
hash.end(); | ||
const digest = hash.read().toString(HASH_ENCODING); | ||
resolve(digest); | ||
}) | ||
.on("error", (err) => { | ||
reject(err); | ||
}); | ||
try { | ||
for (let offset = 0; offset < buffer.length; offset += chunkSize) { | ||
const end = Math.min(offset + chunkSize, buffer.length); | ||
const chunk = buffer.slice(offset, end); | ||
hash.update(chunk); | ||
} | ||
|
||
const digest = hash.digest(HASH_ENCODING); | ||
resolve(digest); | ||
} catch (err) { | ||
reject(err); | ||
} | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters