diff --git a/src/xx.ts b/src/xx.ts index 23a6f80..261c692 100644 --- a/src/xx.ts +++ b/src/xx.ts @@ -90,11 +90,13 @@ export class XXHandshake { private encrypt(k: bytes32, n: uint32, ad: bytes, plaintext: bytes) : bytes { const nonce = this.nonceToBytes(n); const ctx = new AEAD(); + ctx.init(k, nonce); ctx.aad(ad); ctx.encrypt(plaintext); - return ctx.final(); + // Encryption is done on the sent reference + return plaintext; } private decrypt(k: bytes32, n: uint32, ad: bytes, ciphertext: bytes) : bytes { @@ -105,7 +107,8 @@ export class XXHandshake { ctx.aad(ad); ctx.decrypt(ciphertext); - return ctx.final(); + // Decryption is done on the sent reference + return ciphertext; } private isEmptyKey(k: bytes32) : boolean { diff --git a/test/xx.test.ts b/test/xx.test.ts index 2c4f03a..ba9b08f 100644 --- a/test/xx.test.ts +++ b/test/xx.test.ts @@ -1,6 +1,5 @@ import { expect, assert } from "chai"; import { Buffer } from 'buffer'; -import { ed25519 } from 'bcrypto'; import { XXHandshake, KeyPair } from "../src/xx"; import { loadPayloadProto, generateEd25519Keys } from "./utils"; @@ -108,4 +107,32 @@ describe("Index", () => { await doHandshake(xx); }); + it("Test symmetric encrypt and decrypt", async () => { + const xx = new XXHandshake(); + const { nsInit, nsResp } = await doHandshake(xx); + const ad = Buffer.from("authenticated"); + const message = Buffer.from("HelloCrypto"); + + xx.encryptWithAd(nsInit.cs1, ad, message); + assert(!Buffer.from("HelloCrypto").equals(message), "Encrypted message should not be same as plaintext."); + const decrypted = xx.decryptWithAd(nsResp.cs1, ad, message); + + assert(Buffer.from("HelloCrypto").equals(decrypted), "Decrypted text not equal to original message."); + }); + + it("Test multiple messages encryption and decryption", async () => { + const xx = new XXHandshake(); + const { nsInit, nsResp } = await doHandshake(xx); + const ad = Buffer.from("authenticated"); + const message = Buffer.from("ethereum1"); + + xx.encryptWithAd(nsInit.cs1, ad, message); + const decrypted = xx.decryptWithAd(nsResp.cs1, ad, message); + assert(Buffer.from("ethereum1").equals(decrypted), "Decrypted text not equal to original message."); + + const message2 = Buffer.from("ethereum2"); + xx.encryptWithAd(nsInit.cs1, ad, message2); + const decrypted2 = xx.decryptWithAd(nsResp.cs1, ad, message2); + assert(Buffer.from("ethereum2").equals(decrypted2), "Decrypted text not equal to original message."); + }); });