How encrypt and decript text by using nem-sdk.js

Hello.

Would it be possible to do the following?
Suppose I have address A and address B and i want to encrypt a text message
so it can be read by address B without sending this text in transaction on the blockchain so without
using the blockchain at all.

Which of the functions would I need to use from here:

I have seen there are a functions (encrypt, decrypt, encode, decode)
This encode / decode seems what am looking for or I am wrong?

If i need to use this then I need the sender or receiver public keys.
If this is the case how can I derive a public key from an address?

Is there any other way to do it properly?
Thanks.

You can use the Crypto.encrypt and Crypto.decrypt functions.

If you want it to use a shared key between sender/recipient, you are going to need the encode/decode logic (ephemeral key generation, then encryption), have a look at those :ok_hand:

1 Like

Hello. Thanks for fast reply.
Do you have any good link of a sample code for that shared key method?

Btw. I have checked the source of the NanoWallet and the nem-sdk.js and is seems that
encode/decode is used to encrypt the message.

https://github.com/QuantumMechanics/NEM-sdk/blob/master/src/model/transactions/message.js

The receiver public key is fetched from NIS node when the address is entered in the NANO wallet.
In case the public key for the address can’t be fetched then is not possible to send encrypted message.

Yes, this is indeed only possible for public accounts and non-multisig accounts.

One note is that I wrongly assumed “Symbol” in my reply above (there is no ephemeral key pair with NIS).

No problem! If the time comes i will ask the same question for Symbol!
If you want you can paste a link here to that Symbol ephemeral key pair
anyway so I will take a look how this works.

Thanks.

Hey there,

you can find an example usage of the encode() method here (NIS SDK): https://github.com/QuantumMechanics/NEM-sdk/blob/master/src/model/transactions/message.js#L17

and what i refer to as “ephemeral key pair” is taken from Symbol’s persistent delegation request transactions as shown here: https://github.com/nemtech/symbol-sdk-typescript-javascript/blob/master/src/model/message/PersistentHarvestingDelegationMessage.ts#L46. Generally, when encrypting with a shared key, it is recommended to generate an ephemeral key and share this part instead.

2 Likes

Thank you. :+1: