Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

der: support negative integers #114

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/asn1/decoders/der.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ DERNode.prototype._decodeBool = function decodeBool(buffer) {
DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
// Bigint, return as it is (assume big endian)
const raw = buffer.raw();
let res = new bignum(raw);
let res = new bignum(raw).fromTwos(raw.length * 8);

if (values)
res = values[res.toString(10)] || res;
Expand Down
49 changes: 15 additions & 34 deletions lib/asn1/encoders/der.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const inherits = require('inherits');
const BN = require('bn.js');
const Buffer = require('buffer').Buffer;
const Node = require('../base/node');

Expand Down Expand Up @@ -194,46 +195,26 @@ DERNode.prototype._encodeInt = function encodeInt(num, values) {
}

// Bignum, assume big endian
if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
const numArray = num.toArray();
if (!num.sign && numArray[0] & 0x80) {
numArray.unshift(0);
if (!Buffer.isBuffer(num)) {
if (!BN.isBN(num)) {
num = new BN(num);
}
const numArray = num.toTwos(num.byteLength() * 8).toArray();
if (num.isNeg() !== Boolean(numArray[0] & 0x80)) {
numArray.unshift(num.isNeg() ? 0xff : 0);
}
num = new Buffer(numArray);
}

if (Buffer.isBuffer(num)) {
let size = num.length;
if (num.length === 0)
size++;

const out = new Buffer(size);
num.copy(out);
if (num.length === 0)
out[0] = 0;
return this._createEncoderBuffer(out);
}

if (num < 0x80)
return this._createEncoderBuffer(num);

if (num < 0x100)
return this._createEncoderBuffer([0, num]);

let size = 1;
for (let i = num; i >= 0x100; i >>= 8)
let size = num.length;
if (num.length === 0)
size++;

const out = new Array(size);
for (let i = out.length - 1; i >= 0; i--) {
out[i] = num & 0xff;
num >>= 8;
}
if(out[0] & 0x80) {
out.unshift(0);
}

return this._createEncoderBuffer(new Buffer(out));
const out = new Buffer(size);
num.copy(out);
if (num.length === 0)
out[0] = 0;
return this._createEncoderBuffer(out);
};

DERNode.prototype._encodeBool = function encodeBool(value) {
Expand Down