Add additional functions:

encodePublic(publicKey), decodePublic(publicKey) used in
encrypt() and decrypt() respectively - to comply with the network.
This commit is contained in:
Lee Miller 2022-12-25 00:20:37 +02:00
parent 8c9d298dc9
commit da810c2546
Signed by: lee.miller
GPG Key ID: 4F97A5EA88F4AB63
2 changed files with 39 additions and 7 deletions

View File

@ -8,9 +8,13 @@
const EC_GROUP_ORDER = Buffer.from('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 'hex');
const ZERO32 = Buffer.alloc(32, 0);
const curve_secp256k1 = 714,
key_length = 32;
var promise = typeof Promise === "undefined" ?
require("es6-promise").Promise :
Promise;
Promise;
const struct = require("python-struct");
var crypto = require("crypto");
// try to use secp256k1, fallback to browser implementation
try {
@ -117,6 +121,33 @@ var getPublic = exports.getPublic = function(privateKey) {
return secp256k1.publicKeyConvert(compressed, false);
};
// to comply with the bitmessage network
function encodePublic(publicKey) {
return Buffer.concat([
struct.pack('!H', curve_secp256k1),
struct.pack('!H', key_length),
publicKey.slice(1, 33),
struct.pack('!H', key_length),
publicKey.slice(33),
]);
};
function decodePublic(publicKey) {
var i = 0;
var curve = struct.unpack('!H', publicKey.slice(i, i + 2))[0];
assert(curve == curve_secp256k1, "Wrong curve!");
i += 2;
var tmplen = struct.unpack('!H', publicKey.slice(i, i + 2))[0];
assert(tmplen == key_length, "Bad key length!");
i += 2;
var publicKeyX = publicKey.slice(i, i + tmplen);
i += tmplen;
tmplen = struct.unpack('!H', publicKey.slice(i, i + 2))[0];
assert(tmplen == key_length, "Bad key length!");
var publicKeyY = publicKey.slice(i, i + tmplen);
return Buffer.concat([Buffer.from("04", "hex"), publicKeyX, publicKeyY]);
};
/**
* Get compressed version of public key.
*/
@ -213,7 +244,7 @@ exports.encrypt = function(publicKeyTo, msg, opts) {
{
ephemPrivateKey = opts.ephemPrivateKey || crypto.randomBytes(32);
}
ephemPublicKey = getPublic(ephemPrivateKey);
ephemPublicKey = encodePublic(getPublic(ephemPrivateKey));
resolve(derive(ephemPrivateKey, publicKeyTo));
}).then(function(Px) {
var hash = sha512(Px);
@ -241,7 +272,7 @@ exports.encrypt = function(publicKeyTo, msg, opts) {
* plaintext on successful decryption and rejects on failure.
*/
exports.decrypt = function(privateKey, opts) {
return derive(privateKey, opts.ephemPublicKey).then(function(Px) {
return derive(privateKey, decodePublic(opts.ephemPublicKey)).then(function(Px) {
assert(privateKey.length === 32, "Bad private key");
assert(isValidPrivateKey(privateKey), "Bad private key");
var hash = sha512(Px);

View File

@ -50,10 +50,11 @@
"mocha": "*"
},
"dependencies": {
"acorn": "7.1.1",
"elliptic": "6.5.4",
"es6-promise": "4.2.8",
"nan": "2.14.0"
"acorn": "7.1.1",
"elliptic": "6.5.4",
"es6-promise": "4.2.8",
"nan": "2.14.0",
"python-struct": "1.1.3"
},
"optionalDependencies": {
"secp256k1": "3.7.1"