boho 2.2.1 → 3.0.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/src/constants.js CHANGED
@@ -1,125 +1,41 @@
1
- // Copyright (c) 2024 Taeo Lee (sixgen@gmail.com)
1
+ // Copyright (c) 2024-2026 Taeo Lee (sixgen@gmail.com)
2
2
  // MIT License
3
3
  //
4
4
  // https://github.com/remocons/boho
5
- //
6
- //
7
- //
8
- import MBP from "meta-buffer-pack"
9
- import { Buffer } from 'buffer/index.js'
10
5
 
11
6
  /**
12
- * Boho message type constants
7
+ * Boho message types (one-byte header). Boho 3 (Ascon). The 2.x codes 0xB1, 0xB2, 0xB6, 0xB7
8
+ * and 0xB8 belong to the classic protocol and are not used.
13
9
  * @typedef {Object} BohoMsg
14
10
  * @property {number} SERVER_TIME_NONCE
11
+ * @property {number} AUTH_FAIL
15
12
  * @property {number} AUTH_REQ
16
13
  * @property {number} AUTH_RES
17
- * @property {number} AUTH_FAIL
18
14
  * @property {number} ENC_PACK
19
15
  * @property {number} ENC_E2E
20
- * @property {number} ENC_488
16
+ * @property {number} ENC
21
17
  */
