@li0ard/dstu 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,11 +20,12 @@ npm i @li0ard/dstu
20
20
 
21
21
  ## Supported algorithms
22
22
 
23
- - Curves and DSA (DSTU 4145-2002, polynomial and optimal normal basis)
23
+ - Curves and ECDSA (DSTU 4145-2002, polynomial and optimal normal basis)
24
24
  - Kalyna cipher (DSTU 7624:2014)
25
25
  - Kupyna hash function (DSTU 7564:2014)
26
26
  - Supports KMAC
27
27
  - Strumok stream cipher (DSTU 8845:2019)
28
+ - ECIES encryption schema over Twisted Edwards curves (DSTU 9041:2020)
28
29
 
29
30
  ## Supported cipher modes
30
31
 
@@ -23,12 +23,11 @@ export const expandPoint = (xBytes, params) => {
23
23
  const rhs = field.mul(x2, xClean);
24
24
  if (a === 1)
25
25
  rhs.ixor(x2);
26
- if (b)
27
- rhs.ixor(b);
28
- const z = field.solve_quad(field.mul(rhs, field.invert(x2)));
26
+ rhs.ixor(b);
27
+ const z = field.solve_quad(field.div(rhs, x2));
29
28
  const traceZ = field.trace(z);
30
29
  if ((traceZ === 0 && bit) || (traceZ === 1 && !bit))
31
- z.setn(0, !z.testn(0));
30
+ field.invBit(z, 0);
32
31
  let y = field.mul(z, xClean);
33
32
  if (onb && converter)
34
33
  y = converter.pbToOnb(y);
@@ -7,12 +7,15 @@ export declare const binaryWeierstrass: (parameters: DSTUParameters) => Readonly
7
7
  LENGTH: number;
8
8
  mod: (f: BN) => BN;
9
9
  mul: (x: BN, v: BN) => BN;
10
+ div: (x: BN, v: BN) => BN;
10
11
  sqr: (x: BN) => BN;
12
+ sqrt: (x: BN) => BN;
11
13
  invert: (f: BN) => BN;
12
14
  solve_quad: (v: BN) => BN;
13
15
  trace: (x: BN) => 0 | 1;
14
16
  traceOnb: (x: BN) => 0 | 1;
15
17
  hashToField: (hash: TArg<Uint8Array>) => BN;
18
+ invBit: (x: BN, i: number) => BN;
16
19
  fromHexStringOrBytes: (v: string | Uint8Array) => BN;
17
20
  toBytes: (x: BN, length?: number) => TRet<Uint8Array>;
18
21
  }>;
@@ -86,29 +89,7 @@ export declare const binaryWeierstrass: (parameters: DSTUParameters) => Readonly
86
89
  };
87
90
  mulWnaf(f: BN): /*elided*/ any;
88
91
  };
