@li0ard/dstu 0.1.4 → 0.1.6

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.
@@ -0,0 +1,132 @@
1
+ import { Field, mod } from "@noble/curves/abstract/modular.js";
2
+ import { bitGet, bitLen, bytesToNumberBE, randomBytes } from "@noble/curves/utils.js";
3
+ import { concatBytes } from "@noble/hashes/utils.js";
4
+ export const dstu9041Curve = (parameters) => {
5
+ if (parameters.a != 2n)
6
+ throw new Error("Unsuppored `a` parameter, must be 2");
7
+ if (mod(parameters.p, 8n) != 5n)
8
+ throw new Error("Unsupported `p` prime");
9
+ const Fp = Field(parameters.p), Fn = Field(parameters.n);
10
+ const { a, d, Gx, Gy } = parameters;
11
+ const isValidXY = (x, y) => {
12
+ const x2 = Fp.sqr(x);
13
+ const y2 = Fp.sqr(y);
14
+ const left = Fp.add(x2, Fp.mul(a, y2));
15
+ const right = Fp.add(Fp.ONE, Fp.mul(d, Fp.mul(x2, y2)));
16
+ return Fp.eql(left, right);
17
+ };
18
+ if (!isValidXY(Gx, Gy))
19
+ throw new Error("Invalid base point");
20
+ const p_minus_1 = Fp.sub(Fp.ZERO, Fp.ONE);
21
+ const p_minus_1_over_2 = Fp.div(Fp.sub(Fp.ORDER, Fp.ONE), 2n);
22
+ const a_over_d = Fp.div(a, d);
23
+ class Point {
24
+ X;
25
+ Y;
26
+ Z;
27
+ static BASE = new Point(Gx, Gy, Fp.ONE);
28
+ static ZERO = new Point(Fp.ONE, Fp.ZERO, Fp.ONE);
29
+ static Fp = Fp;
30
+ static Fn = Fn;
31
+ constructor(X, Y, Z) {
32
+ this.X = X;
33
+ this.Y = Y;
34
+ this.Z = Z;
35
+ Object.freeze(this);
36
+ }
37
+ get x() {
38
+ return Fp.div(this.X, this.Z);
39
+ }
40
+ get y() {
41
+ return Fp.div(this.Y, this.Z);
42
+ }
43
+ add(other) {
44
+ const A = Fp.mul(this.Z, other.Z);
45
+ const B = Fp.sqr(A);
46
+ const C = Fp.mul(this.X, other.X);
47
+ const D = Fp.mul(this.Y, other.Y);
48
+ const E = Fp.mul(d, Fp.mul(C, D));
49
+ const F = Fp.sub(B, E);
50
+ const G = Fp.add(B, E);
51
+ const self_sum = Fp.add(this.X, this.Y);
52
+ const other_sum = Fp.add(other.X, other.Y);
53
+ const cross = Fp.mul(self_sum, other_sum);
54
+ const xr = Fp.mul(Fp.mul(A, G), Fp.sub(C, Fp.mul(a, D)));
55
+ const yr = Fp.mul(Fp.mul(A, F), Fp.sub(Fp.sub(cross, C), D));
56
+ const zr = Fp.mul(F, G);
57
+ return new Point(xr, yr, zr);
58
+ }
59
+ multiply(scalar) {
60
+ if (this.is0())
61
+ return Point.ZERO;
62
+ let S = new Point(this.X, this.Y, this.Z);
63
+ for (let i = bitLen(scalar) - 2; i >= 0; i--) {
64
+ S = S.add(S);
65
+ if (bitGet(scalar, i) == Fp.ONE)
66
+ S = S.add(this);
67
+ }
68
+ return S;
69
+ }
70
+ is0() {
71
+ return Fp.eql(this.x, Fp.ONE) && Fp.eql(this.y, Fp.ZERO);
72
+ }
73
+ assertValidity() {
74
+ if (!isValidXY(this.x, this.y))
75
+ throw new Error("Assertation failed: point isn't on curve");
76
+ return this;
77
+ }
78
+ toBytes() {
79
+ return concatBytes(Fp.toBytes(this.x), Fp.toBytes(this.y));
80
+ }
81
+ static fromBytes(bytes) {
82
+ if (bytes.length !== 2 * Fp.BYTES)
83
+ throw new Error(`expected ${2 * Fp.BYTES} bytes, got ${bytes.length}`);
84
+ const x = Fp.fromBytes(bytes.subarray(0, Fp.BYTES));
85
+ const y = Fp.fromBytes(bytes.subarray(Fp.BYTES, 2 * Fp.BYTES));
86
+ return Point.fromAffine(x, y);
87
+ }
88
+ static fromAffine(x, y) { return new Point(x, y, Fp.ONE).assertValidity(); }
89
+ static fromX(x) {
90
+ const x2 = Fp.sqr(x);
91
+ if (Fp.eql(x, Fp.ZERO) ||
92
+ Fp.eql(x, Fp.ONE) ||
93
+ Fp.eql(x, p_minus_1) ||
94
+ Fp.eql(x2, a_over_d))
95
+ throw new Error("Invalid x-coordinate, can't recover y");
96
+ const num = Fp.sub(Fp.ONE, x2);
97
+ const denom = Fp.sub(a, Fp.mul(d, x2));
98
+ const v = Fp.div(num, denom);
99
+ if (Fp.pow(v, p_minus_1_over_2) != Fp.ONE)
100
+ throw new Error("Invalid x-coordinate, non-complience with euler criterion");
101
+ const candidate = Point.fromAffine(x, Fp.sqrt(v));
102
+ if (!candidate.multiply(Fn.ORDER).is0())
103
+ throw new Error("Invalid x-coordinate, can't recover y");
104
+ return candidate;
105
+ }
106
+ }
107
+ const getPublicKey = (secretKey) => Point.BASE.multiply(bytesToNumberBE(secretKey)).toBytes();
108
+ const keygen = () => {
109
+ const secretKey = randomBytes(Fp.BYTES);
110
+ const publicKey = getPublicKey(secretKey);
111
+ return { secretKey, publicKey };
112
+ };
113
+ return Object.freeze({ Point, getPublicKey, keygen });
114
+ };
115
+ export const curve256 = dstu9041Curve({
116
+ p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe4dn,
117
+ n: 0x4000000000000000000000000000000029e26087789bc2815bdff97093543ccfn,
118
+ a: 2n,
119
+ d: 0x18n,
120
+ h: 1n,
121
+ Gx: 0x91f5d0e7e2d417e3108b13b075cdc7756045f8424479fcfe8f23d27250a0883fn,
122
+ Gy: 0x742f27a268641c9d7ddf69892be3df3d8f9cc52260b89a4953c8379c7c0a212bn
123
+ });
124
+ export const curve512 = dstu9041Curve({
125
+ p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc95n,
126
+ n: 0x400000000000000000000000000000000000000000000000000000000000000028a3ce52209e2bd4952882d5574165192c46c0d0311fea6bf9fece70ee63b59fn,
127
+ a: 2n,
128
+ d: 0x10dn,
129
+ h: 1n,
130
+ Gx: 0x5230a1ee747050a072bd7319741586ea520388b6b53094571c821a2fc9a9e83d56665346b5db04c43e75261dbda512728faafac48ae9260a5a184e2933e3a400n,
131
+ Gy: 0x53a0d50cc63c9219762f451978aef214dbcfcc3a5cb5ef27124991a86b42b3a1a832724a0e6b930fdd1da2e27a540d6b675e4422c444f529c508f0bae7d0a85n
132
+ });
@@ -0,0 +1,21 @@
1
+ import { type TArg, type TRet } from "@noble/curves/utils.js";
2
+ /** DSTU 9041:2020 (256 bit) */
3
+ export declare const dstu9041_256: Readonly<{
4
+ getPublicKey: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;
5
+ keygen: () => {
6
+ secretKey: TRet<Uint8Array>;
7
+ publicKey: TRet<Uint8Array>;
8
+ };
9
+ encrypt: (message: TArg<Uint8Array>, publicKey: TArg<Uint8Array>, rand?: TArg<Uint8Array>) => TRet<Uint8Array>;
10
+ decrypt: (ciphertext: TArg<Uint8Array>, privateKey: TArg<Uint8Array>) => TRet<Uint8Array>;
11
+ }>;
12
+ /** DSTU 9041:2020 (512 bit) */
13
+ export declare const dstu9041_512: Readonly<{
14
+ getPublicKey: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;
15
+ keygen: () => {
16
+ secretKey: TRet<Uint8Array>;
17
+ publicKey: TRet<Uint8Array>;
18
+ };
19
+ encrypt: (message: TArg<Uint8Array>, publicKey: TArg<Uint8Array>, rand?: TArg<Uint8Array>) => TRet<Uint8Array>;
20
+ decrypt: (ciphertext: TArg<Uint8Array>, privateKey: TArg<Uint8Array>) => TRet<Uint8Array>;
21
+ }>;
@@ -0,0 +1,98 @@
1
+ import { bytesToNumberBE, concatBytes, equalBytes, numberToBytesBE } from "@noble/curves/utils.js";
2
+ import { kupyna256 } from "../kupyna/index.js";
3
+ import { curve256, curve512 } from "./curve.js";
4
+ import { kw } from "../modes/index.js";
5
+ import { Kalyna256, Kalyna512 } from "../kalyna/index.js";
6
+ import { randomBytes } from "@noble/hashes/utils.js";
7
+ const ID_KUPYNA256 = 1;
8
+ const dstu9041 = (length) => {
9
+ const MAX_LENGTH = length == 256 ? 200 : 424;
10
+ const PADDED_MESSAGE_BYTES = MAX_LENGTH / 8;
11
+ const HASH_LENGTH_BYTES = length == 256 ? 4 : 8;
12
+ const STRUCT_BYTES = 1 + HASH_LENGTH_BYTES + 2 + PADDED_MESSAGE_BYTES;
13
+ const curve = length == 256 ? curve256 : curve512;
14
+ const cipher = length == 256 ? Kalyna256 : Kalyna512;
15
+ const padMessage = (message, messageBits) => {
16
+ if (messageBits == 0)
17
+ throw new Error("Invalid message length");
18
+ if (messageBits > MAX_LENGTH)
19
+ throw new Error("Message too long");
20
+ const messageBytes = Math.ceil(messageBits / 8);
21
+ if (message.length != messageBytes)
22
+ throw new Error("Message length mismatch");
23
+ const paddedMessage = new Uint8Array(PADDED_MESSAGE_BYTES);
24
+ paddedMessage.set(message, PADDED_MESSAGE_BYTES - messageBytes);
25
+ return paddedMessage;
26
+ };
27
+ const buildStruct = (hashId, paddedMessage, messageLength) => {
28
+ const digest = kupyna256(concatBytes(messageLength, paddedMessage));
29
+ const struct = new Uint8Array(STRUCT_BYTES);
30
+ struct[0] = hashId;
31
+ struct.set(digest.subarray(digest.length - HASH_LENGTH_BYTES), 1);
32
+ struct.set(messageLength, 1 + HASH_LENGTH_BYTES);
33
+ struct.set(paddedMessage, 3 + HASH_LENGTH_BYTES);
34
+ return struct;
35
+ };
36
+ const parseStruct = (struct) => {
37
+ if (struct.length != STRUCT_BYTES)
38
+ throw new Error("Invalid ciphertext");
39
+ const hashId = struct[0];
40
+ if (hashId != ID_KUPYNA256)
41
+ throw new Error("Invalid hash ID");
42
+ const embeddedHash = struct.subarray(1, HASH_LENGTH_BYTES + 1);
43
+ const messageLength = struct.subarray(1 + HASH_LENGTH_BYTES, 3 + HASH_LENGTH_BYTES);
44
+ const paddedMessage = new Uint8Array(PADDED_MESSAGE_BYTES);
45
+ paddedMessage.set(struct.subarray(3 + HASH_LENGTH_BYTES));
46
+ const messageBits = Number(bytesToNumberBE(messageLength));
47
+ if (messageBits == 0)
48
+ throw new Error("Invalid message length");
49
+ if (messageBits > MAX_LENGTH)
50
+ throw new Error("Message too long");
51
+ const digest = kupyna256(concatBytes(messageLength, paddedMessage));
52
+ if (!equalBytes(embeddedHash, digest.subarray(digest.length - HASH_LENGTH_BYTES)))
53
+ throw new Error("Integrity check failed, hash mismatch");
54
+ const messageBytes = Math.ceil(messageBits / 8);
55
+ const paddingLen = PADDED_MESSAGE_BYTES - messageBytes;
56
+ let invalidPadding = 0;
57
+ for (let i = 0; i < paddedMessage.length; i++)
58
+ invalidPadding |= (i < paddingLen ? 1 : 0) & (paddedMessage[i] != 0 ? 1 : 0);
59
+ if (invalidPadding != 0)
60
+ throw new Error("Invalid padding");
61
+ return paddedMessage.subarray(paddingLen);
62
+ };
63
+ return Object.freeze({
64
+ getPublicKey: curve.getPublicKey,
65
+ keygen: curve.keygen,
66
+ encrypt: (message, publicKey, rand) => {
67
+ const message_bits = message.length * 8;
68
+ const paddedMessage = padMessage(message, message_bits);
69
+ const struct = buildStruct(ID_KUPYNA256, paddedMessage, numberToBytesBE(message_bits, 2));
70
+ const e = curve.Point.Fn.create(bytesToNumberBE(rand ?? randomBytes(STRUCT_BYTES)));
71
+ const R = curve.Point.BASE.multiply(e);
72
+ const r = curve.Point.Fp.toBytes(R.x);
73
+ const T = curve.Point.fromBytes(publicKey).multiply(e);
74
+ const key = curve.Point.Fp.toBytes(T.x);
75
+ const plaintext = new Uint8Array(2 * STRUCT_BYTES);
76
+ plaintext.set(struct);
77
+ const ciphertext = kw(new cipher(key)).wrap(plaintext);
78
+ return concatBytes(r, ciphertext);
79
+ },
80
+ decrypt: (ciphertext, privateKey) => {
81
+ if (ciphertext.length != length / 2)
82
+ throw new Error("Invalid ciphertext length");
83
+ const r = bytesToNumberBE(ciphertext.subarray(0, STRUCT_BYTES));
84
+ if (!curve.Point.Fp.isValidNot0(r))
85
+ throw new Error("Invalid ciphertext");
86
+ const R = curve.Point.fromX(r);
87
+ const T = R.multiply(bytesToNumberBE(privateKey));
88
+ const key = curve.Point.Fp.toBytes(T.x);
89
+ // KW already does unpadding
90
+ const plaintext = kw(new cipher(key)).unwrap(ciphertext.subarray(STRUCT_BYTES));
91
+ return parseStruct(plaintext);
92
+ }
93
+ });
94
+ };
95
+ /** DSTU 9041:2020 (256 bit) */
96
+ export const dstu9041_256 = dstu9041(256);
97
+ /** DSTU 9041:2020 (512 bit) */
98
+ export const dstu9041_512 = dstu9041(512);
package/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from "./dstu4145/index.js";
2
+ export * from "./dstu9041/index.js";
2
3
  export { Kalyna128, Kalyna128_256, Kalyna256, Kalyna256_512, Kalyna512 } from "./kalyna/index.js";
