Git Product home page Git Product logo

ts-md5's Introduction

Introduction

A MD5 implementation for TypeScript

  • Can handle Unicode strings
  • Supports incremental hashing
  • Works with Files and Blobs

This library also includes tools for:

  • Hashing a file or blob
  • A webworker for performing hashing
  • A webworker handler for requesting files or blobs to be hashed
    • promise based
    • files or blobs are queued for processing on the webworker

Based on work by

Usage

Install

Install the node module with npm install ts-md5

Basic Hashing

  1. Import the class
    • import {Md5} from 'ts-md5';
  2. Hash some things
    • Md5.hashStr('blah blah blah') => hex:string
    • Md5.hashStr('blah blah blah', true) => raw:Int32Array(4)
    • Md5.hashAsciiStr('blah blah blah') => hex:string
    • Md5.hashAsciiStr('blah blah blah', true) => raw:Int32Array(4)

For more complex uses:

md5 = new Md5();

// Append incrementally your file or other input
// Methods are chainable
md5.appendStr('somestring')
    .appendAsciiStr('a different string')
    .appendByteArray(blob);

// Generate the MD5 hex string
md5.end();

Hashing a File

NOTE:: You have to make sure ts-md5/dist/md5_worker.js is made available in your build so it can be accessed directly by a browser It should always remain as a seperate file.

import {ParallelHasher} from 'ts-md5';

let hasher = new ParallelHasher('/path/to/ts-md5/dist/md5_worker.js');
hasher.hash(fileBlob).then(function(result) {
   console.log('md5 of fileBlob is', result);
});

Building from src