89
- expand(xExt: BN): {
90
- _precomp?: {
91
- pos: /*elided*/ any[];
92
- neg: /*elided*/ any[];
93
- };
94
- _double?: /*elided*/ any;
95
- x: BN;
96
- y: BN;
97
- add(p: /*elided*/ any): /*elided*/ any;
98
- mul(f: BN): /*elided*/ any;
99
- negate(): /*elided*/ any;
100
- clone(): /*elided*/ any;
101
- isZero(): boolean;
102
- compress(): BN;
103
- toBytes(isCompressed?: boolean): TRet<Uint8Array>;
104
- double(): /*elided*/ any;
105
- timesPow2(e: number): /*elided*/ any;
106
- precomp(width: number): {
107
- pos: /*elided*/ any[];
108
- neg: /*elided*/ any[];
109
- };
110
- mulWnaf(f: BN): /*elided*/ any;
111
- };
92
+ /** Deserialize point from bytes (compressed/uncompressed) */
112
93
  fromBytes(bytes: TArg<Uint8Array>): {
113
94
  _precomp?: {
114
95
  pos: /*elided*/ any[];
@@ -10,6 +10,7 @@ export const binaryWeierstrass = (parameters) => {
10
10
  const toExternal = (f) => onb ? onb.pbToOnb(f) : f.clone();
11
11
  const order = field.fromHexStringOrBytes(parameters.order);
12
12
  const b = toInternal(field.fromHexStringOrBytes(parameters.b));
13
+ const c = field.sqrt(b);
13
14
  const scalarByteLength = Math.ceil(order.bitLength() / 8), pointByteLength = field.LENGTH * 2;
14
15
  const lengths = Object.freeze({
15
16
  fieldByteLength: field.LENGTH,
@@ -17,6 +18,22 @@ export const binaryWeierstrass = (parameters) => {
17
18
  scalarByteLength,
18
19
  signatureByteLength: scalarByteLength * 2
19
20
  });
21
+ const Madd = (X1, Z1, X2, Z2, x) => {
22
+ const A = field.mul(X1, Z2);
23
+ const B = field.mul(Z1, X2);
24
+ const T = field.mul(A, B);
25
+ const Znew = field.sqr(A.ixor(B));
26
+ const Xnew = field.mul(Znew, x).ixor(T);
27
+ return [Xnew, Znew];
28
+ };
29
+ const Mdouble = (X, Z) => {
30
+ const X2 = field.sqr(X);
31
+ const Z2 = field.sqr(Z);
32
+ const T = field.sqr(field.mul(Z2, c));
33
+ const Znew = field.mul(X2, Z2);
34
+ const Xnew = field.sqr(X2).ixor(T);
35
+ return [Xnew, Znew];
36
+ };
20
37
  // Point operations
21
38
  class Point {
22
39
  x;
@@ -39,11 +56,10 @@ export const binaryWeierstrass = (parameters) => {
39
56
  return this;
40
57
  let lbd, x2;
41
58
  if (x0.cmp(x1) !== 0) {
42
- const tmp = y0.xor(y1), tmp2 = x0.xor(x1);
43
- lbd = field.mul(tmp, field.invert(tmp2));
59
+ lbd = field.div(y0.xor(y1), x0.xor(x1));
44
60
  x2 = field.sqr(lbd);
45
61
  if (parameters.a === 1)
46
- x2.setn(0, !x2.testn(0));
62
+ field.invBit(x2, 0);
47
63
  x2.ixor(lbd).ixor(x0).ixor(x1);
48
64
  }
49
65
  else {
@@ -51,36 +67,53 @@ export const binaryWeierstrass = (parameters) => {
51
67
  return pz;
52
68
  if (x1.isZero())
53
69
  return pz;
54
- lbd = x1.xor(field.mul(p.y, field.invert(p.x)));
70
+ lbd = x1.xor(field.div(p.y, p.x));
55
71
  x2 = field.sqr(lbd);
56
72
  if (parameters.a === 1)
57
- x2.setn(0, !x2.testn(0));
73
+ field.invBit(x2, 0);
58
74
  x2.ixor(lbd);
59
75
  }
60
- const y2 = field.mul(lbd, x1.xor(x2)).xor(x2).xor(y1);
76
+ const y2 = field.mul(lbd, x1.xor(x2)).ixor(x2).ixor(y1);
61
77
  pz.x = x2;
62
78
  pz.y = y2;
63
79
  return pz;
64
80
  }
65
81
  mul(f) {
66
- let pz = Point.ZERO.clone(), p = this.clone();
67
- for (let j = f.bitLength() - 1; j >= 0; j--) {
68
- if (f.testn(j)) {
69
- pz = pz.add(p);
70
- p = p.add(p);
82
+ if (f.isZero() || this.x.isZero())
83
+ return Point.ZERO.clone();
84
+ let X1 = this.x.clone(), Z1 = new BN(1);
85
+ const xSqr = field.sqr(this.x);
86
+ let X2 = field.sqr(xSqr).ixor(b), Z2 = xSqr.clone();
87
+ for (let i = f.bitLength() - 2; i >= 0; i--) {
88
+ if (f.testn(i)) {
89
+ [X1, Z1] = Madd(X1, Z1, X2, Z2, this.x);
90
+ [X2, Z2] = Mdouble(X2, Z2);
71
91
  }
72
92
  else {
73
- p = pz.add(p);
74
- pz = pz.add(pz);
93
+ [X2, Z2] = Madd(X2, Z2, X1, Z1, this.x);
94
+ [X1, Z1] = Mdouble(X1, Z1);
75
95
  }
76
96
  }
77
- return pz;
97
+ // Convert projective coords to affine
98
+ if (Z1.isZero())
99
+ return Point.ZERO.clone();
100
+ if (Z2.isZero())
101
+ return this.negate();
102
+ const A = field.mul(this.x, Z1).ixor(X1);
103
+ const B = field.mul(this.x, Z2).ixor(X2);
104
+ const Z1Z2 = field.mul(Z1, Z2);
105
+ const Z1Z2x = field.mul(Z1Z2, this.x);
106
+ const D = field.invert(field.mul(Z1Z2x, Z1));
107
+ const N = field.mul(A, B).ixor(field.mul(Z1Z2, xSqr.ixor(this.y)));
108
+ const Xk = field.mul(X1, field.mul(Z1Z2x, D));
109
+ const Yk = field.mul(field.mul(A, N), D).ixor(this.y);
110
+ return new Point(Xk, Yk);
78
111
  }
79
- negate() { return new Point(this.x, this.x.xor(this.y)); }
80
- clone() { return new Point(this.x, this.y); }
112
+ negate() { return new Point(this.x.clone(), this.x.xor(this.y)); }
113
+ clone() { return new Point(this.x.clone(), this.y.clone()); }
81
114
  isZero() { return this.x.isZero() && this.y.isZero(); }
82
115
  compress() {
83
- const tmp = field.mul(field.invert(this.x), this.y);
116
+ const tmp = field.div(this.y, this.x);
84
117
  return toExternal(this.x).setn(0, field.trace(tmp));
85
118
  }
86
119
  toBytes(isCompressed = false) {
@@ -145,37 +178,37 @@ export const binaryWeierstrass = (parameters) => {
145
178
  }
146
179
  return R;
147
180
  }
148
- static expand(xExt) {
149
- const bit = xExt.testn(0);
150
- const xCleanExt = xExt.clone();
151
- xCleanExt.setn(0, 0);
152
- const traceX = onb ? field.traceOnb(xCleanExt) : field.trace(xCleanExt);
153
- if ((traceX === 1 && parameters.a === 0) || (traceX === 0 && parameters.a === 1))
154
- xCleanExt.setn(0, 1);
155
- const xClean = toInternal(xCleanExt);
156
- const x2 = field.sqr(xClean);
157
- const rhs = field.mul(x2, xClean);
158
- if (parameters.a === 1)
159
- rhs.ixor(x2);
160
- if (b)
161
- rhs.ixor(b);
162
- const z = field.solve_quad(field.mul(rhs, field.invert(x2)));
163
- const traceZ = field.trace(z);
164
- if ((traceZ === 0 && bit) || (traceZ === 1 && !bit))
165
- z.setn(0, !z.testn(0));
166
- return new Point(xClean, field.mul(z, xClean));
167
- }
181
+ /** Deserialize point from bytes (compressed/uncompressed) */
168
182
  static fromBytes(bytes) {
183
+ // Uncompressed
169
184
  if (bytes.length == pointByteLength)
170
185
  return new Point(toInternal(field.fromHexStringOrBytes(bytes.subarray(0, field.LENGTH))), toInternal(field.fromHexStringOrBytes(bytes.subarray(field.LENGTH))));
171
- else if (bytes.length == field.LENGTH)
172
- return Point.expand(field.fromHexStringOrBytes(bytes));
186
+ // Compressed (need to recover y-coord)
187
+ else if (bytes.length == field.LENGTH) {
188
+ const xExt = field.fromHexStringOrBytes(bytes);
189
+ const bit = xExt.testn(0);
190
+ xExt.setn(0, 0);
191
+ const traceX = onb ? field.traceOnb(xExt) : field.trace(xExt);
192
+ if ((traceX === 1 && parameters.a === 0) || (traceX === 0 && parameters.a === 1))
193
+ xExt.setn(0, 1);
194
+ const x = toInternal(xExt);
195
+ const x2 = field.sqr(x);
196
+ const rhs = field.mul(x2, x);
197
+ if (parameters.a === 1)
198
+ rhs.ixor(x2);
199
+ rhs.ixor(b);
200
+ const z = field.solve_quad(field.div(rhs, x2));
201
+ const traceZ = field.trace(z);
202
+ if ((traceZ === 0 && bit) || (traceZ === 1 && !bit))
203
+ field.invBit(z, 0);
204
+ return new Point(x, field.mul(z, x));
205
+ }
173
206
  else
174
207
  throw new Error(`Invalid bytes length. Must be ${pointByteLength} for uncompressed and ${field.LENGTH} for compressed`);
175
208
  }
176
209
  }
177
210
  // Precompute
178
- Point.BASE.mulWnaf(new BN(3));
211
+ Point.BASE.precomp(4);
179
212
  return Object.freeze({
180
213
  Field: field, Point,
181
214
  ORDER: order,
@@ -8,12 +8,15 @@ export declare const createField: (m: number, ks: number[]) => Readonly<{
8
8
  LENGTH: number;
9
9
  mod: (f: BN) => BN;
10
10
  mul: (x: BN, v: BN) => BN;
11
+ div: (x: BN, v: BN) => BN;
11
12
  sqr: (x: BN) => BN;
13
+ sqrt: (x: BN) => BN;
12
14
  invert: (f: BN) => BN;
13
15
  solve_quad: (v: BN) => BN;
14
16
  trace: (x: BN) => 0 | 1;
15
17
  traceOnb: (x: BN) => 0 | 1;
16
18
  hashToField: (hash: TArg<Uint8Array>) => BN;
19
+ invBit: (x: BN, i: number) => BN;
17
20
  fromHexStringOrBytes: (v: string | Uint8Array) => BN;
18
21
  toBytes: (x: BN, length?: number) => TRet<Uint8Array>;
19
22
  }>;
@@ -53,21 +53,21 @@ const le2BN = (arr) => {
53
53
  }
54
54
  return new BN(bytes, "le");
55
55
  };
56
- const xorShiftedWordInto = (arr, val, shift) => {
56
+ const xorShiftedWordInto = (dst, val, shift) => {
57
57
  if (val === 0 || shift < 0)
58
58
  return;
59
59
  const wordShift = shift >>> 5, bitShift = shift & 31;
60
60
  if (bitShift === 0) {
61
- if (wordShift < arr.length)
62
- arr[wordShift] ^= (val >>> 0);
61
+ if (wordShift < dst.length)
62
+ dst[wordShift] ^= (val >>> 0);
63
63
  }
64
64
  else {
65
65
  const lo = (val << bitShift) >>> 0;
66
66
  const hi = (val >>> (WORD_BITS - bitShift)) >>> 0;
67
- if (wordShift < arr.length)
68
- arr[wordShift] ^= lo;
69
- if (wordShift + 1 < arr.length)
70
- arr[wordShift + 1] ^= hi;
67
+ if (wordShift < dst.length)
68
+ dst[wordShift] ^= lo;
69
+ if (wordShift + 1 < dst.length)
70
+ dst[wordShift + 1] ^= hi;
71
71
  }
72
72
  };
73
73
  /** Compute curve modulo */
@@ -83,12 +83,12 @@ export const computeMod = (m, ks) => {
83
83
  export const createField = (m, ks) => {
84
84
  const modulo = computeMod(m, ks), wordsPerElement = Math.ceil(m / WORD_BITS), wordsForProduct = 2 * wordsPerElement, vl = modulo.bitLength();
85
85
  const bMod = (f) => {
86
+ // `f` will be mutated
86
87
  if (f.bitLength() <= m)
87
88
  return f;
88
- const bag = f;
89
- while (bag.bitLength() > m)
90
- bag.ixor(modulo.ushln(bag.bitLength() - vl));
91
- return bag;
89
+ while (f.bitLength() > m)
90
+ f.ixor(modulo.ushln(f.bitLength() - vl));
91
+ return f;
92
92
  };
93
93
  const mod = (f) => {
94
94
  if (f.bitLength() <= m)
@@ -127,6 +127,7 @@ export const createField = (m, ks) => {
127
127
  }
128
128
  return mod(acc);
129
129
  };
130
+ const div = (x, v) => mul(x, invert(v));
130
131
  const sqr = (x) => {
131
132
  const bytes = x.toArray();
132
133
  const out = new Uint8Array(bytes.length * 2);
@@ -138,6 +139,13 @@ export const createField = (m, ks) => {
138
139
  return mod(new BN(out));
139
140
  };
140
141
  const testBit = (x, i) => x.testn(i) ? 1 : 0;
142
+ const invBit = (x, i) => x.setn(i, !x.testn(i));
143
+ const sqrt = (x) => {
144
+ let r = mod(x);
145
+ for (let i = 0; i < m - 1; i++)
146
+ r = sqr(r);
147
+ return r;
148
+ };
141
149
  const trace = (x) => {
142
150
  let t = x;
143
151
  for (let i = 1; i < m; i++)
@@ -189,8 +197,8 @@ export const createField = (m, ks) => {
189
197
  const toBytes = (x, length) => new Uint8Array(x.toArray("be", length));
190
198
  return Object.freeze({
191
199
  MODULO: modulo, LENGTH: Math.ceil(m / 8),
192
- mod, mul, sqr, invert, solve_quad,
193
- trace, traceOnb, hashToField,
200
+ mod, mul, div, sqr, sqrt, invert,
201
+ solve_quad, trace, traceOnb, hashToField, invBit,
194
202
  fromHexStringOrBytes, toBytes
195
203
  });
196
204
  };
@@ -20,10 +20,10 @@ export const init_onb_parameters = (parameters) => {
20
20
  const compress_mulp = new BN(hexToBytes(onb.matrix), "le");
21
21
  decompress_matrix(compress_mulp, mulp);
22
22
  const root1 = new BN(hexToBytes(onb.root1), "le"), root2 = new BN(hexToBytes(onb.root2), "le");
23
- const multiplyOnb = (x, y) => {
23
+ const multiplyOnb = (x) => {
24
24
  const r = new BN(0);
25
25
  const xb = (pos) => (x.testn(pos % m) ? 1 : 0);
26
- const yb = (pos) => (y.testn(pos % m) ? 1 : 0);
26
+ const yb = (pos) => (root2.testn(pos % m) ? 1 : 0);
27
27
  for (let j = 0; j < m; j++) {
28
28
  let bit = 0;
29
29
  for (let i = 0; i < m - 1; i++) {
@@ -47,13 +47,13 @@ export const init_onb_parameters = (parameters) => {
47
47
  };
48
48
  const toPb = new Array(m);
49
49
  toPb[0] = root1.clone();
50
- const { mul } = createField(m, ks);
50
+ const { sqr } = createField(m, ks);
51
51
  for (let i = 1; i < m; i++)
52
- toPb[i] = mul(toPb[i - 1], toPb[i - 1]);
52
+ toPb[i] = sqr(toPb[i - 1]);
53
53
  const _toOnb = new Array(m);
54
- _toOnb[0] = new BN(1).shln(m).subn(1);
54
+ _toOnb[0] = new BN(1).ishln(m).isubn(1);
55
55
  for (let i = 1; i < m; i++)
56
- _toOnb[i] = multiplyOnb(_toOnb[i - 1], root2);
56
+ _toOnb[i] = multiplyOnb(_toOnb[i - 1]);
57
57
  const toOnb = _toOnb.map(reverseBits);
58
58
  return Object.freeze({
59
59
  onbToPb: (x) => {
@@ -4,7 +4,7 @@ import BN from "bn.js";
4
4
  const DEFAULT_CUTOFFS = [13, 41, 121, 337, 897, 2305];
5
5
  export const bitLength = (n) => n === 0 ? 0 : 32 - Math.clz32(n);
6
6
  const compactNaf = (k) => {
7
- if (k.bitLength() >= 1 << 16)
7
+ if (k.bitLength() >= (1 << 16))
8
8
  throw new Error("'k' must have bitlength < 2^16");
9
9
  if (k.isZero())
10
10
  return new Int32Array(0);
package/dstu4145/index.js CHANGED
@@ -6,7 +6,7 @@ import BN from "bn.js";
6
6
  export const dstu4145 = (parameters) => {
7
7
  const curve = binaryWeierstrass(parameters);
8
8
  const { Field, Point, MASK, lengths } = curve;
9
- const getPublicKey = (secretKey, isCompressed = false) => Point.BASE.mul(Field.fromHexStringOrBytes(secretKey)).negate().toBytes(isCompressed);
9
+ const getPublicKey = (secretKey, isCompressed = false) => Point.BASE.mulWnaf(Field.fromHexStringOrBytes(secretKey)).negate().toBytes(isCompressed);
10
10
  const randomPrivateKey = () => Field.toBytes(new BN(randomBytes(lengths.scalarByteLength)).imaskn(MASK), lengths.scalarByteLength);
11
11
  const computePresign = (rand) => {
12
12
  const e = (rand
@@ -16,7 +16,7 @@ export const dstu4145 = (parameters) => {
16
16
  throw new Error("Invalid custom rand for presign (rand = 0)");
17
17
  if (e.isZero())
18
18
  return computePresign(rand);
19
- const Fe = Point.BASE.mul(e).x;
19
+ const Fe = Point.BASE.mulWnaf(e).x;
20
20
  if (Fe.isZero())
21
21
  return computePresign(rand);
22
22
  return { Fe, e };
@@ -45,7 +45,7 @@ export const dstu4145 = (parameters) => {
45
45
  if (s.isZero() || s.gte(curve.ORDER) || r.isZero() || r.gte(curve.ORDER))
46
46
  return false;
47
47
  const h = prepareHash(digest);
48
- const R = Point.BASE.mulWnaf(s).add(Q.mulWnaf(r));
48
+ const R = Point.BASE.mulWnaf(s).add(Q.mul(r));
49
49
  const y = curve.toExternalField(Field.mul(h, R.x)).imaskn(MASK);
50
50
  return y.eq(r);
51
51
  };