Skip to content

Instantly share code, notes, and snippets.

@ghostzero
Created February 24, 2025 19:31
Show Gist options
  • Select an option

  • Save ghostzero/482b6a91c25494e53c0a3b8862ad0ac5 to your computer and use it in GitHub Desktop.

Select an option

Save ghostzero/482b6a91c25494e53c0a3b8862ad0ac5 to your computer and use it in GitHub Desktop.
<template>
<div id="app">
<h1>MD5 File Hash Calculator</h1>
<input type="file" @change="handleFileChange" />
<p v-if="finalHash">MD5 Hash: {{ finalHash }}</p>
</div>
</template>
<script setup lang="ts">
import { createMD5 } from 'hash-wasm'
const finalHash = ref<string | null>(null);
const handleFileChange = async (event: Event) => {
const file = (event.target as HTMLInputElement).files?.[0];
if (!file) return;
const chunkSize = 16777216;
finalHash.value = await calculate(file, chunkSize);
}
async function calculate(file: File, chunkSize: number) {
const dataSize = file.size;
let sumOfSums = [];
let parts = 0;
let position = 0;
while (position < dataSize) {
let length = chunkSize;
if (position + chunkSize > dataSize) {
length = dataSize - position;
}
const sum = await md5sum(file, position, length);
console.log(`Part ${parts + 1}: ${sum.toString('hex')}`);
sumOfSums.push(sum);
parts++;
position += length;
}
let finalSum;
if (parts === 1) {
finalSum = sumOfSums[0];
} else {
const hasher = await createMD5();
const hexString = sumOfSums.join('');
const byteArray = new Uint8Array(hexString.length / 2);
for (let i = 0; i < hexString.length; i += 2) {
byteArray[i / 2] = parseInt(hexString.substring(i, i + 2), 16);
}
hasher.update(byteArray);
finalSum = hasher.digest();
}
let sumHex = finalSum.toString('hex');
if (parts > 1) {
sumHex += '-' + parts;
}
return sumHex;
}
function md5sum(file: File, start, length) {
return new Promise(async (resolve) => {
const hasher = await createMD5();
const reader = new FileReader();
reader.onload = () => {
const buffer = reader.result as ArrayBuffer;
const view = new Uint8Array(buffer);
hasher.update(view);
resolve(hasher.digest());
};
const chunk = file.slice(start, start + length);
reader.readAsArrayBuffer(chunk);
});
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment