feat: nip44 v2

This commit is contained in:
Kieran 2024-08-26 15:57:46 +03:00
parent 1ed36352a8
commit 644bd57094
No known key found for this signature in database
GPG Key ID: DE71CEB3925BE941
12 changed files with 223 additions and 142 deletions

View File

@ -16,6 +16,7 @@ import { useRequestBuilder } from "@snort/system-react";
import { useEffect, useMemo } from "react";
import { useEmptyChatSystem } from "@/Hooks/useEmptyChatSystem";
import useEventPublisher from "@/Hooks/useEventPublisher";
import useLogin from "@/Hooks/useLogin";
import useModeration from "@/Hooks/useModeration";
import { findTag } from "@/Utils";
@ -24,7 +25,6 @@ import { LoginSession } from "@/Utils/Login";
import { Nip4Chats, Nip4ChatSystem } from "./nip4";
import { Nip17Chats, Nip17ChatSystem } from "./nip17";
import { Nip28Chats, Nip28ChatSystem } from "./nip28";
import useEventPublisher from "@/Hooks/useEventPublisher";
export enum ChatType {
DirectMessage = 1,

View File

@ -33,6 +33,7 @@
"typescript": "^5.2.2"
},
"dependencies": {
"@noble/ciphers": "^0.6.0",
"@noble/curves": "^1.4.0",
"@noble/hashes": "^1.4.0",
"@nostr-dev-kit/ndk": "^2.8.2",

View File

@ -0,0 +1,9 @@
export const enum MessageEncryptorVersion {
Nip4 = 0,
Nip44 = 1,
}
export interface MessageEncryptor {
encryptData(plaintext: string): Promise<string> | string;
decryptData(ciphertext: string): Promise<string> | string;
}

View File

@ -0,0 +1,145 @@
import { chacha20 } from "@noble/ciphers/chacha";
import { equalBytes } from "@noble/ciphers/utils";
import { secp256k1 } from "@noble/curves/secp256k1";
import { extract as hkdf_extract, expand as hkdf_expand } from "@noble/hashes/hkdf";
import { hmac } from "@noble/hashes/hmac";
import { sha256 } from "@noble/hashes/sha256";
import { concatBytes, randomBytes, utf8ToBytes } from "@noble/hashes/utils";
import { base64 } from "@scure/base";
declare const TextDecoder: any;
const decoder = new TextDecoder();
const u = {
minPlaintextSize: 0x0001, // 1b msg => padded to 32b
maxPlaintextSize: 0xffff, // 65535 (64kb-1) => padded to 64kb
utf8Encode: utf8ToBytes,
utf8Decode(bytes: Uint8Array) {
return decoder.decode(bytes);
},
getConversationKey(privkeyA: string, pubkeyB: string): Uint8Array {
const sharedX = secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB).subarray(1, 33);
return hkdf_extract(sha256, sharedX, "nip44-v2");
},
getMessageKeys(conversationKey: Uint8Array, nonce: Uint8Array) {
const keys = hkdf_expand(sha256, conversationKey, nonce, 76);
return {
chacha_key: keys.subarray(0, 32),
chacha_nonce: keys.subarray(32, 44),
hmac_key: keys.subarray(44, 76),
};
},
calcPaddedLen(len: number): number {
if (!Number.isSafeInteger(len) || len < 1) throw new Error("expected positive integer");
if (len <= 32) return 32;
const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1);
const chunk = nextPower <= 256 ? 32 : nextPower / 8;
return chunk * (Math.floor((len - 1) / chunk) + 1);
},
writeU16BE(num: number) {
if (!Number.isSafeInteger(num) || num < u.minPlaintextSize || num > u.maxPlaintextSize)
throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");
const arr = new Uint8Array(2);
new DataView(arr.buffer).setUint16(0, num, false);
return arr;
},
pad(plaintext: string): Uint8Array {
const unpadded = u.utf8Encode(plaintext);
const unpaddedLen = unpadded.length;
const prefix = u.writeU16BE(unpaddedLen);
const suffix = new Uint8Array(u.calcPaddedLen(unpaddedLen) - unpaddedLen);
return concatBytes(prefix, unpadded, suffix);
},
unpad(padded: Uint8Array): string {
const unpaddedLen = new DataView(padded.buffer).getUint16(0);
const unpadded = padded.subarray(2, 2 + unpaddedLen);
if (
unpaddedLen < u.minPlaintextSize ||
unpaddedLen > u.maxPlaintextSize ||
unpadded.length !== unpaddedLen ||
padded.length !== 2 + u.calcPaddedLen(unpaddedLen)
)
throw new Error("invalid padding");
return u.utf8Decode(unpadded);
},
hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array) {
if (aad.length !== 32) throw new Error("AAD associated data must be 32 bytes");
const combined = concatBytes(aad, message);
return hmac(sha256, key, combined);
},
// metadata: always 65b (version: 1b, nonce: 32b, max: 32b)
// plaintext: 1b to 0xffff
// padded plaintext: 32b to 0xffff
// ciphertext: 32b+2 to 0xffff+2
// raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)
// compressed payload (base64): 132b to 87472b
decodePayload(payload: string) {
if (typeof payload !== "string") throw new Error("payload must be a valid string");
const plen = payload.length;
if (plen < 132 || plen > 87472) throw new Error("invalid payload length: " + plen);
if (payload[0] === "#") throw new Error("unknown encryption version");
if (payload.startsWith("{") && payload.endsWith("}")) {
throw new Error("invalid base64: JSON string in content");
}
let data: Uint8Array;
try {
data = base64.decode(payload);
} catch (error) {
throw new Error("invalid base64: " + (error as any).message);
}
const dlen = data.length;
if (dlen < 99 || dlen > 65603) throw new Error("invalid data length: " + dlen);
const vers = data[0];
return {
version: vers,
nonce: data.subarray(1, 33),
ciphertext: data.subarray(33, vers === 2 ? -32 : undefined),
mac: vers === 2 ? data.subarray(-32) : undefined,
};
},
};
function encrypt_v2(plaintext: string, conversationKey: Uint8Array, nonce = randomBytes(32)) {
const { chacha_key, chacha_nonce, hmac_key } = u.getMessageKeys(conversationKey, nonce);
const padded = u.pad(plaintext);
const ciphertext = chacha20(chacha_key, chacha_nonce, padded);
const mac = u.hmacAad(hmac_key, ciphertext, nonce);
return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac));
}
function decrypt_v2(ciphertext: Uint8Array, nonce: Uint8Array, mac: Uint8Array, conversationKey: Uint8Array) {
const { chacha_key, chacha_nonce, hmac_key } = u.getMessageKeys(conversationKey, nonce);
const calculatedMac = u.hmacAad(hmac_key, ciphertext, nonce);
if (!equalBytes(calculatedMac, mac!)) throw new Error("invalid MAC");
const padded = chacha20(chacha_key, chacha_nonce, ciphertext);
return u.unpad(padded);
}
function decrypt_v1(ciphertext: Uint8Array, nonce: Uint8Array, conversationKey: Uint8Array) {
const padded = chacha20(conversationKey, nonce, ciphertext);
return u.unpad(padded);
}
export const nip44 = {
utils: u,
v1: {
getConversationKey: (privKey: string, pubKey: string) => {
const key = secp256k1.getSharedSecret(privKey, "02" + pubKey);
return sha256(key.slice(1, 33));
},
decrypt: decrypt_v1,
},
v2: {
getConversationKey: u.getConversationKey,
encrypt: encrypt_v2,
decrypt: decrypt_v2,
},
};

