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
|
/* See LICENSE file for copyright and license details. */
#include "common.h"
size_t
libsha2_unmarshal(struct libsha2_state *restrict state, const void *restrict buf_, size_t bufsize)
{
const char *restrict buf = buf_;
size_t off = 0;
if (bufsize < sizeof(int) + sizeof(enum libsha2_algorithm) + sizeof(size_t)) {
errno = EINVAL;
return 0;
}
if (*(const int *)buf) { /* version */
errno = EINVAL;
return 0;
}
off += sizeof(int);
state->algorithm = *(const enum libsha2_algorithm *)&buf[off];
off += sizeof(enum libsha2_algorithm);
state->message_size = *(const size_t *)&buf[off];
off += sizeof(size_t);
switch (state->algorithm) {
case LIBSHA2_224:
case LIBSHA2_256:
if (bufsize - off < sizeof(state->k.b32) + sizeof(state->w.b32) + sizeof(state->h.b32)) {
errno = EINVAL;
return 0;
}
memcpy(state->k.b32, &buf[off], sizeof(state->k.b32));
off += sizeof(state->k.b32);
memcpy(state->w.b32, &buf[off], sizeof(state->w.b32));
off += sizeof(state->w.b32);
memcpy(state->h.b32, &buf[off], sizeof(state->h.b32));
off += sizeof(state->h.b32);
break;
case LIBSHA2_384:
case LIBSHA2_512:
case LIBSHA2_512_224:
case LIBSHA2_512_256:
if (bufsize - off < sizeof(state->k.b64) + sizeof(state->w.b64) + sizeof(state->h.b64)) {
errno = EINVAL;
return 0;
}
memcpy(state->k.b64, &buf[off], sizeof(state->k.b64));
off += sizeof(state->k.b64);
memcpy(state->w.b64, &buf[off], sizeof(state->w.b64));
off += sizeof(state->w.b64);
memcpy(state->h.b64, &buf[off], sizeof(state->h.b64));
off += sizeof(state->h.b64);
break;
default:
errno = EINVAL;
return 0;
}
if (bufsize - off < sizeof(size_t)) {
errno = EINVAL;
return 0;
}
state->chunk_size = *(const size_t *)&buf[off];
off += sizeof(size_t);
if (bufsize - off < (state->message_size / 8) % state->chunk_size) {
errno = EINVAL;
return 0;
}
memcpy(state->chunk, &buf[off], (state->message_size / 8) % state->chunk_size);
off += (state->message_size / 8) % state->chunk_size;
return off;
}
|