def decrypt(self, ciphertext, nonce=None, encoder=encoding.RawEncoder): """ Decrypts the ciphertext using the given nonce and returns the plaintext message. :param ciphertext: [:class:`bytes`] The encrypted message to decrypt :param nonce: [:class:`bytes`] The nonce used when encrypting the ciphertext :param encoder: The encoder used to decode the ciphertext. :rtype: [:class:`bytes`] """ # Decode our ciphertext ciphertext = encoder.decode(ciphertext) if nonce is None: # If we were given the nonce and ciphertext combined, split them. nonce = ciphertext[:self.NONCE_SIZE] ciphertext = ciphertext[self.NONCE_SIZE:] if len(nonce) != self.NONCE_SIZE: raise ValueError("The nonce must be exactly %s bytes long" % self.NONCE_SIZE) plaintext = libnacl.crypto_box_open_afternm( ciphertext, nonce, self._shared_key, ) return plaintext
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 decrypt(self, ctxt, nonce=None): ''' Decrypt the given message, if a nonce is passed in attempt to decrypt it with the given nonce, otherwise assum that the nonce is attached to the message ''' if nonce is None: nonce = ctxt[:libnacl.crypto_box_NONCEBYTES] ctxt = ctxt[libnacl.crypto_box_NONCEBYTES:] elif len(nonce) != libnacl.crypto_box_NONCEBYTES: raise ValueError('Invalid nonce') msg = libnacl.crypto_box_open_afternm(ctxt, nonce, self._k) return msg