dfklfg/packages/system/tests/Impl.test.ts

46 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-06-14 14:03:07 +00:00
import { schnorr, secp256k1 } from "@noble/curves/secp256k1";
import { Nip4WebCryptoEncryptor } from "../src/impl/nip4";
2023-10-06 12:16:28 +00:00
import { XChaCha20Encryptor } from "../src/impl/nip44";
2023-06-14 14:03:07 +00:00
import { bytesToHex } from "@noble/curves/abstract/utils";
const aKey = secp256k1.utils.randomPrivateKey();
const aPubKey = schnorr.getPublicKey(aKey);
const bKey = secp256k1.utils.randomPrivateKey();
const bPubKey = schnorr.getPublicKey(bKey);
describe("NIP-04", () => {
2023-07-22 18:37:46 +00:00
it("should encrypt/decrypt", async () => {
const msg = "test hello, 123";
const enc = new Nip4WebCryptoEncryptor();
const sec = enc.getSharedSecret(bytesToHex(aKey), bytesToHex(bPubKey));
2023-06-14 14:03:07 +00:00
2023-10-06 12:16:28 +00:00
const payload = await enc.encryptData(msg, sec);
expect(payload).toHaveProperty("ciphertext");
expect(payload).toHaveProperty("nonce");
expect(payload.v).toBe(0);
2023-06-14 14:03:07 +00:00
2023-07-22 18:37:46 +00:00
const dec = new Nip4WebCryptoEncryptor();
const sec2 = enc.getSharedSecret(bytesToHex(bKey), bytesToHex(aPubKey));
2023-10-06 12:16:28 +00:00
const plaintext = await dec.decryptData(payload, sec2);
2023-07-22 18:37:46 +00:00
expect(plaintext).toEqual(msg);
});
});
2023-06-14 14:03:07 +00:00
describe("NIP-44", () => {
2023-07-22 18:37:46 +00:00
it("should encrypt/decrypt", () => {
const msg = "test hello, 123";
2023-10-06 12:16:28 +00:00
const enc = new XChaCha20Encryptor();
2023-07-22 18:37:46 +00:00
const sec = enc.getSharedSecret(bytesToHex(aKey), bytesToHex(bPubKey));
2023-10-06 12:16:28 +00:00
const payload = enc.encryptData(msg, sec);
expect(payload).toHaveProperty("ciphertext");
expect(payload).toHaveProperty("nonce");
expect(payload.v).toBe(1);
2023-07-22 18:37:46 +00:00
2023-10-06 12:16:28 +00:00
const dec = new XChaCha20Encryptor();
2023-07-22 18:37:46 +00:00
const sec2 = enc.getSharedSecret(bytesToHex(bKey), bytesToHex(aPubKey));
2023-10-06 12:16:28 +00:00
const plaintext = dec.decryptData(payload, sec2);
2023-07-22 18:37:46 +00:00
expect(plaintext).toEqual(msg);
});
});