Esempio n. 1
0
def test_crypto_lock_unlock_wrapper(msg, ad):
    # should be able to pass in a bytearray or memoryview
    key = bytes(32)
    nonce = bytes(24)
    for wrapper in [bytes, bytearray, memoryview]:
        mac, ct = crypto_lock(key, nonce, wrapper(msg), wrapper(ad))
        # should be the same regardless of wrapper!
        assert (mac, ct) == crypto_lock(key, nonce, msg, ad)
        # should unlock correctly as well
        assert crypto_unlock(key, mac, nonce, wrapper(ct), wrapper(ad)) == msg
Esempio n. 2
0
    def encrypt(self, msg, nonce=None):
        """
        Encrypt the given message `msg`, optionally with a specified `nonce`.
        If the given `nonce` is ``None``, then it is automatically generated.
        See :class:`.EncryptedMessage` for details on how the encrypted message
        is encoded.

        :param msg: Message to encrypt (a bytes-like object).
        :param nonce: Optional :py:obj:`bytes` object of length :py:obj:`.NONCE_SIZE`.

        :rtype: :class:`.EncryptedMessage`
        """
        if nonce is None:
            nonce = random(self.NONCE_SIZE)
        mac, ct = crypto_lock(key=self._key, msg=msg, nonce=nonce)
        return EncryptedMessage.from_parts(nonce=nonce, mac=mac, ciphertext=ct)
Esempio n. 3
0
def test_crypto_lock_equivalent(key, nonce, msg):
    # we expose the more general crypto_lock_aead()
    # function, so check if we are calling it the right way
    # when ad == b''
    original_message = msg
    aead_mac, aead_ct = crypto_lock(key, nonce, msg)

    msg_size = len(msg)
    mac = ffi.new('uint8_t[16]')
    key = ffi.new('uint8_t[32]', key)
    nonce = ffi.new('uint8_t[24]', nonce)
    msg = ffi.new('uint8_t[]', msg)
    ct = ffi.new('uint8_t[]', msg_size)
    lib.crypto_lock(mac, ct, key, nonce, msg, msg_size)
    assert bytes(mac) == aead_mac
    assert bytes(ct) == aead_ct

    # check that we can decrypt this
    lib.crypto_wipe(msg, msg_size)
    rv = lib.crypto_unlock(msg, key, nonce, mac, ct, msg_size)
    assert rv == 0
    assert bytes(msg)[:-1] == original_message
Esempio n. 4
0
def test_crypto_lock_key(key, nonce, msg, key2):
    mac, ct = crypto_lock(key, nonce, msg)
    if key != key2:
        assert crypto_unlock(key2, mac, nonce, ct) is None
Esempio n. 5
0
def test_crypto_lock_nonce(key, nonce, msg, nonce2):
    mac, ct = crypto_lock(key, nonce, msg)
    if nonce != nonce2:
        assert crypto_unlock(key, mac, nonce2, ct) is None
Esempio n. 6
0
def test_crypto_lock_mac(key, nonce, msg, mac2):
    mac, ct = crypto_lock(key, nonce, msg)
    if mac != mac2:
        assert crypto_unlock(key, mac2, nonce, ct) is None
Esempio n. 7
0
def test_crypto_lock(key, nonce, msg, additional_data):
    mac, ct = crypto_lock(key, nonce, msg, additional_data)
    assert crypto_unlock(key, mac, nonce, ct, additional_data) == msg