Skip to content
Snippets Groups Projects
monocypher.c 108 KiB
Newer Older
Charles Wright's avatar
Charles Wright committed
    crypto_chacha20(auth_key, 0, 64, sub_key, nonce + 16);
    crypto_chacha20_ctr(cipher_text, plain_text, text_size,
                        sub_key, nonce + 16, 1);
    lock_auth(mac, auth_key, ad, ad_size, cipher_text, text_size);
    WIPE_BUFFER(sub_key);
    WIPE_BUFFER(auth_key);
}

int crypto_unlock_aead(u8 *plain_text, const u8 key[32], const u8 nonce[24],
                       const u8  mac[16],
                       const u8 *ad         , size_t ad_size,
                       const u8 *cipher_text, size_t text_size)
{
    u8 sub_key[32];
    u8 auth_key[64]; // "Wasting" the whole Chacha block is faster
    crypto_hchacha20(sub_key, key, nonce);
    crypto_chacha20(auth_key, 0, 64, sub_key, nonce + 16);
    u8 real_mac[16];
    lock_auth(real_mac, auth_key, ad, ad_size, cipher_text, text_size);
    WIPE_BUFFER(auth_key);
    if (crypto_verify16(mac, real_mac)) {
        WIPE_BUFFER(sub_key);
        WIPE_BUFFER(real_mac);
        return -1;
    }
    crypto_chacha20_ctr(plain_text, cipher_text, text_size,
                        sub_key, nonce + 16, 1);
    WIPE_BUFFER(sub_key);
    WIPE_BUFFER(real_mac);
    return 0;
}

void crypto_lock(u8 mac[16], u8 *cipher_text,
                 const u8 key[32], const u8 nonce[24],
                 const u8 *plain_text, size_t text_size)
{
    crypto_lock_aead(mac, cipher_text, key, nonce, 0, 0, plain_text, text_size);
}

int crypto_unlock(u8 *plain_text,
                  const u8 key[32], const u8 nonce[24], const u8 mac[16],
                  const u8 *cipher_text, size_t text_size)
{
    return crypto_unlock_aead(plain_text, key, nonce, mac, 0, 0,
                              cipher_text, text_size);
}