Skip to content

Sending a message example

CI edited this page Apr 2, 2019 · 2 revisions

In this example we show how to create, get and use a resource to encrypt and decrypt a message.

Show code
const DataPeps = require("datapeps-sdk");

global["TextEncoder"] = require("text-encoding").TextEncoder;
global["TextDecoder"] = require("text-encoding").TextDecoder;

global.fetch = require("node-fetch");
global.Headers = global.fetch.Headers;

async function main() {
  let aliceLogin = "aliceliddell";
  let bobLogin = "bobmorane";

  // Alice logs in
  let aliceSession = await DataPeps.Session.login(aliceLogin, "aliceP@ssw0rd");

  // Alice creates a resource
  let textResource = await new DataPeps.ResourceAPI(aliceSession).create(
    "text",
    null,
    [aliceLogin, bobLogin]
  );

  // Alice encrypts a message to Bob
  let messageToBob = "Hello, Bob!";
  console.log(`Alice message to Bob: ${messageToBob}`);
  let messageToBobBytes = new TextEncoder().encode("Hello, Bob!");
  let encryptedMessageToBob = textResource.encrypt(messageToBobBytes);

  // Alice logs out
  aliceSession.close();

  // Bob logs in
  let bobSession = await DataPeps.Session.login(bobLogin, "bobP@ssw0rd");

  // Bob gets the resource from DataPeps, using the resource ID
  let textResourceForBob = await new DataPeps.ResourceAPI(bobSession).get(
    textResource.id
  );

  // Bob decrypts the message from Alice
  let decryptedMessageToBobBytes = textResourceForBob.decrypt(
    encryptedMessageToBob
  );
  let decryptedMessageToBob = new TextDecoder().decode(
    decryptedMessageToBobBytes
  );
  console.log("Decrypted message received by Bob:", decryptedMessageToBob);
}

main().catch(e => console.log("An error occurred: ", e));

Running the example

Before running the example make sure you followed the steps described here.

To fetch the code run the following command in the examples directory:

git clone https://gist.github.com/4ddc1651918485f3adff7492853e43ec.git sending-a-message

To run this example execute the following command in the examples directory:

node sending-a-message/sending-a-message.js