Switch to XChaCha20-Poly1305

This commit is contained in:
2021-07-23 10:35:49 -05:00
parent 43335584c5
commit 7fe1420876
5 changed files with 26 additions and 342 deletions

View File

@@ -3,7 +3,6 @@ import { Int64BE, Uint64BE } from 'int64-buffer';
import crypto from 'crypto';
import { TextEncoder } from 'text-encoding';
import { getCustomEncryption } from '../utils/constants';
import {
be_ui8_array_to_i16,
be_ui8_array_to_i32,
@@ -18,14 +17,13 @@ import {
ui8_array_to_ui8,
ui8_to_ui8_array,
} from '../utils/byte_order';
import JSChaCha20 from '../utils/jschacha20';
import {XChaCha20Poly1305} from '@stablelib/xchacha20poly1305';
export default class packet {
constructor(token) {
this.token = token;
}
static HEADER_STRING = 'repertory';
static HEADER = new TextEncoder().encode(this.HEADER_STRING);
buffer = null;
@@ -164,7 +162,8 @@ export default class packet {
hash = hash.update(new TextEncoder().encode(this.token));
const key = Uint8Array.from(hash.digest());
const nonce = this.buffer.slice(0, 12);
const nonce = this.buffer.slice(0, 24);
const mac = this.buffer.slice(24, 16);
const customEncryption = getCustomEncryption();
if (customEncryption) {
@@ -172,23 +171,18 @@ export default class packet {
await customEncryption.decrypt(
Buffer.from(key).toString('base64'),
Buffer.from(nonce).toString('base64'),
Buffer.from(this.buffer.slice(12)).toString('base64')
Buffer.from(mac).toString('base64'),
Buffer.from(this.buffer.slice(40)).toString('base64')
),
'base64'
);
} else {
const aad = ui32_to_be_ui8_array(this.buffer.length);
this.buffer = Buffer.from(
new JSChaCha20(key, nonce, 0).decrypt(this.buffer.slice(12))
new XChaCha20Poly1305(key).open(nonce, this.buffer.slice(24), aad),
);
}
this.decode_offset = packet.HEADER.length;
const header = this.buffer.slice(0, 9);
if (header.toString() !== packet.HEADER_STRING) {
return Promise.reject(new Error('Header does not match'));
}
this.buffer = new Uint8Array(this.buffer);
return this.buffer;
} catch (e) {
@@ -284,13 +278,12 @@ export default class packet {
encrypt = async (nonce) => {
try {
this.push_buffer(packet.HEADER);
let hash = crypto.createHash('sha256');
hash = hash.update(new TextEncoder().encode(this.token));
const key = Uint8Array.from(hash.digest());
if (!nonce) {
nonce = Uint8Array.from(randomBytes(12));
nonce = Uint8Array.from(randomBytes(24));
}
const customEncryption = getCustomEncryption();
@@ -306,9 +299,10 @@ export default class packet {
)
);
} else {
this.buffer = new JSChaCha20(key, nonce, 0).encrypt(this.buffer);
const aad = ui32_to_be_ui8_array(this.buffer.length + 40)
this.buffer = new XChaCha20Poly1305(key).seal(nonce, this.buffer, aad);
this.push_buffer(nonce);
}
this.push_buffer(nonce);
return this.buffer;
} catch (e) {