@li0ard/dstu 0.1.9 → 0.2.0

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
@@ -35,7 +35,7 @@ npm i @li0ard/dstu
35
35
  ## Supported cipher modes
36
36
 
37
37
  - Cipher Block Chaining mode (CBC)
38
- - Counter with CBC-MAC (CCM) mode
38
+ - Counter with CBC-MAC mode (CCM)
39
39
  - Cipher Feedback mode (CFB)
40
40
  - Counter mode (CTR)
41
41
  - Electronic Codebook mode (ECB)
@@ -43,6 +43,7 @@ export declare const binaryWeierstrass: (parameters: DSTUParameters) => Readonly
43
43
  neg: /*elided*/ any[];
44
44
  };
45
45
  mulWnaf(f: BN): /*elided*/ any;
46
+ mulAdd(k: BN, Q: /*elided*/ any, l: BN): /*elided*/ any;
46
47
  };
47
48
  BASE: {
48
49
  _precomp?: {
@@ -67,6 +68,7 @@ export declare const binaryWeierstrass: (parameters: DSTUParameters) => Readonly
67
68
  neg: /*elided*/ any[];
68
69
  };
69
70
  mulWnaf(f: BN): /*elided*/ any;
71
+ mulAdd(k: BN, Q: /*elided*/ any, l: BN): /*elided*/ any;
70
72
  };
71
73
  ZERO: {
72
74
  _precomp?: {
@@ -91,6 +93,7 @@ export declare const binaryWeierstrass: (parameters: DSTUParameters) => Readonly
91
93
  neg: /*elided*/ any[];
92
94
  };
93
95
  mulWnaf(f: BN): /*elided*/ any;
96
+ mulAdd(k: BN, Q: /*elided*/ any, l: BN): /*elided*/ any;
94
97
  };
95
98
  /** Deserialize point from bytes (compressed/uncompressed) */
96
99
  fromBytes(bytes: TArg<Uint8Array>): {
@@ -116,6 +119,7 @@ export declare const binaryWeierstrass: (parameters: DSTUParameters) => Readonly
116
119
  neg: /*elided*/ any[];
117
120
  };
118
121
  mulWnaf(f: BN): /*elided*/ any;
122
+ mulAdd(k: BN, Q: /*elided*/ any, l: BN): /*elided*/ any;
119
123
  };
120
124
  };
121
125
  ORDER: BN;
@@ -195,6 +195,25 @@ export const binaryWeierstrass = (parameters) => {
195
195
  }
196
196
  return R;
197
197
  }
198
+ mulAdd(k, Q, l) {
199
+ const m = Math.max(k.bitLength(), l.bitLength()), Z = this.add(Q);
200
+ let R = Point.ZERO.clone();
201
+ for (let i = m - 1; i >= 0; --i) {
202
+ R = R.double();
203
+ if (k.testn(i)) {
204
+ if (l.testn(i)) {
205
+ R = R.add(Z);
206
+ continue;
207
+ }
208
+ R = R.add(this);
209
+ continue;
210
+ }
211
+ if (!l.testn(i))
212
+ continue;
213
+ R = R.add(Q);
214
+ }
215
+ return R;
216
+ }
198
217
  /** Deserialize point from bytes (compressed/uncompressed) */
