• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* BEGIN_HEADER */
2#include "mbedtls/chacha20.h"
3/* END_HEADER */
4
5/* BEGIN_DEPENDENCIES
6 * depends_on:MBEDTLS_CHACHA20_C
7 * END_DEPENDENCIES
8 */
9
10/* BEGIN_CASE */
11void chacha20_crypt( data_t *key_str,
12                     data_t *nonce_str,
13                     int counter,
14                     data_t *src_str,
15                     data_t *expected_output_str )
16{
17    unsigned char output[375];
18    mbedtls_chacha20_context ctx;
19
20    memset( output, 0x00, sizeof( output ) );
21
22    TEST_ASSERT( src_str->len   == expected_output_str->len );
23    TEST_ASSERT( key_str->len   == 32U );
24    TEST_ASSERT( nonce_str->len == 12U );
25
26    /*
27     * Test the integrated API
28     */
29    TEST_ASSERT( mbedtls_chacha20_crypt( key_str->x, nonce_str->x, counter, src_str->len, src_str->x, output ) == 0 );
30
31    ASSERT_COMPARE( output, expected_output_str->len,
32                    expected_output_str->x, expected_output_str->len );
33
34    /*
35     * Test the streaming API
36     */
37    mbedtls_chacha20_init( &ctx );
38
39    TEST_ASSERT( mbedtls_chacha20_setkey( &ctx, key_str->x ) == 0 );
40
41    TEST_ASSERT( mbedtls_chacha20_starts( &ctx, nonce_str->x, counter ) == 0 );
42
43    memset( output, 0x00, sizeof( output ) );
44    TEST_ASSERT( mbedtls_chacha20_update( &ctx, src_str->len, src_str->x, output ) == 0 );
45
46    ASSERT_COMPARE( output, expected_output_str->len,
47                    expected_output_str->x, expected_output_str->len );
48
49    /*
50     * Test the streaming API again, piecewise
51     */
52
53    /* Don't free/init the context nor set the key again,
54     * in order to test that starts() does the right thing. */
55    TEST_ASSERT( mbedtls_chacha20_starts( &ctx, nonce_str->x, counter ) == 0 );
56
57    memset( output, 0x00, sizeof( output ) );
58    TEST_ASSERT( mbedtls_chacha20_update( &ctx, 1, src_str->x, output ) == 0 );
59    TEST_ASSERT( mbedtls_chacha20_update( &ctx, src_str->len - 1,
60                                          src_str->x + 1, output + 1 ) == 0 );
61
62    ASSERT_COMPARE( output, expected_output_str->len,
63                    expected_output_str->x, expected_output_str->len );
64
65    mbedtls_chacha20_free( &ctx );
66}
67/* END_CASE */
68
69/* BEGIN_CASE depends_on:MBEDTLS_SELF_TEST */
70void chacha20_self_test()
71{
72    TEST_ASSERT( mbedtls_chacha20_self_test( 1 ) == 0 );
73}
74/* END_CASE */
75