@sebastianp265/safe-server-side-storage-client
Version:
Library for Confidential Server-Side Message Storage Using the Labyrinth Protocol
34 lines (33 loc) • 2.51 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.labyrinth_hpke_encrypt = labyrinth_hpke_encrypt;
exports.labyrinth_hpke_decrypt = labyrinth_hpke_decrypt;
const keys_1 = require("./keys");
const utils_1 = require("./utils");
const key_derivation_1 = require("./key-derivation");
const authenticated_symmetric_encryption_1 = require("./authenticated-symmetric-encryption");
function labyrinth_hpke_encrypt(recipient_enc_pub, sender_auth_pub, sender_auth_priv, psk, aad, plaintext) {
(0, utils_1.cryptoAssert)(psk.length === key_derivation_1.KEY_LENGTH_BYTES);
const { publicKey: pub_ephem, privateKey: priv_ephem } = (0, keys_1.generateKeyPair)();
const id_id = sender_auth_priv.agree(recipient_enc_pub);
const id_ephem = priv_ephem.agree(recipient_enc_pub);
const fresh_secret = (0, utils_1.concat)(id_id, id_ephem);
const inner_aad = (0, utils_1.concat)(Uint8Array.of(0x01), sender_auth_pub.getX25519PublicKeyBytes(), recipient_enc_pub.getX25519PublicKeyBytes(), pub_ephem.getX25519PublicKeyBytes(), aad);
const subkey = (0, key_derivation_1.kdfOneKey)(fresh_secret, psk, inner_aad);
const nonce = new Uint8Array(authenticated_symmetric_encryption_1.NONCE_LENGTH);
const ciphertext = (0, authenticated_symmetric_encryption_1.encrypt)(subkey, nonce, aad, plaintext);
return (0, utils_1.concat)(Uint8Array.of(0x01), pub_ephem.getEd25519PublicKeyBytes(), ciphertext);
}
function labyrinth_hpke_decrypt(recipient_enc_pub, recipient_enc_priv, sender_auth_pub, psk, aad, ciphertext) {
(0, utils_1.cryptoAssert)(psk.length === key_derivation_1.KEY_LENGTH_BYTES);
const use_case_byte = ciphertext.subarray(0, 1);
(0, utils_1.cryptoAssert)(use_case_byte.length == 1 && use_case_byte[0] == 0x01);
const pub_ephem = new keys_1.PublicKey(ciphertext.subarray(1, 1 + key_derivation_1.KEY_LENGTH_BYTES));
ciphertext = ciphertext.subarray(1 + key_derivation_1.KEY_LENGTH_BYTES);
const id_id = recipient_enc_priv.agree(sender_auth_pub);
const id_ephem = recipient_enc_priv.agree(pub_ephem);
const fresh_secret = (0, utils_1.concat)(id_id, id_ephem);
const inner_aad = (0, utils_1.concat)(Uint8Array.of(0x01), sender_auth_pub.getX25519PublicKeyBytes(), recipient_enc_pub.getX25519PublicKeyBytes(), pub_ephem.getX25519PublicKeyBytes(), aad);
const subkey = (0, key_derivation_1.kdfOneKey)(fresh_secret, psk, inner_aad);
return (0, authenticated_symmetric_encryption_1.decrypt)(subkey, aad, ciphertext);
}