Copy pubkey encoding/decoding from index to browser
Some checks failed
buildbot/multibuild_parent Build done.
buildbot/travis_bionic Build done.
Testing / default (push) Failing after 1m32s

This commit is contained in:
Lee Miller 2024-03-01 02:08:04 +02:00
parent 1622be8696
commit 9f253442ef
Signed by: lee.miller
GPG Key ID: 4F97A5EA88F4AB63

View File

@ -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);