~increscent/aes-ccm

aes-ccm/decrypt.c -rw-r--r-- 2.1 KiB
6fdb84d8 — Robert Williams Found the issue: the msg_len parameter should be 16-bit, but it's 8-bit 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <string.h>

#include "lib.h"

int main()
{
    EVP_CIPHER_CTX *ctx;
    int len;
    int plaintext_len;
    int ret;
    unsigned char plaintext[1024];

    hexToBytes(KEY_STR, strlen(KEY_STR), KEY);
    hexToBytes(IV_STR, strlen(IV_STR), IV);
    hexToBytes(PLAINTEXT_STR, strlen(PLAINTEXT_STR), PLAINTEXT);
    hexToBytes(CIPHERTEXT_STR, strlen(CIPHERTEXT_STR), CIPHERTEXT);
    hexToBytes(MIC_STR, strlen(MIC_STR), MIC);

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new()))
        handleErrors("1");

    /* Initialise the decryption operation. */
    if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_128_ccm(), NULL, NULL, NULL))
        handleErrors("2");

    /* Setting IV len to 7. Not strictly necessary as this is the default
     * but shown here for the purposes of this example */
    if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_IVLEN, sizeof(IV), NULL))
        handleErrors("3");

    /* Set expected tag value. */
    if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_TAG, sizeof(MIC), MIC))
        handleErrors("4");

    /* Initialise key and IV */
    if(1 != EVP_DecryptInit_ex(ctx, NULL, NULL, KEY, IV))
        handleErrors("5");

    /* Provide the total ciphertext length */
    if(1 != EVP_DecryptUpdate(ctx, NULL, &len, NULL, sizeof(CIPHERTEXT)))
        handleErrors("6");

//    /* Provide any AAD data. This can be called zero or more times as required */
//    if(1 != EVP_DecryptUpdate(ctx, NULL, &len, aad, aad_len))
//        handleErrors("7");

    /*
     * Provide the message to be decrypted, and obtain the plaintext output.
     * EVP_DecryptUpdate can be called multiple times if necessary
     */
    ret = EVP_DecryptUpdate(ctx, plaintext, &len, CIPHERTEXT, sizeof(CIPHERTEXT));

    plaintext_len = len;

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    if(ret > 0) {
        printf("Success! Plaintext len: %d\n", plaintext_len);
        printHex(plaintext, plaintext_len);
        /* Success */
        return 0;
    } else {
        printf("Error!\n");
        /* Verify failed */
        return -1;
    }
}