aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/padding.c
blob: a161ec7645ca248d7083fbdd27f45af4b6dc2b33 (plain) (blame)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
 * Copyright (c) 2015 Egor Tensin <Egor.Tensin@gmail.com>
 * This file is part of the "AES tools" project.
 * For details, see https://github.com/egor-tensin/aes-tools.
 * Distributed under the MIT License.
 */

#include <aes/all.h>

#include <assert.h>
#include <stdlib.h>
#include <string.h>

static AES_StatusCode aes_extract_padding_size_pkcs7(
    const void* src,
    size_t src_size,
    size_t* padding_size,
    AES_ErrorDetails* err_details)
{
    const unsigned char* cursor = (const unsigned char*) src + src_size - 1;
    *padding_size = *cursor;

    for (size_t i = 1; i < *padding_size; ++i)
        if (cursor[0 - i] != *padding_size)
            return aes_error_invalid_pkcs7_padding(err_details);

    return AES_SUCCESS;
}

AES_StatusCode aes_extract_padding_size(
    AES_PaddingMethod method,
    const void* src,
    size_t src_size,
    size_t* padding_size,
    AES_ErrorDetails* err_details)
{
    assert(src);
    assert(padding_size);

    if (src == NULL)
        return aes_error_null_argument(err_details, "src");
    if (padding_size == NULL)
        return aes_error_null_argument(err_details, "padding_size");

    switch (method)
    {
        case AES_PADDING_PKCS7:
            return aes_extract_padding_size_pkcs7(
                src, src_size, padding_size, err_details);

        default:
            return aes_error_not_implemented(
                err_details, "unsupported padding method");
    }
}

static AES_StatusCode aes_fill_with_padding_pkcs7(
    void* dest,
    size_t padding_size,
    AES_ErrorDetails* err_details)
{
    AES_UNUSED_PARAMETER(err_details);
    memset(dest, (int) padding_size, padding_size);
    return AES_SUCCESS;
}

AES_StatusCode aes_fill_with_padding(
    AES_PaddingMethod method,
    void* dest,
    size_t padding_size,
    AES_ErrorDetails* err_details)
{
    assert(dest);

    if (dest == NULL)
        return aes_error_null_argument(err_details, "dest");

    switch (method)
    {
        case AES_PADDING_PKCS7:
            return aes_fill_with_padding_pkcs7(
                dest, padding_size, err_details);

        default:
            return aes_error_not_implemented(
                err_details, "unsupported padding method");
    }
}