From 9f253442efaa68f460a21ad9a70bb544f2aae6ae Mon Sep 17 00:00:00 2001 From: Lee Miller Date: Fri, 1 Mar 2024 02:08:04 +0200 Subject: [PATCH] Copy pubkey encoding/decoding from index to browser --- browser.js | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/browser.js b/browser.js index c9847df..d545f07 100644 --- a/browser.js +++ b/browser.js @@ -8,9 +8,13 @@ var subtle = browserCrypto.subtle || browserCrypto.webkitSubtle; var nodeCrypto = require('crypto'); -const EC_GROUP_ORDER = Buffer.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); +const EC_GROUP_ORDER = Buffer.from( + 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex'); const ZERO32 = Buffer.alloc(32, 0); +const curve_secp256k1 = 714, + key_length = 32; + function assert(condition, message) { if (!condition) { throw new Error(message || "Assertion failed"); @@ -137,6 +141,29 @@ var getPublic = exports.getPublic = function(privateKey) { return Buffer.from(ec.keyFromPrivate(privateKey).getPublic("arr")); }; +// to comply with the bitmessage network +function encodePublic(publicKey) { + assert(publicKey.length === 65, "Bad public key"); + var buf = Buffer.alloc(70); + buf.writeUInt16BE(curve_secp256k1, 0, true); + buf.writeUInt16BE(key_length, 2, true); + publicKey.copy(buf, 4, 1, 33); + buf.writeUInt16BE(key_length, 36, true); + publicKey.copy(buf, 38, 33, 65); + return buf; +} + +function decodePublic(publicKey) { + assert(publicKey.readUInt16BE(0, true) === curve_secp256k1, "Wrong curve!"); + assert(publicKey.readUInt16BE(2, true) === key_length, "Bad key length!"); + assert(publicKey.readUInt16BE(36, true) === key_length, "Bad key length!"); + var buf = Buffer.alloc(65); + buf[0] = 0x04; + publicKey.copy(buf, 1, 4, 36); + publicKey.copy(buf, 33, 38, 70); + return buf; +} + /** * Get compressed version of public key. */ @@ -217,7 +244,7 @@ exports.encrypt = function(publicKeyTo, msg, opts) { { ephemPrivateKey = opts.ephemPrivateKey || randomBytes(32); } - ephemPublicKey = getPublic(ephemPrivateKey); + ephemPublicKey = encodePublic(getPublic(ephemPrivateKey)); resolve(derive(ephemPrivateKey, publicKeyTo)); }).then(function(Px) { return sha512(Px); @@ -243,7 +270,8 @@ exports.encrypt = function(publicKeyTo, msg, opts) { exports.decrypt = function(privateKey, opts) { // Tmp variable to save context from flat promises; var encryptionKey; - return derive(privateKey, opts.ephemPublicKey).then(function(Px) { + return derive( + privateKey, decodePublic(opts.ephemPublicKey)).then(function(Px) { return sha512(Px); }).then(function(hash) { encryptionKey = hash.slice(0, 32);