Skip to content

Commit

Permalink
feat: support WebCrypto
Browse files Browse the repository at this point in the history
  • Loading branch information
AJ ONeal committed Feb 3, 2023
1 parent 7cf62e6 commit 27d2d0a
Showing 1 changed file with 44 additions and 7 deletions.
51 changes: 44 additions & 7 deletions lib/hdkey.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ var HDKey = ("object" === typeof module && exports) || {};
const BUFFER_BE = false;
const COMPRESSED = true;

let crypto = require("crypto");
//@ts-ignore
let Crypto = window.crypto || require("crypto");
let bs58check = require("bs58check");

let Utils = {};
Expand Down Expand Up @@ -88,24 +89,60 @@ var HDKey = ("object" === typeof module && exports) || {};
};

/** @type {HDHasher} */
Utils.ripemd160sum = async function (buf) {
Utils.ripemd160sum = async function (bytes) {
let RIPEMD160 = require("ripemd160");
return new RIPEMD160().update(buf).digest();
let buf = Buffer.from(bytes);
let hash = new RIPEMD160().update(buf).digest();
return new Uint8Array(hash);
};

/** @type {HDHasher} */
Utils.sha256sum = async function (buf) {
return crypto.createHash("sha256").update(buf).digest();
Utils.sha256sum = async function (bytes) {
if (!Crypto.subtle) {
let sha256 = Crypto.createHash("sha256").update(bytes).digest();
return new Uint8Array(sha256);
}
let arrayBuffer = await Crypto.subtle.digest("SHA-256", bytes);
let hashBytes = new Uint8Array(arrayBuffer);
return hashBytes;
};

/** @type {HDHmac} */
Utils.sha512hmac = async function (entropy, data) {
return crypto.createHmac("sha512", entropy).update(data).digest();
if (!Crypto.subtle) {
let buf = Crypto.createHmac("sha512", entropy).update(data).digest();
return new Uint8Array(buf);
}

/** @type {"raw"|"pkcs8"|"spki"} */
let format = "raw";
let algo = {
name: "HMAC",
hash: "SHA-512",
};
let extractable = false;
/** @type {Array<KeyUsage>} */
let keyUsages = ["sign"];
let hmacKey = await Crypto.subtle.importKey(
format,
entropy,
algo,
extractable,
keyUsages,
);
let sig = await Crypto.subtle.sign("HMAC", hmacKey, data);

return new Uint8Array(sig);
};

/** @type {HDSecureErase} */
Utils.secureErase = function (buf) {
crypto.randomBytes(buf.length).copy(buf);
if (!Crypto.getRandomValues) {
Crypto.randomBytes(buf.length).copy(buf);
return;
}

Crypto.getRandomValues(buf);
};

/** @type {HDUtilSign} */
Expand Down

0 comments on commit 27d2d0a

Please sign in to comment.