Skip to content Skip to sidebar Skip to footer

Encrypt In Python 3.7 And Decode In Nodejs 12

I read a post: encrypted-data-between-node-js-and-python. I need to implement the reverse path, create the encryption in python and decode in the node. On the Python side I did: fr

Solution 1:

encrypted returned by SecretBox.encrypt() in the PyNaCl code is an EncryptedMessage object (a bytes subclass) that holds the concatenated (24 bytes) nonce and ciphertext. Note that EncryptedMessage also has the properties nonce and ciphertext.

Since the TweetNaCl code uses the concatenated (Base64 encoded) data, these data must first be separated (after Base64 decoding) and nonce and ciphertext must be processed separately in nacl.secretbox.open(). Please note that TweetNaCl uses TypedArrays. For the conversion to or from Utf8 or Base64 the functions from tweetnacl-util can be used:

const secretKey = nacl.util.decodeUTF8('_THIS_IS_MY_32_CHARS_SECRET_KEY_');
const encryptedMessage = nacl.util.decodeBase64('KRmiqOFUN1HklmPZgbd0BINNDDCu3dyB/s4tdTjcw65K6Lr5N797+7zoLm9WClCXIDNLAqrNGwF2MybtJu+U');

// Separate nonce and ciphertextconst nonce = encryptedMessage.slice(0, 24)
const ciphertext = encryptedMessage.slice(24) 

// Decryptconst originalMessage = nacl.secretbox.open(ciphertext, nonce, secretKey);

const decryptedText = nacl.util.encodeUTF8(originalMessage);
console.log(decryptedText); // Some Italians hate wine    
<scriptsrc="https://cdn.jsdelivr.net/npm/tweetnacl-util@0.15.1/nacl-util.min.js"></script><scriptsrc="https://cdn.jsdelivr.net/npm/tweetnacl@1.0.3/nacl.min.js"></script>

Please note that this snippet is pure JavaScript. In your NodeJS environment you have to replace nacl.util with utils.

Post a Comment for "Encrypt In Python 3.7 And Decode In Nodejs 12"