The project is written in typescript and transpiled into ES5.

  1. Install TypeScript: npm install -g typescript (if you haven't already)
  2. Configure compile options in tsconfig.json
  3. Perform build using: tsc

You can find more information here: https://github.com/Microsoft/TypeScript/wiki/tsconfig.json

Scripts

  1. Build Script: npm run build
  2. Test Script: npm run test

Publishing

  1. Sign up to https://www.npmjs.com/
  2. Configure package.json https://docs.npmjs.com/files/package.json
  3. run npm publish https://docs.npmjs.com/cli/publish

License

MIT

ts-md5's People

Contributors

blackholegalaxy avatar dependabot[bot] avatar fsallin avatar itsmontoya avatar johnbendi avatar jounqin avatar mryuion avatar realjoshbyrnes avatar sokolovstas avatar stakach avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

ts-md5's Issues

missing licence

Hey, we wan't to use your project, but there is a licence missing in your project :)
Thanks a lot.

md5_worker.js fails with 'require is not defined'

I cloned the repo and copied dist/* to my Angular 4.4.6 application (both under node_modules/ts-md5/dist and src/assets). Then attempted to md5sum a file per the following snippet.

import { Md5 } from 'ts-md5/dist/md5';
import { ParallelHasher } from 'ts-md5/dist/parallel_hasher';
...
    for (let i = 0; i < this.filesToUpload.length; i++) {
      const fileReader = new FileReader();
      fileReader.onload = function(e : ProgressEvent) {
        let hasher = new ParallelHasher('assets/md5_worker.js');
        hasher.hash(fileReader.result)
          .then(function(result) {
            console.log('hash: ' + result);
          });
        const md5 = new Md5();
         md5.appendByteArray(fileReader.result);
        console.log("hash: " + md5.end()); // this isn't correct. 
      };
      fileReader.readAsBinaryString(this.filesToUpload[i]);

When running the app, Chrome's console shows:
ErrorEvent {isTrusted: true, message: "Uncaught ReferenceError: require is not defined", filename: "http://localhost:4200/assets/md5_worker.js", lineno: 401, colno: 13, …}

Line 401 of md5_worker.js corresponds to this statement:
`var md5_1 = require("./md5");

Is RequireJS meant to be a prerequisite of ts-md5?

As a secondary but related issue:
I had first tried using the latest version (v1.2.2) of ts-md5 from NPM. But it also failed with:
ErrorEvent {isTrusted: true, message: "Uncaught TypeError: Md5.Md5 is not a constructor", filename: "http://localhost:4200/assets/md5_worker.js", lineno: 417, colno: 21, …} Uncaught TypeError: Md5.Md5 is not a constructor at Md5FileHasher.hash (md5_worker.js:417) at global.onmessage (md5_worker.js:502)

Line 417 of md5_worker.js corresponds to:

    Md5FileHasher.prototype.hash = function (blob) {
        var self = this;
        self._blob = blob;
        self._length = Math.ceil(blob.size / self._partSize);
        self._part = 0;
        self._md5 = new Md5.Md5();   <---  FAILS HERE
        self._processPart();
    };

So md5_worker.js doesn't work whether it's from
a. the head of git: "Uncaught ReferenceError: require is not defined"
b. or NPM: "Uncaught TypeError: Md5.Md5 is not a constructor"

And FYI, the version on NPM is a few months out-of-date compared to git.

I'd appreciate any help getting the file hashing feature of ts-md5 operational in my app.

Thanks,
David

(Sorry for the earlier, empty post. I accidentally hit Enter just as I had started composing this).

Cannot find name 'WorkerOptions'.

I have update ts-md5 to 1.2.5. and get the error

Cannot find name 'WorkerOptions'.

constructor(workerUri: string, workerOptions?: WorkerOptions);

Compile errors

When compiling, I receive the following errors:

node_modules/ts-md5/src/md5.ts(242,31): error TS2531: Object is possibly 'null'.
node_modules/ts-md5/src/md5.ts(243,31): error TS2531: Object is possibly 'null'.
node_modules/ts-md5/src/md5.ts(263,17): error TS2322: Type 'string' is not assignable to type 'never'.
node_modules/ts-md5/src/md5.ts(265,17): error TS2322: Type 'string' is not assignable to type 'never'.
node_modules/ts-md5/src/md5.ts(272,30): error TS7006: Parameter 'x' implicitly has an 'any' type.
node_modules/ts-md5/src/md5.ts(272,33): error TS7006: Parameter 'k' implicitly has an 'any' type.

Provide a Changelog

I see there is a new version 1.2.10, it would to good to now what changed in this version

It would be great if this project could provide a changelog information (e.g. CHANGELOG.md, or using the github releases).

'require is not defined'

Recreation

Environment

OS

elementary OS 5.0 Juno

Angular

Angular CLI: 8.3.12
Node: 12.12.0
OS: linux x64
Angular: 8.0.1
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.800.3
@angular-devkit/build-angular     0.800.3
@angular-devkit/build-optimizer   0.800.3
@angular-devkit/build-webpack     0.800.3
@angular-devkit/core              8.0.3
@angular-devkit/schematics        8.3.12
@angular/cdk                      8.1.1
@angular/cli                      8.3.12
@angular/flex-layout              8.0.0-beta.26
@angular/material                 8.1.1
@ngtools/webpack                  8.0.3
@schematics/angular               8.3.12
@schematics/update                0.803.12
rxjs                              6.4.0
typescript                        3.4.5
webpack                           4.30.0

ts-md5

"ts-md5": "1.2.6",

Browser

Chrome
Version 77.0.3865.120 (Official Build) (64-bit)

html template

  <form enctype="multipart/form-data" method="post">
    <div>
      <label for="picked">ARFF dataset</label>
      <div>
        <input
          type="file"
          id="picked"
          #picked
          (click)="message = ''"
          (change)="onPicked(picked)"
        />
      </div>
    </div>
  </form>

controller ts

import { Component } from "@angular/core";
import { UploaderService } from "./uploader.service";
import { global } from "../global";
import { ParallelHasher } from "ts-md5/dist/parallel_hasher";
@Component({
  selector: "app-uploader",
  templateUrl: "./uploader.component.html",
  providers: [UploaderService]
})
export class UploaderComponent {
  message: string = "Please upload an .arff file!";
  constructor(private uploaderService: UploaderService) {}
  userID: string = null;
  onPicked(input: HTMLInputElement) {
    const file = input.files[0];
    let hasher = new ParallelHasher("../assets/ts-md5/dist/md5_worker.js");
    hasher.hash(file).then(function(result) {
      console.log("md5 of file is", result);
    });
    if (file) {
      let fileExtension = file.name.split(".").pop();
      // console.log(fileExtension);
      if (fileExtension != "arff" && fileExtension != "ARFF") {
        this.message = "File error! Please provide a valid arff file!";
        console.error("File extension error!");
      } else {
        this.uploaderService.upload(file).subscribe(msg => {
          input.value = null;
          this.message = msg;
          this.userID = global.userID;
        });
      }
    }
  }
}

Error output

parallel_hasher.js:13 Hash worker failure ErrorEvent {isTrusted: true, message: "Uncaught ReferenceError: require is not defined", filename: "http://localhost:4200/assets/ts-md5/dist/md5_worker.js", lineno: 401, colno: 13, …}
ParallelHasher.self._hashWorker.onerror @ parallel_hasher.js:13
wrapFn @ zone-evergreen.js:1191
invokeTask @ zone-evergreen.js:391
onInvokeTask @ core.js:30885
invokeTask @ zone-evergreen.js:390
runTask @ zone-evergreen.js:168
invokeTask @ zone-evergreen.js:465
invokeTask @ zone-evergreen.js:1603
globalZoneAwareCallback @ zone-evergreen.js:1629
error (async)
customScheduleGlobal @ zone-evergreen.js:1742
scheduleTask @ zone-evergreen.js:378
onScheduleTask @ zone-evergreen.js:272
scheduleTask @ zone-evergreen.js:372
scheduleTask @ zone-evergreen.js:211
scheduleEventTask @ zone-evergreen.js:237
(anonymous) @ zone-evergreen.js:1911
desc.set @ zone-evergreen.js:1252
ParallelHasher @ parallel_hasher.js:11
onPicked @ uploader.component.ts:16
eval @ UploaderComponent.html:17
handleEvent @ core.js:34789
callWithDebugContext @ core.js:36407
debugHandleEvent @ core.js:36043
dispatchEvent @ core.js:22533
(anonymous) @ core.js:33721
(anonymous) @ platform-browser.js:1789
invokeTask @ zone-evergreen.js:391
onInvokeTask @ core.js:30885
invokeTask @ zone-evergreen.js:390
runTask @ zone-evergreen.js:168
invokeTask @ zone-evergreen.js:465
invokeTask @ zone-evergreen.js:1603
globalZoneAwareCallback @ zone-evergreen.js:1629
md5_file_hasher.ts:6 Uncaught ReferenceError: require is not defined
    at md5_file_hasher.ts:6

hashString vs hashAsciiString

Hi I am trying to use your library but I am unsure which method (hashString or hashAsciiString) to use.

What is the difference between:

Md5.hashString("foobar")
Md5.hashAsciiString("foobar")

and when to use which?

Thanks in advance!

require is not defined

Since updates few days ago and especially this commit: 996cbd5#diff-2f043c58a6b511acb59702fd73ef287fR401

The following error came back again:

Uncaught ReferenceError: require is not defined
    at md5_worker.js:401
(anonymous) @ md5_worker.js:401

It seems to have been fixed in previous version following discussions here: #7

But the mentioned commit make require() and self._md5 = new md5_1.Md5(); reappear, leading to the error.

Remove Source Maps

The module on NPM includes a reference to md5.js.map.
I use webpack in my project to combine my own code with all modules in a single file. When I load this bundle afterwards in a browser, I get an error that md5.js.map couldn't be loaded (because I don't copy it to the output directory).
I just tried to fork the repo and solve it myself, but unfortunately all dependencies are set to latest and due to the change to TS 2.0 (at least I think this is the reason) the project currently can't be compiled successfully.

@stakach: What versions of your dependencies have you used the last time you successfully compiled the sources?

getting error Cannot find name 'WorkerOptions'.

i am using ts-md5": "^1.2.4" and below is my environment
Angular CLI: 6.2.9
Node: 10.16.0
OS: win32 x64
Angular: 6.1.10
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, platform-server, router

Package Version

@angular-devkit/architect 0.7.5
@angular-devkit/build-angular 0.7.5
@angular-devkit/build-optimizer 0.7.5
@angular-devkit/build-webpack 0.7.5
@angular-devkit/core 0.7.5
@angular-devkit/schematics 0.8.9
@angular/cli 6.2.9
@ngtools/webpack 6.1.5
@schematics/angular 0.8.9
@schematics/update 0.8.9
rxjs 6.5.3
typescript 2.9.2
webpack 4.39.3

while executing the command ng serve i am getting the error as

ERROR in node_modules/ts-md5/dist/parallel_hasher.d.ts(6,52): error TS2304: Cannot find name 'WorkerOptions'.

and when i went to the particular file removed the workerOptions in constructor and it worked but this is not the solution
@stakach @skogsbaer @itsmontoya @johnbendi @qk4

image

Calculate MD5 from file path

We can calculate md5 from blob,

import {ParallelHasher} from 'ts-md5/dist/parallel_hasher';
 
let hasher = new ParallelHasher('/path/to/ts-md5/dist/md5_worker.js');
hasher.hash(fileBlob).then(function(result) {
   console.log('md5 of fileBlob is', result);
});

If we can calculate MD5 from file path as well that will good.

SyntaxError: expected expression, got '<'

while i try to run md5 for a file i get this erreur:

SyntaxError: expected expression, got '<' 

this is my code:

 let hasher = new ParallelHasher('ECHRI-ADMIN-WEB-APP/node_modules/ts-md5/dist             /md5_worker.js');
 hasher.hash(file);

how to solve it ?

in IE9 bug

SCRIPT5009: “Int32Array”未定义
md5.js (390,5)

Should end method return a undefined?

Method end has a specific case when it return undefined.

public end(raw: boolean = false) {
  // ...  
    const matches = dataBitsLen.toString(16).match(/(.*?)(.{0,8})$/);
      if (matches === null) {
        return;
       }
  // ...  
}
``

Maybe this case should raise an exception?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.