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