Skip to content

Commit

Permalink
Add a react-native section to package.json, split off from browser file.
Browse files Browse the repository at this point in the history
  • Loading branch information
dmitrizagidulin committed May 9, 2021
1 parent 00f496a commit 13286c6
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/MessageDigest-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*/
'use strict';

const crypto = require('isomorphic-webcrypto');
const crypto = self.crypto || self.msCrypto;

module.exports = class MessageDigest {
/**
Expand Down
46 changes: 46 additions & 0 deletions lib/MessageDigest-reactnative.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved.
*/
'use strict';

const crypto = require('isomorphic-webcrypto');
require('fast-text-encoding');

module.exports = class MessageDigest {
/**
* Creates a new MessageDigest.
*
* @param algorithm the algorithm to use.
*/
constructor(algorithm) {
// check if crypto.subtle is available
// check is here rather than top-level to only fail if class is used
if(!(crypto && crypto.subtle)) {
throw new Error('crypto.subtle not found.');
}
if(algorithm === 'sha256') {
this.algorithm = {name: 'SHA-256'};
} else if(algorithm === 'sha1') {
this.algorithm = {name: 'SHA-1'};
} else {
throw new Error(`Unsupported algorithm "${algorithm}".`);
}
this._content = '';
}

update(msg) {
this._content += msg;
}

async digest() {
const data = new TextEncoder().encode(this._content);
const buffer = new Uint8Array(
await crypto.subtle.digest(this.algorithm, data));
// return digest in hex
let hex = '';
for(let i = 0; i < buffer.length; ++i) {
hex += buffer[i].toString(16).padStart(2, '0');
}
return hex;
}
};
9 changes: 9 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"lib/*.js"
],
"dependencies": {
"fast-text-encoding": "^1.0.3",
"isomorphic-webcrypto": "^2.3.8"
},
"devDependencies": {
Expand Down Expand Up @@ -62,6 +63,14 @@
},
"browser": {
"./lib/MessageDigest.js": "./lib/MessageDigest-browser.js",
"./lib/MessageDigest-reactnative.js": false,
"fast-text-encoding": false,
"isomorphic-webcrypto": false,
"rdf-canonize-native": false
},
"react-native": {
"./lib/MessageDigest.js": "./lib/MessageDigest-reactnative.js",
"./lib/MessageDigest-browser.js": false,
"rdf-canonize-native": false
}
}

0 comments on commit 13286c6

Please sign in to comment.