How to use the @polkadot/util-crypto.naclEncrypt function in @polkadot/util-crypto

To help you get started, we’ve selected a few @polkadot/util-crypto examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github polkadot-js / common / docs / examples / util-crypto / 01_encrypt_decrypt_message_nacl / index.js View on Github external
async function main () {
  const secret = new Uint8Array(32);
  const messagePreEncryption = new Uint8Array([1, 2, 3, 4, 5, 4, 3, 2, 1]);
  const noncePreEncryption = new Uint8Array(24);

  // Encrypt the message
  const { encrypted, nonce } = naclEncrypt(messagePreEncryption, secret, noncePreEncryption);

  // Show contents of the encrypted message
  console.log(`Encrypted message: ${JSON.stringify(encrypted, null, 2)}`);

  // Decrypt the message
  const messageDecrypted = naclDecrypt(encrypted, nonce, secret);
  // Convert each Uint8Array to a string for comparison
  const isMatch = messagePreEncryption.toString === messageDecrypted.toString;

  // Verify that the decrypted message matches the original message
  console.log(`Does the decrypted message match the original message? ${isMatch}`);
}
github polkadot-js / common / docs / examples / util-crypto / 02_sign_verify_message_nacl / index.js View on Github external
async function main () {
  // Create account seed for Alice as fallback if generated mnemonic not valid
  const seedAlice = 'Alice'.padEnd(32, ' ');

  // Generate new public/secret keypair for Alice from the supplied seed
  const { secretKey, publicKey } = naclKeypairFromSeed(stringToU8a(seedAlice));

  // Encrypt message. Create Uint8Array's filled with random bytes of specified length
  const secret = randomAsU8a(32);
  const messagePreEncryption = stringToU8a('please send me DOTs');
  const noncePreEncryption = randomAsU8a(24);

  const { encrypted } = naclEncrypt(messagePreEncryption, secret, noncePreEncryption);

  // Sign the message with a valid signature
  const messageSignature = naclSign(encrypted, secretKey);

  console.log(`Message signature: ${u8aToHex(messageSignature)}`);

  // Validate that the message was correctly signed
  const isValidSignature = naclVerify(encrypted, messageSignature, publicKey);

  console.log(`Was the message correctly signed? ${isValidSignature}`);
}
github polkadot-js / common / packages / keyring / src / pair / encode.ts View on Github external
export default function encode ({ publicKey, secretKey }: PairInfo, passphrase?: string): Uint8Array {
  assert(secretKey, 'Expected a valid secretKey to be passed to encode');

  const encoded = u8aConcat(
    PKCS8_HEADER,
    secretKey,
    PKCS8_DIVIDER,
    publicKey
  );

  if (!passphrase) {
    return encoded;
  }

  const { encrypted, nonce } = naclEncrypt(encoded, u8aFixLength(stringToU8a(passphrase), 256, true));

  return u8aConcat(nonce, encrypted);
}