subtle-digest
a simple (callback-based) wrapper around crypto.subtle.digest
Install
$ npm install subtle-digest
Usage
Testing for algorithm support
Before you start wildly trying to hash things, you might want to determine browser support. subtle-digest
provides a handy method for checking both if the browser supports crypto.subtle.digest
, and also if it supports your desired algorithm.
var supports =
Hashing things
Because crypto.subtle.digest
accepts and returns ArrayBuffer
objects, the most basic usage of subtle-digest
is as follows:
var digest =
However, if your application is doing a lot of hashing with a particular algorithm you might find this approach more pleasant:
var digest = var sha1 =
Dealing in strings
Based on my own usage, I suspect a lot of people want hexadecimal string representations of their hashes. I consider that outside of the scope of this module, but it’s pretty easy to achieve:
var digest = var hex =
And if you want to generate a hash of a string, it’s similiarly uncomplicated:
var digest = var hex = var u8a =
Errors
If you attempt to use an unsupported algorithm, you might be forwarded an error from the browser like so:
var digest =
But some browsers, cough Safari cough, might just throw an error and never trigger the callback, so you should probably use subtle-digest/supports
before attempting to hash anything. Having said that, if you’re happy to sacrifice performance for convenience, you could just require subtle-digest/lazy
var digest =
This will always work, regardless of the browser, because it automagically runs subtle-digest/supports
before making any calls to subtle-digest
. The original API is maintained through a bit of queuing and dynamic function invocation.
Page weight
require('subtle-digest')
compression | size |
---|---|
subtle-digest.js | 1.17 kB |
subtle-digest.min.js | 882 B |
subtle-digest.min.js.gz | 475 B |
require('subtle-digest/supports')
compression | size |
---|---|
subtle-digest/supports.js | 1.39 kB |
subtle-digest/supports.min.js | 979 B |
subtle-digest/supports.min.js.gz | 527 B |
require('subtle-digest/lazy')
compression | size |
---|---|
subtle-digest/lazy.js | 2.71 kB |
subtle-digest/lazy.min.js | 1.65 kB |
subtle-digest/lazy.min.js.gz | 768 B |
Running the tests
Until testling comes back (or is replaced by something elegant) you can run the tests yourself in any browser:
$ git clone git@github.com:michaelrhodes/subtle-digest$ cd subtle-digest$ npm install$ npm test