xref: /openbmc/qemu/crypto/ivgen.c (revision cb730894)
1 /*
2  * QEMU Crypto block IV generator
3  *
4  * Copyright (c) 2015-2016 Red Hat, Inc.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20 
21 #include "qemu/osdep.h"
22 #include "crypto/ivgenpriv.h"
23 #include "crypto/ivgen-plain.h"
24 #include "crypto/ivgen-plain64.h"
25 #include "crypto/ivgen-essiv.h"
26 
27 
28 QCryptoIVGen *qcrypto_ivgen_new(QCryptoIVGenAlgorithm alg,
29                                 QCryptoCipherAlgorithm cipheralg,
30                                 QCryptoHashAlgorithm hash,
31                                 const uint8_t *key, size_t nkey,
32                                 Error **errp)
33 {
34     QCryptoIVGen *ivgen = g_new0(QCryptoIVGen, 1);
35 
36     ivgen->algorithm = alg;
37     ivgen->cipher = cipheralg;
38     ivgen->hash = hash;
39 
40     switch (alg) {
41     case QCRYPTO_IVGEN_ALG_PLAIN:
42         ivgen->driver = &qcrypto_ivgen_plain;
43         break;
44     case QCRYPTO_IVGEN_ALG_PLAIN64:
45         ivgen->driver = &qcrypto_ivgen_plain64;
46         break;
47     case QCRYPTO_IVGEN_ALG_ESSIV:
48         ivgen->driver = &qcrypto_ivgen_essiv;
49         break;
50     default:
51         error_setg(errp, "Unknown block IV generator algorithm %d", alg);
52         g_free(ivgen);
53         return NULL;
54     }
55 
56     if (ivgen->driver->init(ivgen, key, nkey, errp) < 0) {
57         g_free(ivgen);
58         return NULL;
59     }
60 
61     return ivgen;
62 }
63 
64 
65 int qcrypto_ivgen_calculate(QCryptoIVGen *ivgen,
66                             uint64_t sector,
67                             uint8_t *iv, size_t niv,
68                             Error **errp)
69 {
70     return ivgen->driver->calculate(ivgen, sector, iv, niv, errp);
71 }
72 
73 
74 QCryptoIVGenAlgorithm qcrypto_ivgen_get_algorithm(QCryptoIVGen *ivgen)
75 {
76     return ivgen->algorithm;
77 }
78 
79 
80 QCryptoCipherAlgorithm qcrypto_ivgen_get_cipher(QCryptoIVGen *ivgen)
81 {
82     return ivgen->cipher;
83 }
84 
85 
86 QCryptoHashAlgorithm qcrypto_ivgen_get_hash(QCryptoIVGen *ivgen)
87 {
88     return ivgen->hash;
89 }
90 
91 
92 void qcrypto_ivgen_free(QCryptoIVGen *ivgen)
93 {
94     if (!ivgen) {
95         return;
96     }
97     ivgen->driver->cleanup(ivgen);
98     g_free(ivgen);
99 }
100