199
218
  static fromBytes(bytes) {
200
219
  // Uncompressed
package/dstu4145/ecies.js CHANGED
@@ -1,4 +1,4 @@
1
- import { randomBytes } from "@noble/hashes/utils.js";
1
+ import { abytes, randomBytes } from "@noble/hashes/utils.js";
2
2
  import { Dstu9311, gost3431195 } from "../dstu9311/index.js";
3
3
  import { Kalyna256 } from "../kalyna/index.js";
4
4
  import { keyWrap } from "../keywrap.js";
@@ -25,6 +25,9 @@ export const dstu4145Encrypter = (curve, hash, withCofactor = true, useDstu9311
25
25
  * @param plaintext - Message to encrypt.
26
26
  */
27
27
  encrypt: (secretKeyA, publicKeyB, plaintext) => {
28
+ abytes(secretKeyA, undefined, "secretKeyA");
29
+ abytes(publicKeyB, undefined, "publicKeyB");
30
+ abytes(plaintext, undefined, "plaintext");
28
31
  const cek = randomBytes(32), ukm = randomBytes(64), iv = randomBytes(macLength);
29
32
  const sharedKey = getSharedSecret(curve.getSharedSecret(secretKeyA, publicKeyB, withCofactor), ukm);
30
33
  const wcek = keyWrap(sharedKey, useDstu9311).wrap(cek, iv);
@@ -38,6 +41,13 @@ export const dstu4145Encrypter = (curve, hash, withCofactor = true, useDstu9311
38
41
  * @param encryptedMessage - Encrypted message object.
39
42
  */
40
43
  decrypt: (secretKeyB, publicKeyA, encryptedMessage) => {
44
+ abytes(secretKeyB, undefined, "secretKeyB");
45
+ abytes(publicKeyA, undefined, "publicKeyA");
46
+ abytes(encryptedMessage.data, undefined, "encryptedMessage.data");
47
+ abytes(encryptedMessage.iv, undefined, "encryptedMessage.iv");
48
+ abytes(encryptedMessage.wcek, undefined, "encryptedMessage.wcek");
49
+ if (encryptedMessage.ukm)
50
+ abytes(encryptedMessage.ukm, undefined, "encryptedMessage.ukm");
41
51
  const sharedKey = getSharedSecret(curve.getSharedSecret(secretKeyB, publicKeyA, withCofactor), encryptedMessage.ukm);
42
52
  const cek = keyWrap(sharedKey, useDstu9311).unwrap(encryptedMessage.wcek);
43
53
  return cfb(new Cipher(cek), encryptedMessage.iv).decrypt(encryptedMessage.data);
package/dstu4145/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { concatBytes, randomBytes } from "@noble/hashes/utils.js";
1
+ import { abool, abytes, concatBytes, randomBytes } from "@noble/hashes/utils.js";
2
2
  import { DSTU_163, DSTU_167, DSTU_173, DSTU_179, DSTU_191, DSTU_233, DSTU_257, DSTU_307, DSTU_367, DSTU_431 } from "./const.js";
3
3
  import { binaryWeierstrass } from "./ec/index.js";
4
4
  import BN from "bn.js";
@@ -7,7 +7,7 @@ import { reverseBytes } from "../utils.js";
7
7
  export const dstu4145 = (parameters) => {
8
8
  const curve = binaryWeierstrass(parameters);
9
9
  const { Field, Point, MASK, lengths } = curve;
10
- const getPublicKey = (secretKey, isCompressed = true) => Point.BASE.mul(Field.fromHexStringOrBytes(secretKey)).negate().toBytes(isCompressed);
10
+ const getPublicKey = (secretKey, isCompressed = true) => Point.BASE.mul(Field.fromHexStringOrBytes(abytes(secretKey, undefined, "secretKey"))).negate().toBytes(abool(isCompressed, "isCompressed"));
11
11
  /** Computes presign (ephermeral keypair) */
12
12
  const computePresign = (rand) => {
13
13
  const e = new BN(rand ?? randomBytes(lengths.scalarByteLength)).imaskn(MASK);
@@ -28,6 +28,10 @@ export const dstu4145 = (parameters) => {
28
28
  return h;
29
29
  };
30
30
  const sign = (secretKey, digest, rand) => {
31
+ abytes(secretKey, undefined, "secretKey");
32
+ abytes(digest, undefined, "digest");
33
+ if (rand)
34
+ abytes(rand, undefined, "rand");
31
35
  const d = new BN(secretKey), h = prepareHash(digest), { Fe, e } = computePresign(rand);
32
36
  if (d.isZero() || d.gte(curve.ORDER))
33
37
  throw new Error("Invalid private key, must be in range 1 < key < order");
@@ -40,18 +44,22 @@ export const dstu4145 = (parameters) => {
40
44
  return concatBytes(Field.toBytes(s, lengths.scalarByteLength), Field.toBytes(r, lengths.scalarByteLength));
41
45
  };
42
46
  const verify = (publicKey, digest, signature) => {
43
- if (signature.length != lengths.signatureByteLength)
44
- throw new Error("Invalid signature length");
47
+ abytes(publicKey, undefined, "publicKey");
48
+ abytes(digest, undefined, "digest");
49
+ abytes(signature, lengths.signatureByteLength, "signature");
45
50
  const Q = Point.fromBytes(publicKey);
46
51
  const s = Field.fromHexStringOrBytes(signature.subarray(0, lengths.scalarByteLength)), r = Field.fromHexStringOrBytes(signature.subarray(lengths.scalarByteLength));
47
52
  if (s.isZero() || s.gte(curve.ORDER) || r.isZero() || r.gte(curve.ORDER))
48
53
  return false;
49
54
  const h = prepareHash(digest);
50
- const R = Point.BASE.mulWnaf(s).add(Q.mul(r));
55
+ const R = Point.BASE.mulAdd(s, Q, r);
51
56
  const y = curve.toExternalField(Field.mul(h, R.x)).imaskn(MASK);
52
57
  return y.eq(r);
53
58
  };
54
59
  const getSharedSecret = (secretKeyA, publicKeyB, withCofactor = true) => {
60
+ abytes(secretKeyA, undefined, "secretKeyA");
61
+ abytes(publicKeyB, undefined, "publicKeyB");
62
+ abool(withCofactor, "withCofactor");
55
63
  const d = new BN(secretKeyA), Q = Point.fromBytes(publicKeyB);
56
64
  if (d.isZero() || d.gte(curve.ORDER))
57
65
  throw new Error("Invalid private key, must be in range 1 < key < order");
@@ -63,6 +71,7 @@ export const dstu4145 = (parameters) => {
63
71
  return Field.toBytes(curve.toExternalField(R.x), lengths.fieldByteLength);
64
72
  };
65
73
  const keygen = (isCompressed = true) => {
74
+ abool(isCompressed, "isCompressed");
66
75
  const secretKey = Field.toBytes(new BN(randomBytes(lengths.scalarByteLength)).imaskn(MASK), lengths.scalarByteLength);
67
76
  const publicKey = getPublicKey(secretKey, isCompressed);
68
77
  return { secretKey, publicKey };
package/dstu9041/curve.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Field, mod } from "@noble/curves/abstract/modular.js";
2
- import { concatBytes, bitGet, bitLen, bytesToNumberBE, randomBytes } from "@noble/curves/utils.js";
2
+ import { concatBytes, bitGet, bitLen, bytesToNumberBE, randomBytes, abytes } from "@noble/curves/utils.js";
3
3
  export const dstu9041Curve = (parameters) => {
4
4
  if (parameters.a != 2n)
5
5
  throw new Error("Unsuppored `a` parameter, must be 2");
@@ -105,7 +105,7 @@ export const dstu9041Curve = (parameters) => {
105
105
  return candidate;
106
106
  }
107
107
  }
108
- const getPublicKey = (secretKey) => Point.BASE.multiply(bytesToNumberBE(secretKey)).toBytes();
108
+ const getPublicKey = (secretKey) => Point.BASE.multiply(bytesToNumberBE(abytes(secretKey, undefined, "secretKey"))).toBytes();
109
109
  const keygen = () => {
110
110
  const secretKey = randomBytes(Fp.BYTES);
111
111
  const publicKey = getPublicKey(secretKey);
package/dstu9041/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { randomBytes, bytesToNumberBE, concatBytes, equalBytes, numberToBytesBE } from "@noble/curves/utils.js";
1
+ import { randomBytes, bytesToNumberBE, concatBytes, equalBytes, numberToBytesBE, abytes } from "@noble/curves/utils.js";
2
2
  import { kupyna256 } from "../kupyna/index.js";
3
3
  import { curve256, curve512, dstu9041Curve } from "./curve.js";
4
4
  import { kw } from "../modes/kw.js";
@@ -33,6 +33,7 @@ const dstu9041 = (length) => {
33
33
  return paddedMessage;
34
34
  };
35
35
  const buildStruct = (message) => {
36
+ abytes(message);
36
37
  const paddedMessage = padMessage(message);
37
38
  const messageLength = numberToBytesBE(message.length * 8, 2);
38
39
  const digest = kupyna256(concatBytes(messageLength, paddedMessage)).subarray(-HASH_LENGTH_BYTES);
@@ -44,8 +45,7 @@ const dstu9041 = (length) => {
44
45
  return struct;
45
46
  };
46
47
  const parseStruct = (struct) => {
47
- if (struct.length != STRUCT_BYTES)
48
- throw new Error("Invalid ciphertext");
48
+ abytes(struct, STRUCT_BYTES, "struct");
49
49
  if (struct[0] != ID_KUPYNA256)
50
50
  throw new Error("Invalid hash ID");
51
51
  const embeddedHash = struct.subarray(1, HASH_LENGTH_BYTES + 1);
@@ -73,6 +73,10 @@ const dstu9041 = (length) => {
73
73
  getPublicKey: curve.getPublicKey,
74
74
  keygen: curve.keygen,
75
75
  encrypt: (plaintext, publicKey, rand) => {
76
+ abytes(plaintext, undefined, "plaintext");
77
+ abytes(publicKey, undefined, "publicKey");
78
+ if (rand)
79
+ abytes(rand);
76
80
  const struct = buildStruct(plaintext);
77
81
  const e = Fn.create(bytesToNumberBE(rand ?? randomBytes(STRUCT_BYTES)));
78
82
  const r = Fp.toBytes(Point.BASE.multiply(e).x);
@@ -83,8 +87,8 @@ const dstu9041 = (length) => {
83
87
  return concatBytes(r, ciphertext);
84
88
  },
85
89
  decrypt: (ciphertext, privateKey) => {
86
- if (ciphertext.length != length / 2)
87
- throw new Error("Invalid ciphertext length");
90
+ abytes(ciphertext, length / 2, "ciphertext");
91
+ abytes(privateKey, undefined, "privateKey");
88
92
  const r = bytesToNumberBE(ciphertext.subarray(0, STRUCT_BYTES));
89
93
  if (!Fp.isValidNot0(r))
90
94
  throw new Error("Invalid ciphertext");
@@ -1,41 +1,75 @@
1
1
  import { type Hash, type TArg, type TRet } from "@noble/hashes/utils.js";
2
2
  import { _HMAC } from "@noble/hashes/hmac.js";
3
- /** GOST 34.311-95 hash function */
4
- export declare class Gost3431195 implements Hash<Gost3431195> {
3
+ /** Internal GOST 34.311-95 hash class */
4
+ export declare class _Gost3431195 implements Hash<_Gost3431195> {
5
5
  private sbox;
6
6
  readonly blockLen = 32;
7
7
  readonly outputLen = 32;
8
8
  readonly canXOF = false;
9
9
  private buffer;
10
- /** GOST 34.311-95 hash function */
10
+ private pos;
11
+ private h;
12
+ private len;
13
+ private checksum;
14
+ /** Internal GOST 34.311-95 hash class */
11
15
  constructor(sbox?: TArg<Uint8Array>);
12
16
  /** Create hash instance */
13
- static create(): Gost3431195;
17
+ static create(): _Gost3431195;
14
18
  destroy(): void;
15
- clone(): Gost3431195;
16
- _cloneInto(to?: Gost3431195): Gost3431195;
19
+ clone(): _Gost3431195;
20
+ _cloneInto(to?: _Gost3431195): _Gost3431195;
21
+ private processBlock;
17
22
  update(data: TArg<Uint8Array>): this;
18
23
  digestInto(buf: TArg<Uint8Array>): void;
19
24
  digest(): TRet<Uint8Array>;
20
25
  }
21
- /** GOST 34.311-95 hash function */
26
+ /**
27
+ * GOST 34.311-95 hash function
28
+ *
29
+ * @param msg - message bytes to hash.
30
+ * @returns Digest bytes.
31
+ * @example
32
+ * ```ts
33
+ * import { gost3431195 } from "@li0ard/dstu/dstu9311.js";
34
+ *
35
+ * gost3431195(new Uint8Array([97, 98, 99]));
36
+ * gost3431195.create(sbox?).update(new Uint8Array([97, 98, 99])).digest();
37
+ * ```
38
+ */
22
39
  export declare const gost3431195: {
23
40
  outputLen: number;
24
41
  blockLen: number;
25
42
  canXOF: boolean;
26
43
  } & import("@noble/hashes/utils.js").HashInfo & {
27
44
  (msg: TArg<Uint8Array>): TRet<Uint8Array>;
28
- create(): Gost3431195;
45
+ create(): _Gost3431195;
29
46
  } & ((msg: TArg<TArg<Uint8Array<ArrayBufferLike>>>) => Uint8Array<ArrayBufferLike> & Uint8Array<ArrayBuffer>) & {
30
47
  outputLen: number;
31
48
  blockLen: number;
32
49
  canXOF: boolean;
33
50
  oid?: TRet<Uint8Array> | undefined;
34
- create: () => Gost3431195;
51
+ create: () => _Gost3431195;
35
52
  };
36
- /** GOST 34.311-95 HMAC */
37
- export declare class Gost3431195HMAC extends _HMAC<Gost3431195> {
53
+ /**
54
+ * HMAC over GOST 34.311-95 hash function
55
+ *
56
+ * @param key - authentication key bytes
57
+ */
58
+ export declare class Gost3431195HMAC extends _HMAC<_Gost3431195> {
38
59
  constructor(key: TArg<Uint8Array>);
39
60
  }
40
- /** GOST 34.311-95 HMAC */
61
+ /**
62
+ * HMAC over GOST 34.311-95 hash function
63
+ *
64
+ * @param key - authentication key bytes
65
+ * @param message - message bytes to authenticate
66
+ * @returns Authentication tag bytes.
67
+ * @example
68
+ * ```ts
69
+ * import { gost3431195Hmac } from "@li0ard/dstu/dstu9311.js";
70
+ * const key = new Uint8Array([1, 2, 3]);
71
+ * const message = new Uint8Array([4, 5, 6]);
72
+ * const mac = gost3431195Hmac(key, message);
73
+ * ```
74
+ */
41
75
  export declare const gost3431195Hmac: (key: TArg<Uint8Array>, msg: TArg<Uint8Array>) => TRet<Uint8Array>;
package/dstu9311/hash.js CHANGED
@@ -1,4 +1,4 @@
1
- import { concatBytes, copyBytes, createHasher } from "@noble/hashes/utils.js";
1
+ import { abytes, aoutput, clean, concatBytes, copyBytes, createHasher } from "@noble/hashes/utils.js";
2
2
  import { Dstu9311, DKE_1 } from "../dstu9311/index.js";
3
3
  import { bytesToNumberBE, numberToBytesBE } from "@noble/curves/utils.js";
4
4
  import { xorBytes } from "../utils.js";
@@ -39,47 +39,79 @@ const _step = (hin, m, sbox) => {
39
39
  x.set(chi(x));
40
40
  return x;
41
41
  };
42
- /** GOST 34.311-95 hash function */
43
- export class Gost3431195 {
42
+ /** Internal GOST 34.311-95 hash class */
43
+ export class _Gost3431195 {
44
44
  sbox;
45
45
  blockLen = 32;
46
46
  outputLen = 32;
47
47
  canXOF = false;
48
- buffer;
49
- /** GOST 34.311-95 hash function */
48
+ buffer = new Uint8Array(32);
49
+ pos = 0;
50
+ h = new Uint8Array(32);
51
+ len = 0n;
52
+ checksum = 0n;
53
+ /** Internal GOST 34.311-95 hash class */
50
54
  constructor(sbox = DKE_1) {
51
55
  this.sbox = sbox;
52
- this.buffer = new Uint8Array();
56
+ abytes(sbox, 64, "sbox");
53
57
  }
54
58
  /** Create hash instance */
55
- static create() { return new Gost3431195(); }
56
- destroy() { this.buffer = new Uint8Array(); }
59
+ static create() { return new _Gost3431195(); }
60
+ destroy() {
61
+ clean(this.buffer, this.h);
62
+ this.pos = 0;
63
+ this.len = 0n;
64
+ this.checksum = 0n;
65
+ }
57
66
  clone() { return this._cloneInto(); }
58
67
  _cloneInto(to) {
59
- to ||= new Gost3431195();
60
- to.buffer = new Uint8Array(this.buffer);
68
+ to ||= new _Gost3431195();
61
69
  to.sbox = this.sbox;
70
+ to.buffer.set(this.buffer);
71
+ to.pos = this.pos;
72
+ to.h.set(this.h);
73
+ to.len = this.len;
74
+ to.checksum = this.checksum;
62
75
  return to;
63
76
  }
77
+ processBlock(block) {
78
+ const rev = copyBytes(block).reverse();
79
+ this.len += 256n;
80
+ this.checksum = (this.checksum + bytesToNumberBE(rev)) & r;
81
+ this.h.set(_step(this.h, rev, this.sbox));
82
+ }
64
83
  update(data) {
65
- this.buffer = concatBytes(this.buffer, data);
84
+ abytes(data);
85
+ let offset = 0;
86
+ if (this.pos > 0) {
87
+ const take = Math.min(this.blockLen - this.pos, data.length);
88
+ this.buffer.set(data.subarray(0, take), this.pos);
89
+ this.pos += take;
90
+ offset = take;
91
+ if (this.pos === this.blockLen) {
92
+ this.processBlock(this.buffer);
93
+ this.pos = 0;
94
+ }
95
+ }
96
+ for (; offset + this.blockLen <= data.length; offset += this.blockLen)
97
+ this.processBlock(data.subarray(offset, offset + this.blockLen));
98
+ if (offset < data.length) {
99
+ this.buffer.set(data.subarray(offset), 0);
100
+ this.pos = data.length - offset;
101
+ }
66
102
  return this;
67
103
  }
68
104
  digestInto(buf) {
69
- if (buf.length != this.outputLen)
70
- throw new Error("digestInto: Invalid buffer length");
71
- let len = 0n, checksum = 0n;
72
- const h = new Uint8Array(this.blockLen), m = copyBytes(this.buffer);
73
- for (let i = 0; i < m.length; i += this.blockLen) {
74
- let part = m.slice(i, i + this.blockLen).reverse();
75
- len += BigInt(part.length) * 8n;
76
- checksum = (checksum + bytesToNumberBE(part)) & r;
77
- if (part.length < this.blockLen)
78
- part = numberToBytesBE(bytesToNumberBE(part), this.blockLen);
79
- h.set(_step(h, part, this.sbox));
105
+ aoutput(buf, this);
106
+ if (this.pos > 0) {
107
+ const part = new Uint8Array(this.blockLen);
108
+ part.set(this.buffer.slice(0, this.pos).reverse(), this.blockLen - this.pos);
109
+ this.len += BigInt(this.pos) * 8n;
110
+ this.checksum = (this.checksum + bytesToNumberBE(part)) & r;
111
+ this.h.set(_step(this.h, part, this.sbox));
80
112
  }
81
- h.set(_step(_step(h, numberToBytesBE(len, this.blockLen), this.sbox), numberToBytesBE(checksum, this.blockLen), this.sbox));
82
- buf.set(h.reverse());
113
+ const res = _step(_step(this.h, numberToBytesBE(this.len, this.blockLen), this.sbox), numberToBytesBE(this.checksum, this.blockLen), this.sbox);
114
+ buf.set(res.reverse());
83
115
  this.destroy();
84
116
  }
85
117
  digest() {
@@ -88,11 +120,40 @@ export class Gost3431195 {
88
120
  return buffer;
89
121
  }
90
122
  }
91
- /** GOST 34.311-95 hash function */
92
- export const gost3431195 = createHasher(Gost3431195.create);
93
- /** GOST 34.311-95 HMAC */
123
+ /**
124
+ * GOST 34.311-95 hash function
125
+ *
126
+ * @param msg - message bytes to hash.
127
+ * @returns Digest bytes.
128
+ * @example
129
+ * ```ts
130
+ * import { gost3431195 } from "@li0ard/dstu/dstu9311.js";
131
+ *
132
+ * gost3431195(new Uint8Array([97, 98, 99]));
133
+ * gost3431195.create(sbox?).update(new Uint8Array([97, 98, 99])).digest();
134
+ * ```
135
+ */
136
+ export const gost3431195 = createHasher(_Gost3431195.create);
137
+ /**
138
+ * HMAC over GOST 34.311-95 hash function
139
+ *
140
+ * @param key - authentication key bytes
141
+ */
94
142
  export class Gost3431195HMAC extends _HMAC {
95
143
  constructor(key) { super(gost3431195, key); }
96
144
  }
97
- /** GOST 34.311-95 HMAC */
145
+ /**
146
+ * HMAC over GOST 34.311-95 hash function
147
+ *
148
+ * @param key - authentication key bytes
149
+ * @param message - message bytes to authenticate
150
+ * @returns Authentication tag bytes.
151
+ * @example
152
+ * ```ts
153
+ * import { gost3431195Hmac } from "@li0ard/dstu/dstu9311.js";
154
+ * const key = new Uint8Array([1, 2, 3]);
155
+ * const message = new Uint8Array([4, 5, 6]);
156
+ * const mac = gost3431195Hmac(key, message);
157
+ * ```
158
+ */
98
159
  export const gost3431195Hmac = (key, msg) => new Gost3431195HMAC(key).update(msg).digest();
package/dstu9311/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { concatBytes, createView } from "@noble/hashes/utils.js";
1
+ import { abytes, concatBytes, createView } from "@noble/hashes/utils.js";
2
2
  import { DKE_1, keySequences } from "./const.js";
3
3
  import { bytesToNumberLE, numberToBytesLE } from "@noble/curves/utils.js";
4
4
  const G = (v, sbox) => {
@@ -33,12 +33,11 @@ export class Dstu9311 {
33
33
  constructor(key, sbox = DKE_1) {
34
34
  this.key = key;
35
35
  this.sbox = sbox;
36
- if (key.length !== this.keySize)
37
- throw new Error("Invalid key length");
36
+ abytes(key, this.keySize, "key");
37
+ abytes(sbox, 64, "sbox");
38
38
  }
39
39
  proceedBlock(block, sequence) {
40
- if (block.length !== this.blockSize)
41
- throw new Error("Invalid block size");
40
+ abytes(block, this.blockSize, "block");
42
41
  const roundKeys = extendKey(this.key, sequence);
43
42
  let a0 = Number(bytesToNumberLE(block.subarray(4, 8))), a1 = Number(bytesToNumberLE(block.subarray(0, 4)));
44
43
  for (let i = 0; i < roundKeys.length; i++) {
package/iso15946.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import type { CHash, Hash, TArg, TRet } from "@noble/hashes/utils.js";
1
+ import { type CHash, type Hash, type TArg, type TRet } from "@noble/hashes/utils.js";
2
2
  /** ISO/IEC 15946 KDF function */
3
3
  export declare const iso15946_kdf: (hash: CHash<Hash<any>>, wrapAlgoOid: string, inputData: TArg<Uint8Array>, ukm?: TArg<Uint8Array>) => TRet<Uint8Array>;
package/iso15946.js CHANGED
@@ -4,9 +4,11 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
4
4
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
+ import { abytes, ahash } from "@noble/hashes/utils.js";
7
8
  import { AsnConvert, AsnProp, AsnPropTypes } from "@peculiar/asn1-schema";
8
9
  import { AlgorithmIdentifier } from "@peculiar/asn1-x509";
9
- import { Gost3431195 } from "./dstu9311/hash.js";
10
+ import { _Gost3431195 } from "./dstu9311/hash.js";
11
+ import { astring } from "@noble/curves/utils.js";
10
12
  const KEY_LENGTH = new Uint8Array([0, 0, 1, 0]);
11
13
  const COUNTER = new Uint8Array([0, 0, 0, 1]);
12
14
  class SharedInfo {
@@ -35,15 +37,20 @@ const encodeSharedInfo = (oid, ukm) => new Uint8Array(AsnConvert.serialize(new S
35
37
  algorithm: oid,
36
38
  parameters: null
37
39
  }),
38
- entityInfo: ukm,
40
+ entityInfo: ukm?.buffer,
39
41
  suppPubInfo: KEY_LENGTH.buffer
40
42
  })));
41
43
  /** ISO/IEC 15946 KDF function */
42
44
  export const iso15946_kdf = (hash, wrapAlgoOid, inputData, ukm) => {
45
+ ahash(hash);
46
+ astring(wrapAlgoOid, "wrapAlgoOid");
47
+ abytes(inputData, undefined, "inputData");
48
+ if (ukm)
49
+ abytes(ukm, undefined, "ukm");
43
50
  if (hash.outputLen != 32)
44
51
  throw new Error("Invalid hash function. Output length must be 32 bytes");
45
52
  const hasher = hash.create();
46
- return hasher.update(hasher instanceof Gost3431195
53
+ return hasher.update(hasher instanceof _Gost3431195
47
54
  ? removeLeadZeros(inputData)
48
55
  : inputData).update(COUNTER).update(encodeSharedInfo(wrapAlgoOid, ukm)).digest();
49
56
  };
package/kalyna/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { TArg, TRet } from "@noble/hashes/utils.js";
1
+ import { type TArg, type TRet } from "@noble/hashes/utils.js";
2
2
  import type { Cipher } from "../types.js";
3
3
  export declare const column: (x: TArg<BigUint64Array>, i: number, N: number, c1: number, c2: number, c3: number, c4: number, c5: number, c6: number, c7: number, table?: Readonly<TArg<BigUint64Array>[]>, sign?: 1 | -1) => bigint;
4
4
  export declare abstract class Kalyna implements Cipher {
package/kalyna/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { abool, abytes, anumber } from "@noble/hashes/utils.js";
1
2
  import { IS, IT, T, S } from "../const.js";
2
3
  import { bytesToUint64sLE, uint64sToBytesLE, byte } from "../utils.js";
3
4
  const swap_block = (k, N) => {
@@ -30,14 +31,15 @@ export class Kalyna {
30
31
  /** Kalyna abstract class */
31
32
  constructor(key, N, isDouble = false) {
32
33
  this.N = N;
34
+ anumber(N, "N");
35
+ abool(isDouble, "isDouble");
33
36
  if (N < 2 || (N & (N - 1)) !== 0)
34
37
  throw new Error("N must be power of 2 and >= 2");
35
38
  this.blockSize = N << 3;
36
39
  this.keySize = this.blockSize;
37
40
  if (isDouble)
38
41
  this.keySize *= 2;
39
- if (key.length !== this.keySize)
40
- throw new Error("Invalid key length");
42
+ abytes(key, this.keySize, "key");
41
43
  this.wordOffsets = Array.from({ length: 8 }, (_, j) => Math.floor(j * this.N / 8));
42
44
  const X = 6 + 4 * Math.log2(N) + (isDouble ? 4 : 0);
43
45
  this.numRounds = X - (N > 2 || isDouble ? 1 : 0);
@@ -151,8 +153,7 @@ export class Kalyna {
151
153
  }
152
154
  /** Encrypt block */
153
155
  encrypt(block) {
154
- if (block.length != this.blockSize)
155
- throw new Error(`Incorrect length (need - ${this.blockSize}, got - ${block.length})`);
156
+ abytes(block, this.blockSize, "block");
156
157
  const t1 = new BigUint64Array(this.N), t2 = new BigUint64Array(this.N);
157
158
  this.addkey(bytesToUint64sLE(block), t1, this.erk);
158
159
  for (let i = 0; i < this.numRounds; i++) {
@@ -167,8 +168,7 @@ export class Kalyna {
167
168
  }
168
169
  /** Decrypt block */
169
170
  decrypt(block) {
170
- if (block.length != this.blockSize)
171
- throw new Error(`Incorrect length (need - ${this.blockSize}, got - ${block.length})`);
171
+ abytes(block, this.blockSize, "block");
172
172
  const t1 = new BigUint64Array(this.N), t2 = new BigUint64Array(this.N);
173
173
  this.subkey(bytesToUint64sLE(block), t1, this.drk.subarray(this.glOffset));
174
174
  this.IMC(t1);
package/keywrap.js CHANGED
@@ -1,4 +1,4 @@
1
- import { equalBytes, concatBytes, randomBytes } from "@noble/curves/utils.js";
1
+ import { equalBytes, concatBytes, randomBytes, abytes, abool } from "@noble/curves/utils.js";
2
2
  import { Kalyna256 } from "./kalyna/index.js";
3
3
  import { cfb, cmac } from "./modes/index.js";
4
4
  import { Dstu9311 } from "./dstu9311/index.js";
@@ -13,19 +13,22 @@ const IV1_9311 = new Uint8Array([
13
13
  export const keyWrap = (kek, useDstu9311 = false) => {
14
14
  if (kek.length != 32)
15
15
  throw new Error("Invalid key length");
16
+ abytes(kek, 32, "kek");
17
+ abool(useDstu9311, "useDstu9311");
16
18
  const cipher = new (useDstu9311 ? Dstu9311 : Kalyna256)(kek);
17
19
  const ivLength = useDstu9311 ? 8 : 32, macLength = useDstu9311 ? 4 : 32;
18
20
  const macMode = cmac(cipher, macLength);
19
21
  const finalMode = cfb(cipher, useDstu9311 ? IV1_9311 : IV1_KALYNA, 32);
20
22
  return Object.freeze({
21
23
  wrap: (key, iv) => {
24
+ abytes(key, undefined, "key");
22
25
  iv ??= randomBytes(ivLength);
23
- if (iv.length != ivLength)
24
- throw new Error("Invalid IV length");
26
+ abytes(iv, ivLength, "iv");
25
27
  const mac = macMode.compute(key);
26
28
  return finalMode.encrypt(concatBytes(iv, cfb(cipher, iv, 32).encrypt(concatBytes(key, mac))).reverse());
27
29
  },
28
30
  unwrap: (wrappedKey) => {
31
+ abytes(wrappedKey, undefined, "wrappedKey");
29
32
  const dec_wrapped = finalMode.decrypt(wrappedKey).reverse();
30
33
  const iv = dec_wrapped.subarray(0, ivLength);
31
34
  const key_mac = cfb(cipher, iv, 32).decrypt(dec_wrapped.subarray(ivLength));