22
-
23
- // One-byte header for remote control message pack.
24
- export let BohoMsg = {
25
- SERVER_TIME_NONCE : 0xB0,
26
- AUTH_REQ: 0xB1,
27
- AUTH_RES: 0xB2,
18
+ export const BohoMsg = {
19
+ SERVER_TIME_NONCE: 0xB0,
28
20
  AUTH_FAIL: 0xB3,
29
-
30
- ENC_PACK : 0xB6,
31
- ENC_E2E : 0xB7,
32
- ENC_488 : 0xB8
21
+ AUTH_REQ: 0xB4,
22
+ AUTH_RES: 0xB5,
23
+ ENC_PACK: 0xB9,
24
+ ENC_E2E: 0xBA,
25
+ ENC: 0xBB
33
26
  }
34
27
 
35
- for (let c in BohoMsg) { BohoMsg[BohoMsg[c]] = c }
28
+ for (const c of Object.keys(BohoMsg)) { BohoMsg[BohoMsg[c]] = c }
36
29
 
37
30
  /**
38
- * Boho message meta information
39
- * @typedef {Object} Meta
40
- * @property {any} SERVER_TIME_NONCE
41
- * @property {any} AUTH_REQ
42
- * @property {any} AUTH_RES
43
- * @property {any} ENC_PACK
44
- * @property {any} ENC_488
31
+ * Sizes in bytes: whole packets (SERVER_TIME_NONCE, AUTH_REQ, AUTH_RES) or headers before the
32
+ * payload (ENC and ENC_E2E: 21, ENC_PACK: 29).
33
+ * @typedef {Object} MetaSize
45
34
  */
46
-
47
- export const Meta = {
48
-
49
- SERVER_TIME_NONCE: MBP.meta( // 13
50
- MBP.MB('header','8', 0),
51
- MBP.MB('unixTime','32L', 0),
52
- MBP.MB('milTime','16L', 0 ),
53
- MBP.MB('counter','16L', 0 ),
54
- MBP.MB('nonce', Buffer.alloc(4))
55
- ),
56
-
57
- AUTH_REQ: MBP.meta( // 45
58
- MBP.MB('header','8', 0),
59
- MBP.MB('id8',Buffer.alloc(8)),
60
- MBP.MB('nonce', Buffer.alloc(4)),
61
- MBP.MB('hmac32', Buffer.alloc(32))
62
- ),
63
-
64
- AUTH_RES: MBP.meta( // 33
65
- MBP.MB('header','8', 0),
66
- MBP.MB('hmac32', Buffer.alloc(32))
67
- ),
68
-
69
-
70
- ENC_PACK: MBP.meta( //25 + payload
71
- MBP.MB('type','8',0),
72
- MBP.MB('len','32L',0), // pure xdata size.
73
- MBP.MB('salt12', Buffer.alloc(12)), // sec,mil,rand
74
- MBP.MB('hmac',8,0)
75
- // MBP.MB( 'xdata', encData )
76
- ),
77
-
78
-
79
- ENC_488: MBP.meta( // 21 + payload
80
- MBP.MB('type','8', 0 ),
81
- MBP.MB('len','32L', 0 ),
82
- MBP.MB('otpSrc8', Buffer.alloc(8) ),
83
- MBP.MB('hmac8', Buffer.alloc(8) )
84
- // MBP.MB('xdata', encData )
85
- )
86
-
87
-
88
- }
89
-
90
-
91
- function getMetaSize(meta){
92
- let lastItem = meta[ meta.length - 1]
93
- return lastItem[2] + lastItem[3]
94
- }
95
-
96
- /**
97
- * Byte size information for each meta
98
- * @typedef {Object} MetaSize
99
- * @property {number} AUTH_REQ
100
- * @property {number} SERVER_TIME_NONCE
101
- * @property {number} AUTH_RES
102
- * @property {number} ENC_PACK
103
- * @property {number} ENC_488
104
- */
105
-
106
- /**
107
- * Byte size information for each meta
108
- * @type {MetaSize}
109
- */
110
- export const MetaSize = {
111
- SERVER_TIME_NONCE: getMetaSize( Meta.SERVER_TIME_NONCE ),
112
- AUTH_REQ: getMetaSize( Meta.AUTH_REQ ),
113
- AUTH_RES: getMetaSize( Meta.AUTH_RES ),
114
- ENC_PACK: getMetaSize( Meta.ENC_PACK ),
115
- ENC_488: getMetaSize( Meta.ENC_488 )
116
- }
117
-
118
- // console.log( 'boho 2.0.0 MetaSize', MetaSize )
119
- // boho MetaSize {
120
- // SERVER_TIME_NONCE: 13,
121
- // AUTH_REQ: 45,
122
- // AUTH_RES: 33,
123
- // ENC_PACK: 25,
124
- // ENC_488: 21
125
- // }
35
+ export const MetaSize = {
36
+ SERVER_TIME_NONCE: 13,
37
+ AUTH_REQ: 33,
38
+ AUTH_RES: 17,
39
+ ENC: 21,
40
+ ENC_PACK: 29
41
+ }
package/src/index.js CHANGED
@@ -1,17 +1,18 @@
1
- // Copyright (c) 2024 Taeo Lee (sixgen@gmail.com)
1
+ // Copyright (c) 2024-2026 Taeo Lee (sixgen@gmail.com)
2
2
  // MIT License
3
3
  //
4
4
  // https://github.com/remocons/boho
5
5
  //
6
- //
7
- //
8
- import { Boho, RAND, BohoMsg, Meta, MetaSize, sha256, MBP, Buffer } from './boho.js'
6
+ import { Boho, RAND, BohoMsg, MetaSize, deriveKey, MBP, Buffer } from './boho.js'
7
+ import { sha256 } from './sha256-mbp.js'
8
+ import * as ascon from './ascon.js'
9
9
 
10
10
  Boho.RAND = RAND;
11
11
  Boho.BohoMsg = BohoMsg;
12
- Boho.Meta = Meta;
13
12
  Boho.MetaSize = MetaSize;
14
- Boho.sha256 = sha256;
13
+ Boho.deriveKey = deriveKey;
14
+ Boho.ascon = ascon; // Ascon-AEAD128, Hash256, XOF128, CXOF128 (NIST SP 800-232)
15
+ Boho.sha256 = sha256; // SHA-256 and standard HMAC utilities (not used by the protocol)
15
16
  Boho.MBP = MBP;
16
17
  Boho.Buffer = Buffer;
17
18
 
@@ -21,18 +22,8 @@ Boho.Buffer = Buffer;
21
22
  */
22
23
 
23
24
  /**
24
- * @typedef {import('./boho.js').Boho} Boho
25
- * @typedef {import('./boho.js').RAND} RAND
26
- * @typedef {import('./boho.js').BohoMsg} BohoMsg
27
- * @typedef {import('./boho.js').Meta} Meta
28
- * @typedef {import('./boho.js').MetaSize} MetaSize
29
- * @typedef {import('./boho.js').sha256} sha256
30
- * @typedef {import('./boho.js').MBP} MBP
31
- * @typedef {import('./boho.js').Buffer} Buffer
32
- */
33
-
34
- /**
35
- * Default export object of boho
36
- * @type {Boho & { RAND: typeof RAND, BohoMsg: typeof BohoMsg, Meta: typeof Meta, MetaSize: typeof MetaSize, sha256: typeof sha256, MBP: typeof MBP, Buffer: typeof Buffer }}
25
+ * Default export: the Boho class with its helpers.
26
+ * @type {typeof Boho & { RAND: typeof RAND, BohoMsg: typeof BohoMsg, MetaSize: typeof MetaSize,
27
+ * deriveKey: typeof deriveKey, ascon: typeof ascon, sha256: typeof sha256, MBP: typeof MBP, Buffer: typeof Buffer }}
37
28
  */
38
- export default Boho;
29
+ export default Boho;
@@ -0,0 +1,225 @@
1
+ // Ascon prototype tests: official NIST SP 800-232 KATs and a cross-check with the
2
+ // Arduino C++ Ascon (BohoAscon.cpp in the IOSignal Arduino library).
3
+ // Run: npm run test:ascon
4
+ import { before, after, describe, it } from 'node:test'
5
+ import assert from 'node:assert/strict'
6
+ import { spawnSync } from 'node:child_process'
7
+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
8
+ import { randomBytes } from 'node:crypto'
9
+ import { tmpdir } from 'node:os'
10
+ import { join, resolve } from 'node:path'
11
+ import { fileURLToPath } from 'node:url'
12
+ import * as ascon from '../src/ascon.js'
13
+
14
+ const hex = b => Buffer.from(b).toString('hex').toUpperCase()
15
+ const unhex = h => new Uint8Array(Buffer.from(h, 'hex'))
16
+
17
+ // Records copied from the ascon-c reference repository:
18
+ // crypto_aead/asconaead128/LWC_AEAD_KAT_128_128.txt
19
+ const KEY = '000102030405060708090A0B0C0D0E0F'
20
+ const NONCE = '101112131415161718191A1B1C1D1E1F'
21
+ const AEAD = [ // Count, PT, AD, CT||tag
22
+ [1, '', '', '4F9C278211BEC9316BF68F46EE8B2EC6'],
23
+ [2, '', '30', 'CCCB674FE18A09A285D6AB11B35675C0'],
24
+ [17, '', '303132333435363738393A3B3C3D3E3F', 'E4230CDB8330EE9DC0CFD7C7B346E6DC'],
25
+ [33, '', '303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F', 'EFC3E78B02AD9A80A6F0548C5B0BB5BA'],
26
+ [34, '20', '', 'E8DD576ABA1CD3E6FC704DE02AEDB79588'],
27
+ [50, '20', '303132333435363738393A3B3C3D3E3F', '638BBACE2C82A050832E46B3224A9552A0'],
28
+ [100, '202122', '', 'E8C3DEAF8E12816B8EDF39AD1571A9492B7CA2'],
29
+ [290, '2021222324252627', '303132333435363738393A3B3C3D3E3F404142434445464748',
30
+ '16CB13E5853541E2B38396BE456C486F26932ED701D9ADA8'],
31
+ [512, '202122232425262728292A2B2C2D2E', '303132333435363738393A3B3C3D3E3F',
32
+ '6373EBB28BE97C9BAC090CF399C13E646BE0C80B0404770341EB48D6178948'],
33
+ [1089, '202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F',
34
+ '303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F',
35
+ 'CB34D04660A66DBFBE9C856601F5B8AA51A499B55AC8F7FBEFBC331A613EE9CDFD191750A47F211C0A15ED28173D7CAA']
36
+ ]
37
+ // crypto_hash/asconhash256/LWC_HASH_KAT_128_256.txt
38
+ const HASH = [
39
+ [1, '', '0B3BE5850F2F6B98CAF29F8FDEA89B64A1FA70AA249B8F839BD53BAA304D92B2'],
40
+ [2, '00', '0728621035AF3ED2BCA03BF6FDE900F9456F5330E4B5EE23E7F6A1E70291BC80'],
41
+ [9, '0001020304050607', 'B88E497AE8E6FB641B87EF622EB8F2FCA0ED95383F7FFEBE167ACF1099BA764F'],
42
+ [17, '000102030405060708090A0B0C0D0E0F', '3158C1940A2FBADBD68AB661777859B94A689E4EFC375911467ADDD641835C38'],
43
+ [33, '000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F',
44
+ 'BD9D3D60A66B53868EAB2A5C74539A518A1F60F01EB176C60E43DEE81680B33E'],
45
+ [65, '000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F' +
46
+ '202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F',
47
+ 'A6F241BEA5D16405812C06019D9F72D60132BD7C089C60549B2E56BB01C64F48']
48
+ ]
49
+ // crypto_hash/asconxof128/LWC_XOF_KAT_128_512.txt
50
+ const XOF = [
51
+ [1, '', '473D5E6164F58B39DFD84AACDB8AE42EC2D91FED33388EE0D960D9B3993295C6' +
52
+ 'AD77855A5D3B13FE6AD9E6098988373AF7D0956D05A8F1665D2C67D1A3AD10FF'],
53
+ [2, '00', '51430E0438ECDF642B393630D977625F5F337656BA58AB1E960784AC32A16E0D' +
54
+ '446405551F5469384F8EA283CF12E64FA72C426BFEBAEA3AA1529E2C4AB23A2F'],
55
+ [9, '0001020304050607', '8D1886F5D3EC4AF8D15B44BC62B74DA6EA91BC28FB82F9C34079B5ED6E38B6C9' +
56
+ '51803D7DFB3C5E512A0EF5E4060062A6FD067F9C73EF9BEE527411BDA67FC896'],
57
+ [17, '000102030405060708090A0B0C0D0E0F', '10BFEDC5F6442D3E1D8C324878CE1DDF73B01CAFC365589283AC4CBB98E48DE3' +
58
+ 'CEDA8A41BB0983D539E4D90F6458C5C781724FAD641ED3CDB4779931097440B3'],
59
+ [33, '000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F',
60
+ '2E5F3403F4171471CC7934B51982CECE8D6628435DB70E89880F3BE4E0B7B052' +
61
+ '32DFE63C44A836D771337C9C5A2688D1B71ECABE0D5C2006FEF36EF3186138AD']
62
+ ]
63
+
64
+ // crypto_cxof/asconcxof128/LWC_CXOF_KAT_128_512.txt: Count, Msg, Z, MD
65
+ const CXOF = [
66
+ [1, '', '', '4F50159EF70BB3DAD8807E034EAEBD44C4FA2CBBC8CF1F05511AB66CDCC52990' +
67
+ '5CA12083FC186AD899B270B1473DC5F7EC88D1052082DCDFE69FB75D269E7B74'],
68
+ [2, '', '10', '0C93A483E7D574D49FE52CCE03EE646117977D57A8AA57704AB4DAF44B501430' +
69
+ 'FF6AC11A5D1FD6F2154B5C65728268270C8BB578508487B8965718ADA6272FD6'],
70
+ [3, '', '1011', 'D1106C7622E79FE955BD9D79E03B918E770FE0E0CDDDE28BEB924B02C5FC936B' +
71
+ '33ACCA299C89ECA5D71886CBBFA4D54A21C55FDE2B679F5E2488063A1719DC32'],
72
+ [18, '', '101112131415161718191A1B1C1D1E1F20', 'F74D02F0215E2C5E71A89E2315A533F64843223A368DF68B0F2D3603BDBA664F' +
73
+ '2297ABD5EA4EDF25004D7C7E1093C53212EB7C231A6142AA9FBE3A74CFF7A378'],
74
+ [34, '00', '', '7F0C0DDD4BC9603DEED19510CDB954D65CF254F59234BFBF5A730D03D2712DAA' +
75
+ 'B9161C6553F65FA72A25B3174AC13A33218C393577A85B6D6F4319D1EF8A7541'],
76
+ [232, '00010203040506', '', 'AA04B2E280D626F649EBC9E6E09BDCB1ED4B4669647FA727064ECE4C913E2D62' +
77
+ 'F380F31B1B4EB19AB61C77BB49F533DF1E4FDDBA97CDE8315411A85A178E940B'],
78
+ [307, '000102030405060708', '101112131415161718', '75BA4455E500E37946C81FDDF6A5E168A94F18D1B31C7927D109736A8A33887E' +
79
+ '3D7E189E569ACD8508F075E06E89C72877AFB39133EFE2A518DF33BD6D2499CA']
80
+ ]
81
+
82
+ describe('Ascon KAT (NIST SP 800-232)', () => {
83
+ for (const [count, pt, ad, ct] of AEAD) {
84
+ it(`AEAD128 Count ${count}`, () => {
85
+ const key = unhex(KEY); const nonce = unhex(NONCE)
86
+ assert.equal(hex(ascon.encrypt(key, nonce, unhex(pt), unhex(ad))), ct)
87
+ assert.equal(hex(ascon.decrypt(key, nonce, unhex(ct), unhex(ad))), pt)
88
+ })
89
+ }
90
+ for (const [count, msg, md] of HASH) {
91
+ it(`Hash256 Count ${count}`, () => assert.equal(hex(ascon.hash256(unhex(msg))), md))
92
+ }
93
+ for (const [count, msg, md] of XOF) {
94
+ it(`XOF128 Count ${count}`, () => {
95
+ assert.equal(hex(ascon.xof128(unhex(msg), 64)), md)
96
+ for (const n of [0, 1, 7, 8, 9, 31, 33]) assert.equal(hex(ascon.xof128(unhex(msg), n)), md.slice(0, 2 * n))
97
+ })
98
+ }
99
+ })
100
+
101
+ describe('Ascon CXOF128', () => {
102
+ for (const [count, msg, z, md] of CXOF) {
103
+ it(`KAT Count ${count}`, () => {
104
+ assert.equal(hex(ascon.cxof128(unhex(msg), 64, unhex(z))), md)
105
+ for (const n of [0, 1, 8, 9, 33]) assert.equal(hex(ascon.cxof128(unhex(msg), n, unhex(z))), md.slice(0, 2 * n))
106
+ })
107
+ }
108
+ it('differs from XOF128 and refuses a customization string over 256 bytes', () => {
109
+ assert.notEqual(hex(ascon.cxof128('', 32, '')), hex(ascon.xof128('', 32)))
110
+ assert.equal(ascon.cxof128('a', 16, new Uint8Array(256)).length, 16)
111
+ assert.throws(() => ascon.cxof128('a', 16, new Uint8Array(257)), RangeError)
112
+ })
113
+ })
114
+
115
+ describe('Ascon AEAD128 behaviour', () => {
116
+ const key = unhex(KEY); const nonce = unhex(NONCE)
117
+ const [, pt, ad, ct] = AEAD.at(-1)
118
+
119
+ it('rejects changed tag, ciphertext, AD, nonce and key', () => {
120
+ const sealed = unhex(ct)
121
+ const flip = (b, i) => { const c = b.slice(); c[i] ^= 1; return c }
122
+ assert.equal(ascon.decrypt(key, nonce, flip(sealed, sealed.length - 1), unhex(ad)), null)
123
+ assert.equal(ascon.decrypt(key, nonce, flip(sealed, 0), unhex(ad)), null)
124
+ assert.equal(ascon.decrypt(key, nonce, sealed, flip(unhex(ad), 3)), null)
125
+ assert.equal(ascon.decrypt(key, flip(nonce, 15), sealed, unhex(ad)), null)
126
+ assert.equal(ascon.decrypt(flip(key, 0), nonce, sealed, unhex(ad)), null)
127
+ assert.equal(ascon.decrypt(key, nonce, sealed.subarray(0, 15), unhex(ad)), null)
128
+ })
129
+
130
+ it('truncated tags are prefixes of the full tag', () => {
131
+ const sealed8 = ascon.encrypt(key, nonce, unhex(pt), unhex(ad), 8)
132
+ assert.equal(hex(sealed8), ct.slice(0, 2 * (32 + 8)))
133
+ assert.equal(hex(ascon.decrypt(key, nonce, sealed8, unhex(ad), 8)), pt)
134
+ assert.throws(() => ascon.encrypt(key, nonce, '', '', 3), RangeError)
135
+ assert.throws(() => ascon.decrypt(key, nonce, sealed8, '', 17), RangeError)
136
+ })
137
+
138
+ it('accepts strings and typed arrays, checks key and nonce sizes', () => {
139
+ const a = ascon.encrypt(key, nonce, 'hello', 'hdr')
140
+ const b = ascon.encrypt(key.buffer, new Uint16Array(nonce.buffer), Buffer.from('hello'), Buffer.from('hdr'))
141
+ assert.deepEqual(a, b)
142
+ assert.equal(new TextDecoder().decode(ascon.decrypt(key, nonce, a, 'hdr')), 'hello')
143
+ assert.throws(() => ascon.encrypt(key.subarray(1), nonce, ''), RangeError)
144
+ assert.throws(() => ascon.encrypt(key, nonce.subarray(1), ''), RangeError)
145
+ assert.throws(() => ascon.encrypt(key, nonce, 12), TypeError)
146
+ })
147
+
148
+ it('round-trips every length 0..80 with AD lengths 0..40', () => {
149
+ const data = randomBytes(80)
150
+ for (let n = 0; n <= 80; n++) {
151
+ for (let a = 0; a <= 40; a += 5) {
152
+ const sealed = ascon.encrypt(key, nonce, data.subarray(0, n), data.subarray(0, a))
153
+ assert.deepEqual(ascon.decrypt(key, nonce, sealed, data.subarray(0, a)), new Uint8Array(data.subarray(0, n)))
154
+ }
155
+ }
156
+ })
157
+ })
158
+
159
+ // Cross-check with the Arduino C++ prototype on random inputs.
160
+ const directory = fileURLToPath(new URL('.', import.meta.url))
161
+ const prototype = process.env.BOHO_ARDUINO_SRC || resolve(directory, '../../iosignal-arduino/src')
162
+ const cppHost = String.raw`
163
+ #include "BohoAscon.h"
164
+ #include <cstdio>
165
+ #include <cstring>
166
+ #include <vector>
167
+ static std::vector<uint8_t> readHex() {
168
+ char text[4096]; if (std::scanf("%4095s", text) != 1) return {};
169
+ std::vector<uint8_t> v; if (!std::strcmp(text, "-")) return v;
170
+ for (size_t i = 0; text[i] && text[i + 1]; i += 2) { unsigned x; std::sscanf(text + i, "%2x", &x); v.push_back((uint8_t)x); }
171
+ return v;
172
+ }
173
+ static void printHex(const uint8_t *p, size_t n) { for (size_t i = 0; i < n; ++i) std::printf("%02X", p[i]); std::printf("\n"); }
174
+ int main() {
175
+ char op[8];
176
+ while (std::scanf("%7s", op) == 1) {
177
+ if (op[0] == 'E') { // E key nonce ad pt -> ct||tag
178
+ auto k = readHex(), n = readHex(), a = readHex(), p = readHex();
179
+ std::vector<uint8_t> out(p.size() + 16);
180
+ ascon_aead128_encrypt(out.data(), out.data() + p.size(), p.data(), p.size(), a.data(), a.size(), k.data(), n.data());
181
+ printHex(out.data(), out.size());
182
+ } else if (op[0] == 'D') { // D key nonce ad ct||tag -> pt or FAIL
183
+ auto k = readHex(), n = readHex(), a = readHex(), c = readHex();
184
+ size_t len = c.size() - 16; std::vector<uint8_t> out(len + 1);
185
+ if (ascon_aead128_decrypt(out.data(), c.data(), len, a.data(), a.size(), c.data() + len, 16, k.data(), n.data())) printHex(out.data(), len);
186
+ else std::printf("FAIL\n");
187
+ } else if (op[0] == 'H') { auto m = readHex(); uint8_t d[32]; ascon_hash256(d, m.data(), m.size()); printHex(d, 32); }
188
+ else if (op[0] == 'C') { unsigned len; auto m = readHex(); auto z = readHex(); std::scanf("%u", &len); std::vector<uint8_t> o(len + 1); ascon_cxof128(o.data(), len, m.data(), m.size(), z.data(), z.size()); printHex(o.data(), len); }
189
+ else if (op[0] == 'X') { unsigned len; auto m = readHex(); std::scanf("%u", &len); std::vector<uint8_t> o(len + 1); ascon_xof128(o.data(), len, m.data(), m.size()); printHex(o.data(), len); }
190
+ }
191
+ }
192
+ `
193
+
194
+ describe('JS ↔ Arduino C++ Ascon', { skip: !existsSync(join(prototype, 'BohoAscon.cpp')) && 'Arduino BohoAscon.cpp not found: set BOHO_ARDUINO_SRC' }, () => {
195
+ let build, executable
196
+ before(() => {
197
+ build = mkdtempSync(join(tmpdir(), 'boho-ascon-'))
198
+ executable = join(build, 'ascon-host')
199
+ writeFileSync(join(build, 'host.cpp'), cppHost)
200
+ const result = spawnSync('c++', ['-std=c++17', '-O1', '-I', prototype, join(build, 'host.cpp'),
201
+ join(prototype, 'BohoAscon.cpp'), '-o', executable], { encoding: 'utf8', timeout: 60000 })
202
+ assert.equal(result.status, 0, result.stderr || String(result.error))
203
+ })
204
+ after(() => { if (build) rmSync(build, { recursive: true, force: true }) })
205
+
206
+ it('agrees on 300 random AEAD, hash, XOF and CXOF cases in both directions', () => {
207
+ const arg = b => (b.length ? hex(b) : '-')
208
+ const lines = []; const expected = []
209
+ for (let i = 0; i < 300; i++) {
210
+ const key = randomBytes(16); const nonce = randomBytes(16)
211
+ const ad = randomBytes(i % 37); const pt = randomBytes((i * 7) % 101)
212
+ const sealed = ascon.encrypt(key, nonce, pt, ad)
213
+ lines.push(`E ${arg(key)} ${arg(nonce)} ${arg(ad)} ${arg(pt)}`); expected.push(hex(sealed))
214
+ lines.push(`D ${arg(key)} ${arg(nonce)} ${arg(ad)} ${arg(sealed)}`); expected.push(pt.length ? hex(pt) : '')
215
+ const bad = Uint8Array.from(sealed); bad[i % bad.length] ^= 0x40
216
+ lines.push(`D ${arg(key)} ${arg(nonce)} ${arg(ad)} ${arg(bad)}`); expected.push('FAIL')
217
+ lines.push(`H ${arg(pt)}`); expected.push(hex(ascon.hash256(pt)))
218
+ lines.push(`X ${arg(ad)} ${i % 70}`); expected.push(hex(ascon.xof128(ad, i % 70)))
219
+ lines.push(`C ${arg(pt)} ${arg(ad)} ${i % 50}`); expected.push(hex(ascon.cxof128(pt, i % 50, ad)))
220
+ }
221
+ const run = spawnSync(executable, [], { input: lines.join('\n') + '\n', encoding: 'utf8', timeout: 60000 })
222
+ assert.equal(run.status, 0, run.stderr)
223
+ assert.deepEqual(run.stdout.split('\n').slice(0, expected.length), expected)
224
+ })
225
+ })
@@ -0,0 +1,190 @@
1
+ // The Boho class (src/boho.js, the package's default export) against the shared vectors,
2
+ // JS client ↔ JS server, and the JS server ↔ the Arduino C++ Boho class.
3
+ import { before, after, describe, it } from 'node:test'
4
+ import assert from 'node:assert/strict'
5
+ import { spawn, spawnSync } from 'node:child_process'
6
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
7
+ import { tmpdir } from 'node:os'
8
+ import { join, resolve } from 'node:path'
9
+ import { fileURLToPath } from 'node:url'
10
+ import readline from 'node:readline'
11
+ import Default from '../src/index.js'
12
+ import Dist from '../dist/boho.js'
13
+ import { Boho, BohoMsg, deriveKey } from '../src/boho.js'
14
+
15
+ const hex = b => Buffer.from(b).toString('hex')
16
+ const unhex = h => new Uint8Array(Buffer.from(h, 'hex'))
17
+ const vectors = JSON.parse(readFileSync(new URL('./fixtures/boho-vectors.json', import.meta.url), 'utf8'))
18
+
19
+ function loggedIn (login = vectors.logins[0]) {
20
+ const client = new Boho(); client.set_id8(login.id); client.set_key(login.key)
21
+ const server = new Boho(); server.copy_key(deriveKey(login.key))
22
+ const req = client.auth_req(unhex(login.challenge), unhex(login.clientNonce))
23
+ const res = server.verify_auth_req(req, unhex(login.challenge))
24
+ assert.ok(res && client.verify_auth_res(res))
25
+ return { client, server, req, res }
26
+ }
27
+
28
+ describe('Boho class', () => {
29
+ it('is exported from the package and the build', () => {
30
+ assert.equal(Default, Boho)
31
+ assert.equal(typeof Dist, 'function')
32
+ assert.equal(Dist.deriveKey('x').length, 16)
33
+ assert.equal(Default.BohoMsg.ENC, 0xbb)
34
+ assert.equal(Default.BohoMsg[0xb4], 'AUTH_REQ')
35
+ assert.equal(Default.MetaSize.ENC_PACK, 29)
36
+ assert.equal(typeof Default.ascon.cxof128, 'function')
37
+ assert.equal(Default.RAND(5).length, 5)
38
+ })
39
+
40
+ it('keys and logins match the vectors on both sides', () => {
41
+ for (const k of vectors.keys) assert.equal(hex(deriveKey(k.key)), k.derived)
42
+ for (const l of vectors.logins) {
43
+ const { client, server, req, res } = loggedIn(l)
44
+ assert.equal(hex(req), l.authReq)
45
+ assert.equal(hex(res), l.authRes)
46
+ assert.ok(client.isAuthorized && server.isAuthorized)
47
+ }
48
+ })
49
+
50
+ it('the client opens server messages of the vectors and refuses the invalid ones', () => {
51
+ const { client, server } = loggedIn()
52
+ for (const m of vectors.messages) {
53
+ const side = m.dir === 2 ? client : server
54
+ const opened = side.decrypt_session(unhex(m.packet))
55
+ assert.equal(hex(opened), m.plaintext)
56
+ }
57
+ for (const c of vectors.invalid.filter(c => c.kind === 'message')) {
58
+ const login = vectors.logins.find(l => l.sessionKey === c.sessionKey)
59
+ const pair = login === vectors.logins[0] ? { client, server } : loggedIn(login)
60
+ const side = c.dir === 2 ? pair.client : pair.server
61
+ assert.equal(side.decrypt_session(unhex(c.packet)), undefined, c.reason)
62
+ }
63
+ })
64
+
65
+ it('packs of the vectors open, the invalid ones do not', () => {
66
+ const b = new Boho()
67
+ for (const p of vectors.packs) assert.equal(hex(b.decrypt_e2e(unhex(p.packet), p.key).data), p.plaintext)
68
+ for (const c of vectors.invalid.filter(c => c.kind === 'pack')) assert.equal(b.decrypt_e2e(unhex(c.packet), c.key), undefined, c.reason)
69
+ })
70
+
71
+ it('refuses wrong logins', () => {
72
+ const l = vectors.logins[0]
73
+ for (const c of vectors.invalid.filter(c => c.kind === 'authReq')) {
74
+ const server = new Boho(); server.copy_key(deriveKey(c.key))
75
+ assert.equal(server.verify_auth_req(unhex(c.packet), unhex(c.challenge)), false, c.reason)
76
+ assert.equal(server.isAuthorized, false)
77
+ }
78
+ for (const c of vectors.invalid.filter(c => c.kind === 'authRes')) {
79
+ const client = new Boho(); client.set_id8(l.id); client.set_key(l.key)
80
+ client.auth_req(unhex(l.challenge), unhex(l.clientNonce))
81
+ assert.equal(client.verify_auth_res(unhex(c.packet)), undefined, c.reason)
82
+ }
83
+ const bad = unhex(l.challenge); bad[5] = 0xe8; bad[6] = 0x03
84
+ assert.equal(new Boho().auth_req(bad), false)
85
+ const c = new Boho(); c.set_id_key('dev1.secret')
86
+ assert.equal(c.auth_req(bad), false)
87
+ assert.ok(c.auth_req(unhex(l.challenge))) // random nonce
88
+ })
89
+
90
+ it('JS client ↔ JS server: messages both ways, E2E header, strictly increasing clock', () => {
91
+ const { client, server } = loggedIn()
92
+ let last = -1n
93
+ for (let n = 0; n < 50; n++) {
94
+ const data = Buffer.from(Array.from({ length: n }, (_, i) => i))
95
+ const up = client.encrypt_session(data)
96
+ assert.equal(up.length, 21 + n)
97
+ assert.equal(hex(server.decrypt_session(up)), hex(data))
98
+ assert.equal(server.decrypt_session(up.subarray(0, up.length - 1)), undefined)
99
+ const down = server.encrypt_session(data)
100
+ assert.equal(hex(client.decrypt_session(down)), hex(data))
101
+ assert.equal(client.decrypt_session(up), undefined, 'own direction refused')
102
+ const view = new DataView(up.buffer, up.byteOffset)
103
+ const tuple = (BigInt(view.getUint32(5, true)) * 1000n + BigInt(view.getUint16(9, true))) * 65536n + BigInt(view.getUint16(11, true))
104
+ assert.ok(tuple > last); last = tuple
105
+ }
106
+ const head = client.encrypt_session(Buffer.from([0xd2, 1, 0x78]), BohoMsg.ENC_E2E)
107
+ const body = client.encrypt_e2e('hello', 'e2e-key')
108
+ const packet = Buffer.concat([head, body])
109
+ assert.deepEqual([...server.decrypt_session(packet)], [0xd2, 1, 0x78])
110
+ assert.equal(server.decrypt_e2e(packet.subarray(21 + 3), 'e2e-key').data.toString(), 'hello')
111
+ assert.equal(client.encrypt_session('x', 0xb8), undefined)
112
+ client.set_key('other')
113
+ assert.equal(client.encrypt_session('x'), undefined, 'new key ends the session')
114
+ })
115
+ })
116
+
117
+ // JS server ↔ the Arduino C++ Boho class (host build).
118
+ const directory = fileURLToPath(new URL('.', import.meta.url))
119
+ // The Arduino Boho is part of the IOSignal Arduino library (iosignal-arduino/src) since Boho 3.
120
+ const src = process.env.BOHO_ARDUINO_SRC || resolve(directory, '../../iosignal-arduino/src')
121
+ const host = String.raw`
122
+ #include "Boho.h"
123
+ #include <cstdio>
124
+ #include <string>
125
+ #include <vector>
126
+ uint32_t millis() { static uint32_t t = 0; return t += 3; }
127
+ uint32_t micros() { static uint32_t t = 0; return t += 17; }
128
+ static std::vector<uint8_t> hex(const char *s) { std::vector<uint8_t> v; unsigned x; while (s[0] && s[1] && std::sscanf(s, "%2x", &x) == 1) { v.push_back(x); s += 2; } return v; }
129
+ static void put(const uint8_t *p, size_t n) { for (size_t i = 0; i < n; ++i) std::printf("%02x", p[i]); std::printf("\n"); std::fflush(stdout); }
130
+ int main() {
131
+ Boho b; char op[16]; static char arg[8192];
132
+ while (std::scanf("%15s %8191s", op, arg) == 2) {
133
+ std::string o(op); auto in = hex(strcmp(arg, "-") ? arg : "");
134
+ std::vector<uint8_t> out(in.size() + 64);
135
+ if (o == "IDKEY") { b.set_id_key(arg); std::printf("ok\n"); std::fflush(stdout); }
136
+ else if (o == "AUTH") { int n = b.auth_req(out.data(), in.data(), in.size()); put(out.data(), n); }
137
+ else if (o == "RES") { std::printf(b.verify_auth_res(in.data(), in.size()) ? "ok\n" : "fail\n"); std::fflush(stdout); }
138
+ else if (o == "SEND" || o == "SENDE2E") { uint32_t n = b.encrypt_session(out.data(), in.data(), in.size(), o == "SEND" ? Boho::ENC : Boho::ENC_E2E); put(out.data(), n); }
139
+ else if (o == "OPEN") { uint32_t n; if (b.decrypt_session(out.data(), in.data(), in.size(), n)) put(out.data(), n); else { std::printf("fail\n"); std::fflush(stdout); } }
140
+ else if (o == "PACK") { uint32_t n = b.encrypt_e2e(out.data(), in.data(), in.size(), "e2e-key"); put(out.data(), n); }
141
+ else if (o == "UNPACK") { uint32_t n; if (b.decrypt_e2e(out.data(), in.data(), in.size(), "e2e-key", n)) put(out.data(), n); else { std::printf("fail\n"); std::fflush(stdout); } }
142
+ }
143
+ }
144
+ `
145
+
146
+ describe('JS server ↔ Arduino C++ Boho', { skip: !existsSync(join(src, 'BohoAscon.cpp')) && 'Arduino Boho (Ascon) not found: set BOHO_ARDUINO_SRC' }, () => {
147
+ let build, executable
148
+ before(() => {
149
+ build = mkdtempSync(join(tmpdir(), 'boho-host-'))
150
+ executable = join(build, 'host')
151
+ writeFileSync(join(build, 'Arduino.h'), '#pragma once\n#include <cstdint>\n#include <cstddef>\n#include <cstring>\nuint32_t millis();\nuint32_t micros();\n')
152
+ writeFileSync(join(build, 'host.cpp'), host)
153
+ const r = spawnSync('c++', ['-std=c++17', '-O1', '-I', build, '-I', src, join(build, 'host.cpp'),
154
+ join(src, 'Boho.cpp'), join(src, 'BohoAscon.cpp'), '-o', executable], { encoding: 'utf8', timeout: 60000 })
155
+ assert.equal(r.status, 0, r.stderr || String(r.error))
156
+ })
157
+ after(() => { if (build) rmSync(build, { recursive: true, force: true }) })
158
+
159
+ it('logs in with a random nonce and exchanges ENC, ENC_E2E and ENC_PACK both ways', async () => {
160
+ const child = spawn(executable, [], { stdio: ['pipe', 'pipe', 'inherit'] })
161
+ const lines = readline.createInterface({ input: child.stdout })[Symbol.asyncIterator]()
162
+ const ask = async (op, arg = '-') => { const next = lines.next(); child.stdin.write(`${op} ${arg}\n`); return (await next).value }
163
+ try {
164
+ const server = new Boho(); server.copy_key(deriveKey('shared-secret'))
165
+ const challenge = server.server_time_nonce()
166
+ assert.equal(await ask('IDKEY', 'dev7.shared-secret'), 'ok')
167
+ const req = unhex(await ask('AUTH', hex(challenge)))
168
+ assert.equal(req.length, 33)
169
+ const res = server.verify_auth_req(req)
170
+ assert.ok(res, 'server accepts the Arduino login')
171
+ assert.equal(Buffer.from(req.subarray(1, 9)).toString().replace(/\0+$/, ''), 'dev7')
172
+ assert.equal(await ask('RES', hex(res)), 'ok')
173
+ for (const size of [0, 1, 15, 16, 17, 59, 200]) {
174
+ const data = Buffer.from(Array.from({ length: size }, (_, i) => (i * 7) & 255))
175
+ const up = unhex(await ask('SEND', hex(data) || '-'))
176
+ assert.equal(hex(server.decrypt_session(up)), hex(data))
177
+ const down = server.encrypt_session(data)
178
+ assert.equal(await ask('OPEN', hex(down)), hex(data))
179
+ }
180
+ const head = unhex(await ask('SENDE2E', 'd20178'))
181
+ assert.equal(hex(server.decrypt_session(head)), 'd20178')
182
+ const pack = unhex(await ask('PACK', hex(Buffer.from('on=1'))))
183
+ assert.equal(server.decrypt_e2e(pack, 'e2e-key').data.toString(), 'on=1')
184
+ assert.equal(await ask('UNPACK', hex(server.encrypt_e2e('off', 'e2e-key'))), hex(Buffer.from('off')))
185
+ const forged = server.encrypt_session('x'); forged[14] ^= 1
186
+ assert.equal(await ask('OPEN', hex(forged)), 'fail')
187
+ assert.equal(await ask('RES', hex(res)), 'fail', 'AUTH_RES only once')
188
+ } finally { child.stdin.end(); child.kill(); await lines.return() }
189
+ })
190
+ })