@hpke/chacha20poly1305
Version:
A Hybrid Public Key Encryption (HPKE) module extension for ChaCha20/Poly1305
96 lines (95 loc) • 2.73 kB
JavaScript
import { chacha20poly1305 } from "@noble/ciphers/chacha";
import { AeadId } from "@hpke/common";
export class Chacha20Poly1305Context {
constructor(key) {
Object.defineProperty(this, "_key", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this._key = new Uint8Array(key);
}
async seal(iv, data, aad) {
return await this._seal(iv, data, aad);
}
async open(iv, data, aad) {
return await this._open(iv, data, aad);
}
_seal(iv, data, aad) {
return new Promise((resolve) => {
const ret = chacha20poly1305(this._key, new Uint8Array(iv), new Uint8Array(aad)).encrypt(new Uint8Array(data));
resolve(ret.buffer);
});
}
_open(iv, data, aad) {
return new Promise((resolve) => {
const ret = chacha20poly1305(this._key, new Uint8Array(iv), new Uint8Array(aad)).decrypt(new Uint8Array(data));
resolve(ret.buffer);
});
}
}
/**
* The ChaCha20Poly1305 for HPKE AEAD implementing {@link AeadInterface}.
*
* When using `@hpke/core`, the instance of this class can be specified
* to the `aead` parameter of {@link CipherSuiteParams} instead of `AeadId.Chacha20Poly1305`
* as follows:
*
* @example
*
* ```ts
* import {
* CipherSuite,
* DhkemP256HkdfSha256,
* HkdfSha256,
* } from "@hpke/core";
* import {
* Chacha20Poly1305,
* } from "@hpke/chacha20poly1305";
*
* const suite = new CipherSuite({
* kem: new DhkemP256HkdfSha256(),
* kdf: new HkdfSha256(),
* aead: new Chacha20Poly1305(),
* });
* ```
*
* This class is implemented using
* {@link https://github.com/paulmillr/noble-ciphers | @noble/ciphers}.
*/
export class Chacha20Poly1305 {
constructor() {
/** AeadId.Chacha20Poly1305 (0x0003) */
Object.defineProperty(this, "id", {
enumerable: true,
configurable: true,
writable: true,
value: AeadId.Chacha20Poly1305
});
/** 32 */
Object.defineProperty(this, "keySize", {
enumerable: true,
configurable: true,
writable: true,
value: 32
});
/** 12 */
Object.defineProperty(this, "nonceSize", {
enumerable: true,
configurable: true,
writable: true,
value: 12
});
/** 16 */
Object.defineProperty(this, "tagSize", {
enumerable: true,
configurable: true,
writable: true,
value: 16
});
}
createEncryptionContext(key) {
return new Chacha20Poly1305Context(key);
}
}