Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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}`);
}
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}`);
}
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);
}