Beispiel #1
0
static int
aead_cipher_encrypt(cipher_ctx_t *cipher_ctx,
                    uint8_t *c,
                    size_t *clen,
                    uint8_t *m,
                    size_t mlen,
                    uint8_t *ad,
                    size_t adlen,
                    uint8_t *n,
                    uint8_t *k)
{
    int err                      = CRYPTO_OK;
    unsigned long long long_clen = 0;

    size_t nlen = cipher_ctx->cipher->nonce_len;
    size_t tlen = cipher_ctx->cipher->tag_len;

    switch (cipher_ctx->cipher->method) {
    case AES256GCM: // Only AES-256-GCM is supported by libsodium.
        if (cipher_ctx->aes256gcm_ctx != NULL) { // Use it if availble
            err =  crypto_aead_aes256gcm_encrypt_afternm(c, &long_clen, m, mlen,
                                          ad, adlen, NULL, n,
                                          (const aes256gcm_ctx *)cipher_ctx->aes256gcm_ctx);
            *clen = (size_t)long_clen; // it's safe to cast 64bit to 32bit length here
            break;
        }
        // Otherwise, just use the mbedTLS one with crappy AES-NI.
    case AES192GCM:
    case AES128GCM:

        err = mbedtls_cipher_auth_encrypt(cipher_ctx->evp, n, nlen, ad, adlen,
                                          m, mlen, c, clen, c + mlen, tlen);
        *clen += tlen;
        break;
    case CHACHA20POLY1305IETF:
        err = crypto_aead_chacha20poly1305_ietf_encrypt(c, &long_clen, m, mlen,
                                                        ad, adlen, NULL, n, k);
        *clen = (size_t)long_clen;
        break;
#ifdef FS_HAVE_XCHACHA20IETF
    case XCHACHA20POLY1305IETF:
        err = crypto_aead_xchacha20poly1305_ietf_encrypt(c, &long_clen, m, mlen,
                                                         ad, adlen, NULL, n, k);
        *clen = (size_t)long_clen;
        break;
#endif
    default:
        return CRYPTO_ERROR;
    }

    return err;
}
/*
    Public GCM encrypt function.  This will just perform the encryption.  The
    tag should be fetched with psAesGetGCMTag
 */
void psAesEncryptGCM(psAesGcm_t *ctx, const unsigned char *pt, unsigned char *ct, uint32_t len)
{
    unsigned long long ciphertext_len;
    unsigned char *resultEncryption;

    resultEncryption = psMalloc(NULL, len + sizeof(ctx->Tag));

    /* libsodium will put the (cipher text and the tag) in the result, */
    crypto_aead_aes256gcm_encrypt_afternm(resultEncryption, &ciphertext_len,
        (const unsigned char *) pt, (unsigned long long) len,
        (const unsigned char *) ctx->Aad, (unsigned long long) ctx->AadLen,
        NULL, (const unsigned char *) ctx->IV,
        (crypto_aead_aes256gcm_state *) &(ctx->libSodiumCtx));

    /* Copy the authentication tag in context to be able to retrieve it later */
    memcpy(ctx->Tag, (resultEncryption + len), sizeof(ctx->Tag));

    /* Copy the ciphertext in destination */
    memcpy(ct, resultEncryption, len);

    psFree(resultEncryption, NULL);
}