diff --git a/src/ec.js b/src/ec.js index 9f450f8..24d488c 100644 --- a/src/ec.js +++ b/src/ec.js @@ -303,32 +303,28 @@ ECFieldElementFp.prototype.getByteLength = function () { return Math.floor((this.toBigInteger().bitLength() + 7) / 8); }; -ECPointFp.prototype.getEncoded = function (compressed) { - var x = this.getX().toBigInteger(); - var y = this.getY().toBigInteger(); - - // Get value as a 32-byte Buffer - // Fixed length based on a patch by bitaddress.org and Casascius - var enc = integerToBytes(x, 32); +ECPointFp.prototype.getEncoded = function(compressed) { + var x = this.getX().toBigInteger() + var y = this.getY().toBigInteger() + var buffer + // 0x02/0x03 | X if (compressed) { - if (y.isEven()) { - // Compressed even pubkey - // M = 02 || X - enc.unshift(0x02); - } else { - // Compressed uneven pubkey - // M = 03 || X - enc.unshift(0x03); - } + buffer = new Buffer(33) + buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0) + + // 0x04 | X | Y } else { - // Uncompressed pubkey - // M = 04 || X || Y - enc.unshift(0x04); - enc = enc.concat(integerToBytes(y, 32)); + buffer = new Buffer(65) + buffer.writeUInt8(0x04, 0) + + y.toBuffer(32).copy(buffer, 33) } - return enc; -}; + + x.toBuffer(32).copy(buffer, 1) + + return buffer +} ECPointFp.decodeFrom = function (curve, enc) { var type = enc[0]; diff --git a/src/ecpubkey.js b/src/ecpubkey.js index 8bcf984..0c7dafb 100644 --- a/src/ecpubkey.js +++ b/src/ecpubkey.js @@ -48,7 +48,7 @@ ECPubKey.prototype.verify = function(hash, sig) { // Export functions ECPubKey.prototype.toBuffer = function() { - return new Buffer(this.Q.getEncoded(this.compressed)) + return this.Q.getEncoded(this.compressed) } ECPubKey.prototype.toHex = function() { diff --git a/test/ec.js b/test/ec.js index 963bf0e..a547ea1 100644 --- a/test/ec.js +++ b/test/ec.js @@ -35,7 +35,7 @@ describe('ec', function() { curve.fromBigInteger(new BigInteger(f.y)) ) - var encoded = new Buffer(Q.getEncoded(f.compressed)) + var encoded = Q.getEncoded(f.compressed) assert.equal(encoded.toString('hex'), f.hex) }) })