From 13286c6fb612493c7a6d4a2cd15e789fafb315b9 Mon Sep 17 00:00:00 2001 From: Dmitri Zagidulin Date: Sun, 9 May 2021 00:20:00 -0400 Subject: [PATCH] Add a react-native section to package.json, split off from browser file. --- lib/MessageDigest-browser.js | 2 +- lib/MessageDigest-reactnative.js | 46 ++++++++++++++++++++++++++++++++ package.json | 9 +++++++ 3 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 lib/MessageDigest-reactnative.js diff --git a/lib/MessageDigest-browser.js b/lib/MessageDigest-browser.js index bfd74de..3bd8301 100644 --- a/lib/MessageDigest-browser.js +++ b/lib/MessageDigest-browser.js @@ -3,7 +3,7 @@ */ 'use strict'; -const crypto = require('isomorphic-webcrypto'); +const crypto = self.crypto || self.msCrypto; module.exports = class MessageDigest { /** diff --git a/lib/MessageDigest-reactnative.js b/lib/MessageDigest-reactnative.js new file mode 100644 index 0000000..3d50b27 --- /dev/null +++ b/lib/MessageDigest-reactnative.js @@ -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; + } +}; diff --git a/package.json b/package.json index b9763a2..5158aba 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "lib/*.js" ], "dependencies": { + "fast-text-encoding": "^1.0.3", "isomorphic-webcrypto": "^2.3.8" }, "devDependencies": { @@ -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 } }