Skip to content

Encrypting and Decrypting Messages

martiliones edited this page Dec 16, 2023 · 4 revisions

Messages and KVS records are encrypted using Curve25519, Salsa20, and Poly1305 NaCl box and NaCL.secretbox cipher algorithms respectively, then packed in transactions, which are signed and broadcasted to ADAMANT network.

The library offers the following methods to encrypt and decrypt messages and KVS records.

Further reading:

decodeMessage()

Decrypts a message or KVS record, retrieved from ADAMANT blockchain.

  • Typing

    function decodeMessage(
      message: string,
      senderPublicKey: Uint8Array | string,
      keyPairOrPassphrase: string | KeyPair,
      nonce: string
    ): string;
  • Parameters

    • message — message to decrypt
    • senderPublicKey — sender's public key
    • passPhrase — recipient's 12 words mnemonic ADAMANT passphrase
    • nonce — nonce
  • Returns

    Decrypted message, string. Or empty string, if unable to decrypt.

  • Throws

    Error when passed invalid parameter.

  • Example

    import { decodeMessage } from 'adamant-api'
    
    import { config } from './config.js'
    import { api } from './api.js'
    
    const response = await api.getTransaction('12154642911137703318', {
      returnAsset: 1
    })
    
    if (response.success) {
      const { asset, senderPublicKey } = response.data.transaction
      const { message, own_message } = asset.chat
    
      if (chat) {
        const decodedMessage = decodeMessage(
          message,
          senderPublicKey,
          config.passphrase,
          own_message
        )
    
        console.log(decodedMessage)
      }
    }

encodeMessage()

Encodes a message or KVS record.

Note

You do NOT need to encrypt a message when using sendMessage(), it encrypts a message by default.

  • Typing

    function encodeMessage(
      message: string,
      keypair: KeyPair,
      recipientPublicKey: Uint8Array | string
    ): { message: string, own_message: string };
  • Parameters

    • message — message to encrypt
    • keypair — sender's public and private keys
    • recipientPublicKey — recipient's public key
  • Returns

    Object with strings of encrypted message and nonce own_message.

  • Example

    import {
      encodeMessage,
      createNewPassphrase,
      createKeypairFromPassphrase
    } from 'adamant-api'
    import { api } from './api.js'
    
    const passphrase = createNewPassphrase()
    const keypair = createKeypairFromPassphrase(passphrase)
    
    const recipientPublicKey = await api.getPublicKey('U1234...')
    
    const encodedMessage = encodeMessage('Hello, world!', keypair, recipientPublicKey)
    console.log(encodedMessage)