View File

@ -3,12 +3,10 @@ import * as utils from "@noble/curves/abstract/utils";
import { unwrap } from "@snort/shared";
import {
decodeEncryptionPayload,
EventKind,
EventSigner,
FullRelaySettings,
HexKey,
MessageEncryptorVersion,
NostrEvent,
NostrLink,
NotSignedNostrEvent,
@ -262,23 +260,6 @@ export class EventPublisher {
return await this.#sign(eb);
}
/**
* Generic decryption using NIP-23 payload scheme
*/
async decryptGeneric(content: string, from: string) {
const pl = decodeEncryptionPayload(content);
switch (pl.v) {
case MessageEncryptorVersion.Nip4: {
const nip4Payload = `${base64.encode(pl.ciphertext)}?iv=${base64.encode(pl.nonce)}`;
return await this.#signer.nip4Decrypt(nip4Payload, from);
}
case MessageEncryptorVersion.XChaCha20: {
return await this.#signer.nip44Decrypt(content, from);
}
}
throw new Error("Not supported version");
}
async decryptDm(note: NostrEvent) {
if (note.kind === EventKind.SealedRumor) {
const unseal = await this.unsealRumor(note);

View File

@ -1,15 +1,24 @@
import { MessageEncryptor, MessageEncryptorPayload, MessageEncryptorVersion } from "..";
import { MessageEncryptor, MessageEncryptorVersion } from "..";
import { secp256k1 } from "@noble/curves/secp256k1";
import { base64 } from "@scure/base";
export class Nip4WebCryptoEncryptor implements MessageEncryptor {
#sharedSecret?: CryptoKey;
constructor(
readonly privKey: string,
readonly pubKey: string,
) {}
getSharedSecret(privateKey: string, publicKey: string) {
const sharedPoint = secp256k1.getSharedSecret(privateKey, "02" + publicKey);
const sharedX = sharedPoint.slice(1, 33);
return sharedX;
}
async encryptData(content: string, sharedSecet: Uint8Array) {
const key = await this.#importKey(sharedSecet);
async encryptData(content: string) {
if (!this.#sharedSecret) {
this.#sharedSecret = await this.#importKey(this.getSharedSecret(this.privKey, this.pubKey));
}
const iv = window.crypto.getRandomValues(new Uint8Array(16));
const data = new TextEncoder().encode(content);
const result = await window.crypto.subtle.encrypt(
@ -17,25 +26,24 @@ export class Nip4WebCryptoEncryptor implements MessageEncryptor {
name: "AES-CBC",
iv: iv,
},
key,
this.#sharedSecret,
data,
);
return {
ciphertext: new Uint8Array(result),
nonce: iv,
v: MessageEncryptorVersion.Nip4,
} as MessageEncryptorPayload;
return `${base64.encode(new Uint8Array(result))}?iv=${base64.encode(iv)}`;
}
async decryptData(payload: MessageEncryptorPayload, sharedSecet: Uint8Array) {
const key = await this.#importKey(sharedSecet);
async decryptData(payload: string) {
if (!this.#sharedSecret) {
this.#sharedSecret = await this.#importKey(this.getSharedSecret(this.privKey, this.pubKey));
}
const [ciphertext, nonce] = payload.split("?iv=");
const result = await window.crypto.subtle.decrypt(
{
name: "AES-CBC",
iv: payload.nonce,
iv: base64.decode(nonce),
},
key,
payload.ciphertext,
this.#sharedSecret,
base64.decode(ciphertext),
);
return new TextDecoder().decode(result);
}

View File

@ -1,32 +1,27 @@
import { MessageEncryptor, MessageEncryptorPayload, MessageEncryptorVersion } from "..";
import { nip44 } from "../encryption/nip44";
import { MessageEncryptor } from "..";
import { randomBytes } from "@noble/hashes/utils";
import { streamXOR as xchacha20 } from "@stablelib/xchacha20";
import { secp256k1 } from "@noble/curves/secp256k1";
import { sha256 } from "@noble/hashes/sha256";
export class Nip44Encryptor implements MessageEncryptor {
constructor(
readonly privateKey: string,
readonly publicKey: string,
) {}
export class XChaCha20Encryptor implements MessageEncryptor {
getSharedSecret(privateKey: string, publicKey: string) {
const key = secp256k1.getSharedSecret(privateKey, "02" + publicKey);
return sha256(key.slice(1, 33));
encryptData(plaintext: string) {
const conversationKey = nip44.v2.getConversationKey(this.privateKey, this.publicKey);
return nip44.v2.encrypt(plaintext, conversationKey);
}
encryptData(content: string, sharedSecret: Uint8Array) {
const nonce = randomBytes(24);
const plaintext = new TextEncoder().encode(content);
const ciphertext = xchacha20(sharedSecret, nonce, plaintext, plaintext);
return {
ciphertext: Uint8Array.from(ciphertext),
nonce: nonce,
v: MessageEncryptorVersion.XChaCha20,
} as MessageEncryptorPayload;
}
decryptData(payload: MessageEncryptorPayload, sharedSecret: Uint8Array) {
if (payload.v !== MessageEncryptorVersion.XChaCha20) throw new Error("NIP44: wrong encryption version");
const dst = xchacha20(sharedSecret, payload.nonce, payload.ciphertext, payload.ciphertext);
const decoded = new TextDecoder().decode(dst);
return decoded;
decryptData(payload: string): string {
const { version, ciphertext, nonce, mac } = nip44.utils.decodePayload(payload);
if (version === 1) {
const conversationKey = nip44.v1.getConversationKey(this.privateKey, this.publicKey);
return nip44.v1.decrypt(ciphertext, nonce, conversationKey);
}
if (version === 2) {
const conversationKey = nip44.v2.getConversationKey(this.privateKey, this.publicKey);
return nip44.v2.decrypt(ciphertext, nonce, mac!, conversationKey);
}
throw new Error(`Unsupported payload version: ${version}`);
}
}

View File

@ -1,5 +1,3 @@
import { base64 } from "@scure/base";
export { NostrSystem } from "./nostr-system";
export { NDKSystem } from "./ndk-system";
export { default as EventKind } from "./event-kind";
@ -24,12 +22,13 @@ export * from "./text";
export * from "./pow";
export * from "./pow-util";
export * from "./query-optimizer";
export * from "./encrypted";
export * from "./encryption/pin-encrypted";
export * from "./outbox";
export * from "./sync";
export * from "./user-state";
export * from "./cache-relay";
export * from "./connection-cache-relay";
export * from "./encryption";
export * from "./impl/nip4";
export * from "./impl/nip7";
@ -42,49 +41,3 @@ export * from "./cache/index";
export * from "./cache/user-relays";
export * from "./cache/user-metadata";
export * from "./cache/relay-metric";
export const enum MessageEncryptorVersion {
Nip4 = 0,
XChaCha20 = 1,
}
export interface MessageEncryptorPayload {
ciphertext: Uint8Array;
nonce: Uint8Array;
v: MessageEncryptorVersion;
}
export interface MessageEncryptor {
getSharedSecret(privateKey: string, publicKey: string): Promise<Uint8Array> | Uint8Array;
encryptData(plaintext: string, sharedSecet: Uint8Array): Promise<MessageEncryptorPayload> | MessageEncryptorPayload;
decryptData(payload: MessageEncryptorPayload, sharedSecet: Uint8Array): Promise<string> | string;
}
export function decodeEncryptionPayload(p: string): MessageEncryptorPayload {
if (p.startsWith("{") && p.endsWith("}")) {
const pj = JSON.parse(p) as { v: number; nonce: string; ciphertext: string };
return {
v: pj.v,
nonce: base64.decode(pj.nonce),
ciphertext: base64.decode(pj.ciphertext),
};
} else if (p.includes("?iv=")) {
const [ciphertext, nonce] = p.split("?iv=");
return {
v: MessageEncryptorVersion.Nip4,
nonce: base64.decode(nonce),
ciphertext: base64.decode(ciphertext),
};
} else {
const buf = base64.decode(p);
return {
v: buf[0],
nonce: buf.subarray(1, 25),
ciphertext: buf.subarray(25),
};
}
}
export function encodeEncryptionPayload(p: MessageEncryptorPayload) {
return base64.encode(new Uint8Array([p.v, ...p.nonce, ...p.ciphertext]));
}

View File

@ -2,10 +2,8 @@ import { bytesToHex } from "@noble/curves/abstract/utils";
import { getPublicKey } from "@snort/shared";
import { EventExt } from "./event-ext";
import { Nip4WebCryptoEncryptor } from "./impl/nip4";
import { XChaCha20Encryptor } from "./impl/nip44";
import { MessageEncryptorVersion, decodeEncryptionPayload, encodeEncryptionPayload } from "./index";
import { Nip44Encryptor } from "./impl/nip44";
import { NostrEvent, NotSignedNostrEvent } from "./nostr";
import { base64 } from "@scure/base";
export type SignerSupports = "nip04" | "nip44" | string;
@ -49,41 +47,24 @@ export class PrivateKeySigner implements EventSigner {
return this.#publicKey;
}
async nip4Encrypt(content: string, key: string) {
const enc = new Nip4WebCryptoEncryptor();
const secret = enc.getSharedSecret(this.privateKey, key);
const data = await enc.encryptData(content, secret);
return `${base64.encode(data.ciphertext)}?iv=${base64.encode(data.nonce)}`;
async nip4Encrypt(content: string, otherKey: string) {
const enc = new Nip4WebCryptoEncryptor(this.privateKey, otherKey);
return await enc.encryptData(content);
}
async nip4Decrypt(content: string, otherKey: string) {
const enc = new Nip4WebCryptoEncryptor();
const secret = enc.getSharedSecret(this.privateKey, otherKey);
const [ciphertext, iv] = content.split("?iv=");
return await enc.decryptData(
{
ciphertext: base64.decode(ciphertext),
nonce: base64.decode(iv),
v: MessageEncryptorVersion.Nip4,
},
secret,
);
const enc = new Nip4WebCryptoEncryptor(this.privateKey, otherKey);
return await enc.decryptData(content);
}
async nip44Encrypt(content: string, key: string) {
const enc = new XChaCha20Encryptor();
const shared = enc.getSharedSecret(this.#privateKey, key);
const data = enc.encryptData(content, shared);
return encodeEncryptionPayload(data);
async nip44Encrypt(content: string, otherKey: string) {
const enc = new Nip44Encryptor(this.#privateKey, otherKey);
return enc.encryptData(content);
}
async nip44Decrypt(content: string, otherKey: string) {
const payload = decodeEncryptionPayload(content);
if (payload.v !== MessageEncryptorVersion.XChaCha20) throw new Error("Invalid payload version");
const enc = new XChaCha20Encryptor();
const shared = enc.getSharedSecret(this.#privateKey, otherKey);
return enc.decryptData(payload, shared);
const enc = new Nip44Encryptor(this.#privateKey, otherKey);
return enc.decryptData(content);
}
sign(ev: NostrEvent): Promise<NostrEvent> {

View File

@ -1,6 +1,6 @@
import { schnorr, secp256k1 } from "@noble/curves/secp256k1";
import { Nip4WebCryptoEncryptor } from "../src/impl/nip4";
import { XChaCha20Encryptor } from "../src/impl/nip44";
import { Nip44Encryptor } from "../src/impl/nip44";
import { bytesToHex } from "@noble/curves/abstract/utils";
const aKey = secp256k1.utils.randomPrivateKey();
@ -29,7 +29,7 @@ describe("NIP-04", () => {
describe("NIP-44", () => {
it("should encrypt/decrypt", () => {
const msg = "test hello, 123";
const enc = new XChaCha20Encryptor();
const enc = new Nip44Encryptor();
const sec = enc.getSharedSecret(bytesToHex(aKey), bytesToHex(bPubKey));
const payload = enc.encryptData(msg, sec);
@ -37,7 +37,7 @@ describe("NIP-44", () => {
expect(payload).toHaveProperty("nonce");
expect(payload.v).toBe(1);
const dec = new XChaCha20Encryptor();
const dec = new Nip44Encryptor();
const sec2 = enc.getSharedSecret(bytesToHex(bKey), bytesToHex(aPubKey));
const plaintext = dec.decryptData(payload, sec2);
expect(plaintext).toEqual(msg);

View File

@ -4051,6 +4051,13 @@ __metadata:
languageName: node
linkType: hard
"@noble/ciphers@npm:^0.6.0":
version: 0.6.0
resolution: "@noble/ciphers@npm:0.6.0"
checksum: 10/e7f1d2c6ddbdfd48e91bfa9a81993dd5f9196bc24778038ce55aee4572f3a246851660dbbf08004916e35722810a542f83e9bd02f43b185efe016df330f848a5
languageName: node
linkType: hard
"@noble/curves@npm:1.1.0, @noble/curves@npm:~1.1.0":
version: 1.1.0
resolution: "@noble/curves@npm:1.1.0"
@ -4741,6 +4748,7 @@ __metadata:
resolution: "@snort/system@workspace:packages/system"
dependencies:
"@jest/globals": "npm:^29.5.0"
"@noble/ciphers": "npm:^0.6.0"
"@noble/curves": "npm:^1.4.0"
"@noble/hashes": "npm:^1.4.0"
"@nostr-dev-kit/ndk": "npm:^2.8.2"