3
4
  export * from "./kupyna/index.js";
4
5
  export * from "./modes/index.js";
package/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from "./dstu4145/index.js";
2
+ export * from "./dstu9041/index.js";
2
3
  export { Kalyna128, Kalyna128_256, Kalyna256, Kalyna256_512, Kalyna512 } from "./kalyna/index.js";
3
4
  export * from "./kupyna/index.js";
4
5
  export * from "./modes/index.js";
package/kupyna/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { concatBytes, createHasher } from "@noble/hashes/utils.js";
2
- import { bytesToUint64sLE, numberToBytesLE, uint64sToBytesLE } from "../utils.js";
2
+ import { bytesToUint64sLE, uint64sToBytesLE } from "../utils.js";
3
3
  import { column } from "../kalyna/index.js";
4
+ import { numberToBytesLE } from "@noble/curves/utils.js";
4
5
  const r = 0x00f0f0f0f0f0f0f3n;
5
6
  class Kupyna {
6
7
  blockLen;
package/kupyna/kmac.js CHANGED
@@ -1,5 +1,6 @@
1
- import { numberToBytesLE, uint64sToBytesLE } from "../utils.js";
1
+ import { uint64sToBytesLE } from "../utils.js";
2
2
  import { Kupyna256, Kupyna384, Kupyna512 } from "./index.js";
3
+ import { numberToBytesLE } from "@noble/curves/utils.js";
3
4
  const dpad = numberToBytesLE(128, 128);
4
5
  const kpad32 = new Uint8Array([
5
6
  0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
package/modes/cbc.js CHANGED
@@ -3,18 +3,16 @@ import { xorBytes } from "../utils.js";
3
3
  export const cbc = (cipher, iv) => {
4
4
  if (iv.length !== cipher.blockSize)
5
5
  throw new Error("Invalid IV size");
6
- const encrypter = cipher.encrypt.bind(cipher);
7
- const decrypter = cipher.decrypt.bind(cipher);
8
- return {
6
+ return Object.freeze({
9
7
  encrypt: (plaintext) => {
10
8
  if (plaintext.length % cipher.blockSize !== 0)
11
9
  throw new Error("Plaintext not aligned");
12
10
  let buf = new Uint8Array(iv);
13
11
  const output = new Uint8Array(plaintext.length);
14
12
  for (let i = 0; i < plaintext.length; i += cipher.blockSize) {
15
- const blk = encrypter(xorBytes(plaintext.subarray(i, i + cipher.blockSize), buf));
13
+ const blk = cipher.encrypt(xorBytes(plaintext.subarray(i, i + cipher.blockSize), buf));
16
14
  output.set(blk, i);
17
- buf = blk.slice();
15
+ buf = blk;
18
16
  }
19
17
  return output;
20
18
  },
@@ -25,10 +23,10 @@ export const cbc = (cipher, iv) => {
25
23
  const output = new Uint8Array(ciphertext.length);
26
24
  for (let i = 0; i < ciphertext.length; i += cipher.blockSize) {
27
25
  const blk = ciphertext.subarray(i, i + cipher.blockSize);
28
- output.set(xorBytes(decrypter(blk), buf), i);
29
- buf = blk.slice();
26
+ output.set(xorBytes(cipher.decrypt(blk), buf), i);
27
+ buf = blk;
30
28
  }
31
29
  return output;
32
30
  }
33
- };
31
+ });
34
32
  };
package/modes/cfb.js CHANGED
@@ -1,14 +1,12 @@
1
1
  /** Cipher Feedback (CFB) mode */
2
2
  export const cfb = (cipher, iv, q = cipher.blockSize) => {
3
- const encrypter = cipher.encrypt.bind(cipher);
4
- return {
3
+ if (q !== 1 && q !== 8 && q !== 16 && q !== 32 && q !== 64)
4
+ throw new Error('q must be 1, 8, 16, 32, or 64');
5
+ if (q > cipher.blockSize)
6
+ throw new Error('q cannot exceed block size');
7
+ return Object.freeze({
5
8
  encrypt: (plaintext) => {
6
- const blockSize = cipher.blockSize;
7
- if (q !== 1 && q !== 8 && q !== 16 && q !== 32 && q !== 64)
8
- throw new Error('q must be 1, 8, 16, 32, or 64');
9
- if (q > blockSize)
10
- throw new Error('q cannot exceed block size');
11
- let gamma = encrypter(iv);
9
+ let gamma = cipher.encrypt(iv);
12
10
  const feed = new Uint8Array(iv);
13
11
  let offset = 0;
14
12
  const result = new Uint8Array(plaintext.length);
@@ -16,32 +14,27 @@ export const cfb = (cipher, iv, q = cipher.blockSize) => {
16
14
  while (offset > 0 && dataOff < plaintext.length) {
17
15
  result[dataOff] = plaintext[dataOff] ^ gamma[offset];
18
16
  feed[offset++] = result[dataOff++];
19
- if (offset >= blockSize) {
20
- gamma = encrypter(feed);
21
- offset = blockSize - q;
17
+ if (offset >= cipher.blockSize) {
18
+ gamma = cipher.encrypt(feed);
19
+ offset = cipher.blockSize - q;
22
20
  }
23
21
  }
24
22
  while (dataOff + q <= plaintext.length) {
25
23
  for (let i = 0; i < q; i++)
26
- result[dataOff + i] = plaintext[dataOff + i] ^ gamma[blockSize - q + i];
27
- feed.set(gamma.subarray(0, blockSize - q));
28
- feed.set(result.subarray(dataOff, dataOff + q), blockSize - q);
29
- gamma = encrypter(feed);
24
+ result[dataOff + i] = plaintext[dataOff + i] ^ gamma[cipher.blockSize - q + i];
25
+ feed.set(gamma.subarray(0, cipher.blockSize - q));
26
+ feed.set(result.subarray(dataOff, dataOff + q), cipher.blockSize - q);
27
+ gamma = cipher.encrypt(feed);
30
28
  dataOff += q;
31
29
  }
32
30
  while (dataOff < plaintext.length) {
33
- result[dataOff] = plaintext[dataOff] ^ gamma[blockSize - (plaintext.length - dataOff)];
31
+ result[dataOff] = plaintext[dataOff] ^ gamma[cipher.blockSize - (plaintext.length - dataOff)];
34
32
  dataOff++;
35
33
  }
36
34
  return result;
37
35
  },
38
36
  decrypt: (ciphertext) => {
39
- const blockSize = cipher.blockSize;
40
- if (q !== 1 && q !== 8 && q !== 16 && q !== 32 && q !== 64)
41
- throw new Error('q must be 1, 8, 16, 32, or 64');
42
- if (q > blockSize)
43
- throw new Error('q cannot exceed block size');
44
- let gamma = encrypter(iv);
37
+ let gamma = cipher.encrypt(iv);
45
38
  const feed = new Uint8Array(iv);
46
39
  let offset = 0;
47
40
  const result = new Uint8Array(ciphertext.length);
@@ -49,24 +42,24 @@ export const cfb = (cipher, iv, q = cipher.blockSize) => {
49
42
  while (offset > 0 && dataOff < ciphertext.length) {
50
43
  result[dataOff] = ciphertext[dataOff] ^ gamma[offset];
51
44
  feed[offset++] = ciphertext[dataOff++];
52
- if (offset >= blockSize) {
53
- gamma = encrypter(feed);
54
- offset = blockSize - q;
45
+ if (offset >= cipher.blockSize) {
46
+ gamma = cipher.encrypt(feed);
47
+ offset = cipher.blockSize - q;
55
48
  }
56
49
  }
57
50
  while (dataOff + q <= ciphertext.length) {
58
51
  for (let i = 0; i < q; i++)
59
- result[dataOff + i] = ciphertext[dataOff + i] ^ gamma[blockSize - q + i];
60
- feed.set(gamma.subarray(0, blockSize - q));
61
- feed.set(ciphertext.subarray(dataOff, dataOff + q), blockSize - q);
62
- gamma = encrypter(feed);
52
+ result[dataOff + i] = ciphertext[dataOff + i] ^ gamma[cipher.blockSize - q + i];
53
+ feed.set(gamma.subarray(0, cipher.blockSize - q));
54
+ feed.set(ciphertext.subarray(dataOff, dataOff + q), cipher.blockSize - q);
55
+ gamma = cipher.encrypt(feed);
63
56
  dataOff += q;
64
57
  }
65
58
  while (dataOff < ciphertext.length) {
66
- result[dataOff] = ciphertext[dataOff] ^ gamma[blockSize - (ciphertext.length - dataOff)];
59
+ result[dataOff] = ciphertext[dataOff] ^ gamma[cipher.blockSize - (ciphertext.length - dataOff)];
67
60
  dataOff++;
68
61
  }
69
62
  return result;
70
63
  }
71
- };
64
+ });
72
65
  };
package/modes/ctr.js CHANGED
@@ -10,7 +10,7 @@ const incrementCounterAt = (ctr, pos) => {
10
10
  export const ctr = (cipher, iv) => {
11
11
  if (iv.length !== cipher.blockSize)
12
12
  throw new Error("Invalid IV size");
13
- return {
13
+ return Object.freeze({
14
14
  crypt: (msg) => {
15
15
  const keystreamBlocks = [];
16
16
  const ctr = cipher.encrypt(iv);
@@ -20,5 +20,5 @@ export const ctr = (cipher, iv) => {
20
20
  }
21
21
  return xorBytes(concatBytes(...keystreamBlocks), msg);
22
22
  }
23
- };
23
+ });
24
24
  };
package/modes/ecb.js CHANGED
@@ -10,8 +10,8 @@ export const ecb = (cipher) => {
10
10
  output.set(crypter(data.subarray(i, i + cipher.blockSize)), i);
11
11
  return output;
12
12
  };
13
- return {
13
+ return Object.freeze({
14
14
  encrypt: (plaintext) => core(encrypter, plaintext),
15
15
  decrypt: (ciphertext) => core(decrypter, ciphertext),
16
- };
16
+ });
17
17
  };
package/modes/gcm.js CHANGED
@@ -1,20 +1,18 @@
1
1
  import { concatBytes } from "@noble/hashes/utils.js";
2
2
  import { ctr } from "./ctr.js";
3
3
  import { gmac } from "./mac.js";
4
- import { equalBytes } from "../utils.js";
4
+ import { equalBytes } from "@noble/curves/utils.js";
5
5
  /** Galois counter (GCM) mode (AEAD) */
6
- export const gcm = (cipher, iv, q = 16) => {
7
- return {
8
- seal: (plaintext, aad) => {
9
- const enc = ctr(cipher, iv).crypt(plaintext);
10
- return concatBytes(enc, gmac(cipher, q).compute(aad || new Uint8Array(), enc));
11
- },
12
- open: (ciphertext, aad) => {
13
- const enc = ciphertext.subarray(0, -q);
14
- const hC = gmac(cipher, q).compute(aad || new Uint8Array(), enc);
15
- if (!equalBytes(ciphertext.subarray(-q), hC))
16
- throw new Error("Invalid MAC");
17
- return ctr(cipher, iv).crypt(enc);
18
- }
19
- };
20
- };
6
+ export const gcm = (cipher, iv, q = 16) => Object.freeze({
7
+ seal: (plaintext, aad) => {
8
+ const enc = ctr(cipher, iv).crypt(plaintext);
9
+ return concatBytes(enc, gmac(cipher, q).compute(aad || new Uint8Array(), enc));
10
+ },
11
+ open: (ciphertext, aad) => {
12
+ const enc = ciphertext.subarray(0, -q);
13
+ const hC = gmac(cipher, q).compute(aad || new Uint8Array(), enc);
14
+ if (!equalBytes(ciphertext.subarray(-q), hC))
15
+ throw new Error("Invalid MAC");
16
+ return ctr(cipher, iv).crypt(enc);
17
+ }
18
+ });
package/modes/index.d.ts CHANGED
@@ -3,5 +3,7 @@ export * from "./cfb.js";
3
3
  export * from "./ctr.js";
4
4
  export * from "./ecb.js";
5
5
  export * from "./gcm.js";
6
+ export * from "./kw.js";
6
7
  export * from "./mac.js";
7
8
  export * from "./ofb.js";
9
+ export * from "./xts.js";
package/modes/index.js CHANGED
@@ -3,5 +3,7 @@ export * from "./cfb.js";
3
3
  export * from "./ctr.js";
4
4
  export * from "./ecb.js";
5
5
  export * from "./gcm.js";
6
+ export * from "./kw.js";
6
7
  export * from "./mac.js";
7
8
  export * from "./ofb.js";
9
+ export * from "./xts.js";
package/modes/kw.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { type TArg, type TRet } from "@noble/hashes/utils.js";
2
+ import type { Kalyna } from "../kalyna/index.js";
3
+ /** Key wrapping (KW) */
4
+ export declare const kw: (cipher: Kalyna) => {
5
+ wrap: (key: TArg<Uint8Array>) => TRet<Uint8Array>;
6
+ unwrap: (wrappedKey: TArg<Uint8Array>) => TRet<Uint8Array>;
7
+ };
package/modes/kw.js ADDED
@@ -0,0 +1,79 @@
1
+ import { concatBytes } from "@noble/hashes/utils.js";
2
+ import { pad, unpad } from "../padding.js";
3
+ /** Key wrapping (KW) */
4
+ export const kw = (cipher) => {
5
+ const half = cipher.blockSize >> 1;
6
+ return Object.freeze({
7
+ wrap: (key) => {
8
+ let plaintext;
9
+ if (key.length % cipher.blockSize === 0)
10
+ plaintext = key;
11
+ else {
12
+ const withLength = new Uint8Array(key.length + half);
13
+ withLength.set(key);
14
+ let bitLength = key.length << 3;
15
+ let i = 0;
16
+ while (bitLength > 0) {
17
+ withLength[key.length + i] = bitLength & 0xff;
18
+ i++;
19
+ bitLength >>>= 8;
20
+ }
21
+ plaintext = pad(withLength, cipher.blockSize);
22
+ }
23
+ const r = plaintext.length / cipher.blockSize;
24
+ const n = 2 * (r + 1);
25
+ const v = (n - 1) * 6;
26
+ const qLen = (n - 1) * half;
27
+ const B = plaintext.slice(0, half);
28
+ const q = new Uint8Array(qLen);
29
+ q.set(plaintext.subarray(half));
30
+ const block = new Uint8Array(cipher.blockSize);
31
+ for (let i = 1; i <= v; i++) {
32
+ block.set(B);
33
+ block.set(q.subarray(0, half), half);
34
+ const encrypted = cipher.encrypt(block);
35
+ q.copyWithin(0, half);
36
+ q.set(encrypted.subarray(0, half), qLen - half);
37
+ B.set(encrypted.subarray(half));
38
+ B[0] ^= i & 0xff;
39
+ B[1] ^= (i >>> 8) & 0xff;
40
+ B[2] ^= (i >>> 16) & 0xff;
41
+ B[3] ^= (i >>> 24) & 0xff;
42
+ }
43
+ return concatBytes(B, q);
44
+ },
45
+ unwrap: (wrappedKey) => {
46
+ if (wrappedKey.length < 2 * cipher.blockSize)
47
+ throw new Error("Invalid input length: must be at least 2 blocks");
48
+ const r = wrappedKey.length / cipher.blockSize - 1;
49
+ const n = 2 * (r + 1);
50
+ const v = (n - 1) * 6;
51
+ const qLen = (n - 1) * half;
52
+ const B = wrappedKey.slice(0, half);
53
+ const q = wrappedKey.slice(half, half + qLen);
54
+ const block = new Uint8Array(cipher.blockSize);
55
+ for (let i = v; i >= 1; i--) {
56
+ block.set(q.subarray(qLen - half));
57
+ block.set(B, half);
58
+ block[half] ^= i & 0xff;
59
+ block[half + 1] ^= (i >>> 8) & 0xff;
60
+ block[half + 2] ^= (i >>> 16) & 0xff;
61
+ block[half + 3] ^= (i >>> 24) & 0xff;
62
+ const decrypted = cipher.decrypt(block);
63
+ q.copyWithin(half, 0, qLen - half);
64
+ q.set(decrypted.subarray(half));
65
+ B.set(decrypted.subarray(0, half));
66
+ }
67
+ let mismatch = 0;
68
+ for (let k = qLen - cipher.blockSize; k < qLen; k++)
69
+ mismatch |= q[k];
70
+ if (mismatch != 0)
71
+ throw new Error("KW checksum mismatch");
72
+ const recovered = concatBytes(B, q);
73
+ let current_length = unpad(recovered, cipher.blockSize).length;
74
+ if (current_length % cipher.blockSize !== 0)
75
+ current_length -= half + 1;
76
+ return recovered.slice(0, current_length);
77
+ },
78
+ });
79
+ };