I am currently working on a project that involves P2P encryption using Substrate addresses and sr25519 cryptographic keys. However, I am encountering difficulties in implementing encryption and decryption with the NaCl library.

The library doesn't work with sr25519. I tried using ed2curve, but it seems strange. Is there any other way to encrypt/decrypt with sr25519?

1 Answer 1


Okay, I found a way to accomplish this; I need to use a shared secret key.

The @polkadot/wasm-crypto library has a method for it. I had to conduct research on encryption to find the appropriate code because "sr25519Agree" didn't mean anything to me as a developer. :)

import { waitReady, sr25519Agree } from '@polkadot/wasm-crypto'
import { sr25519PairFromSeed, naclEncrypt, naclDecrypt, encodeAddress } from '@polkadot/util-crypto'
import { stringToU8a, u8aToString } from '@polkadot/util'

const SEED_1 = '0x8ed48adf968bfb0d712d1530442187b7a9c5ce528ae079d60c072127d5b0b924'
const SEED_2 = '0x6152353dac161f116233b73b655ee6246da278df692c5599ce108b5fef5b3a09'

(async () => {
  await waitReady()

  const pair_1 = sr25519PairFromSeed(SEED_1)
  console.log('pair_1', encodeAddress(pair_1.publicKey))

  const pair_2 = sr25519PairFromSeed(SEED_2)
  console.log('pair_2', encodeAddress(pair_2.publicKey))

  const shared_1 = sr25519Agree(pair_1.publicKey, pair_2.secretKey)
  const shared_2 = sr25519Agree(pair_2.publicKey, pair_1.secretKey)

    'shared_1 === shared_2',
    u8aToString(shared_1) === u8aToString(shared_2)

  const message = stringToU8a('hello world')

  const {encrypted, nonce} = naclEncrypt(message, shared_1)
  const decryptedMessage = naclDecrypt(encrypted, nonce, shared_2)

  console.log('decryptedMessage', u8aToString(decryptedMessage))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.