def encrypt(self, plaintext, nonce, encoder=encoding.RawEncoder): """ Encrypts the plaintext message using the given `nonce` and returns the ciphertext encoded with the encoder. .. warning:: It is **VITALLY** important that the nonce is a nonce, i.e. it is a number used only once for any given key. If you fail to do this, you compromise the privacy of the messages encrypted. :param plaintext: [:class:`bytes`] The plaintext message to encrypt :param nonce: [:class:`bytes`] The nonce to use in the encryption :param encoder: The encoder to use to encode the ciphertext :rtype: [:class:`nacl.utils.EncryptedMessage`] """ if len(nonce) != self.NONCE_SIZE: raise ValueError("The nonce must be exactly %s bytes long" % self.NONCE_SIZE) ciphertext = libnacl.crypto_box_afternm( plaintext, nonce, self._shared_key, ) encoded_nonce = encoder.encode(nonce) encoded_ciphertext = encoder.encode(ciphertext) return EncryptedMessage._from_parts( encoded_nonce, encoded_ciphertext, encoder.encode(nonce + ciphertext), )
def test_boxnm(self): msg = b'Are you suggesting coconuts migrate?' # run 1 nonce1 = libnacl.utils.rand_nonce() pk1, sk1 = libnacl.crypto_box_keypair() pk2, sk2 = libnacl.crypto_box_keypair() k1 = libnacl.crypto_box_beforenm(pk2, sk1) k2 = libnacl.crypto_box_beforenm(pk1, sk2) enc_msg = libnacl.crypto_box_afternm(msg, nonce1, k1) self.assertNotEqual(msg, enc_msg) clear_msg = libnacl.crypto_box_open_afternm(enc_msg, nonce1, k2) self.assertEqual(clear_msg, msg)
def encrypt(self, msg, nonce=None, pack_nonce=True): ''' Encrypt the given message with the given nonce, if the nonce is not provided it will be generated from the libnacl.utils.rand_nonce function ''' if nonce is None: nonce = libnacl.utils.rand_nonce() elif len(nonce) != libnacl.crypto_box_NONCEBYTES: raise ValueError('Invalid nonce size') ctxt = libnacl.crypto_box_afternm(msg, nonce, self._k) if pack_nonce: return nonce + ctxt else: return nonce, ctxt