How do I decrypt a Nostr message?

618 Views Asked by At

Here's how to send a private message to a Nostr Pubkey:

const crypto = require("crypto");
const secp = require("noble-secp256k1");

const ourPrivateKey = "";
const ourPubKey = "";
const theirPublicKey = "";
const text = "Hello World";

let sharedPoint = secp.getSharedSecret(ourPrivateKey, "02" + theirPublicKey);
let sharedX = sharedPoint.substr(2, 64);

let iv = crypto.randomFillSync(new Uint8Array(16));
var cipher = crypto.createCipheriv(
  "aes-256-cbc",
  Buffer.from(sharedX, "hex"),
  iv
);
let encryptedMessage = cipher.update(text, "utf8", "base64");
encryptedMessage += cipher.final("base64");
let ivBase64 = Buffer.from(iv.buffer).toString("base64");

let event = {
  pubkey: ourPubKey,
  created_at: Math.floor(Date.now() / 1000),
  kind: 4,
  tags: [["p", theirPublicKey]],
  content: encryptedMessage + "?iv=" + ivBase64,
};

console.log(event.content);

How would the receiver be able decrypt this once they receive it?

2

There are 2 best solutions below

1
On BEST ANSWER

If you don't mind using a library, you can use nostr-tools

import {nip04} from 'nostr-tools'

nip04.decrypt(key1,key2,message)
0
On
let encryptedMessageParts = event.content.split("?iv=");
let senderMessage_enctrypted = encryptedMessageParts[0];
let iv_ = Buffer.from(encryptedMessageParts[1], "base64");
sharedPoint = secp.getSharedSecret(ourPrivateKey, "02" + theirPublicKey);
sharedX = sharedPoint.substr(2, 64);
var decipher = crypto.createDecipheriv(
  "aes-256-cbc",
  Buffer.from(sharedX, "hex"),
  iv_
);
let senderMessage_decrypted = decipher.update(
  senderMessage_enctrypted,
  "base64",
  "utf8"
);
senderMessage_decrypted += decipher.final("utf8");
console.log(senderMessage_decrypted);

You can read more about how encrypted DM's work here: https://github.com/nostr-protocol/nips/blob/master/04.md