Files
common/docs/examples/util-crypto/02_sign_verify_message_nacl/index.js
T
Luke Schoen 48008e2cc8 refactor: Extension of #231. Destructuring to combine imports (#237)
* refactor: Destructure imports together from same source in example util-crypto 01

* refactor: Destructure imports together example util-crypto 02. Avoid using default import. Show data to user

* refactor: Destructure imports together example util-crypto 03. Show data to user

* refactor: Split import over two lines looks cleaner

* fix: Address review comments. Update dependencies in examples
2018-11-14 13:26:53 +01:00

30 lines
1.2 KiB
JavaScript
Executable File

const { stringToU8a, u8aToHex } = require('@polkadot/util');
const { naclEncrypt, naclKeypairFromSeed, naclSign, naclVerify, randomAsU8a } = require('@polkadot/util-crypto');
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, nonce } = 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}`);
}
main().catch(console.error).finally(_ => process.exit());