1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21#include "qemu/osdep.h"
22#include "qemu/bswap.h"
23#include "ivgen-essiv.h"
24
25typedef struct QCryptoIVGenESSIV QCryptoIVGenESSIV;
26struct QCryptoIVGenESSIV {
27 QCryptoCipher *cipher;
28};
29
30static int qcrypto_ivgen_essiv_init(QCryptoIVGen *ivgen,
31 const uint8_t *key, size_t nkey,
32 Error **errp)
33{
34 uint8_t *salt;
35 size_t nhash;
36 size_t nsalt;
37 QCryptoIVGenESSIV *essiv = g_new0(QCryptoIVGenESSIV, 1);
38
39
40 nsalt = qcrypto_cipher_get_key_len(ivgen->cipher);
41
42 nhash = qcrypto_hash_digest_len(ivgen->hash);
43
44 salt = g_new0(uint8_t, MAX(nhash, nsalt));
45
46 if (qcrypto_hash_bytes(ivgen->hash, (const gchar *)key, nkey,
47 &salt, &nhash,
48 errp) < 0) {
49 g_free(essiv);
50 g_free(salt);
51 return -1;
52 }
53
54
55 essiv->cipher = qcrypto_cipher_new(ivgen->cipher,
56 QCRYPTO_CIPHER_MODE_ECB,
57 salt, MIN(nhash, nsalt),
58 errp);
59 if (!essiv->cipher) {
60 g_free(essiv);
61 g_free(salt);
62 return -1;
63 }
64
65 g_free(salt);
66 ivgen->private = essiv;
67
68 return 0;
69}
70
71static int qcrypto_ivgen_essiv_calculate(QCryptoIVGen *ivgen,
72 uint64_t sector,
73 uint8_t *iv, size_t niv,
74 Error **errp)
75{
76 QCryptoIVGenESSIV *essiv = ivgen->private;
77 size_t ndata = qcrypto_cipher_get_block_len(ivgen->cipher);
78 uint8_t *data = g_new(uint8_t, ndata);
79
80 sector = cpu_to_le64(sector);
81 memcpy(data, (uint8_t *)§or, MIN(sizeof(sector), ndata));
82 if (sizeof(sector) < ndata) {
83 memset(data + sizeof(sector), 0, ndata - sizeof(sector));
84 }
85
86 if (qcrypto_cipher_encrypt(essiv->cipher,
87 data,
88 data,
89 ndata,
90 errp) < 0) {
91 g_free(data);
92 return -1;
93 }
94
95 if (ndata > niv) {
96 ndata = niv;
97 }
98 memcpy(iv, data, ndata);
99 if (ndata < niv) {
100 memset(iv + ndata, 0, niv - ndata);
101 }
102 g_free(data);
103 return 0;
104}
105
106static void qcrypto_ivgen_essiv_cleanup(QCryptoIVGen *ivgen)
107{
108 QCryptoIVGenESSIV *essiv = ivgen->private;
109
110 qcrypto_cipher_free(essiv->cipher);
111 g_free(essiv);
112}
113
114
115struct QCryptoIVGenDriver qcrypto_ivgen_essiv = {
116 .init = qcrypto_ivgen_essiv_init,
117 .calculate = qcrypto_ivgen_essiv_calculate,
118 .cleanup = qcrypto_ivgen_essiv_cleanup,
119};
120
121