2 * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #include "cipher_sm4_xts.h"
12 #define XTS_SET_KEY_FN(fn_set_enc_key, fn_set_dec_key, \
13 fn_block_enc, fn_block_dec, \
14 fn_stream, fn_stream_gb) { \
15 size_t bytes = keylen / 2; \
18 fn_set_enc_key(key, &xctx->ks1.ks); \
19 xctx->xts.block1 = (block128_f)fn_block_enc; \
21 fn_set_dec_key(key, &xctx->ks1.ks); \
22 xctx->xts.block1 = (block128_f)fn_block_dec; \
24 fn_set_enc_key(key + bytes, &xctx->ks2.ks); \
25 xctx->xts.block2 = (block128_f)fn_block_enc; \
26 xctx->xts.key1 = &xctx->ks1; \
27 xctx->xts.key2 = &xctx->ks2; \
28 xctx->stream = fn_stream; \
29 xctx->stream_gb = fn_stream_gb; \
32 static int cipher_hw_sm4_xts_generic_initkey(PROV_CIPHER_CTX
*ctx
,
33 const unsigned char *key
,
36 PROV_SM4_XTS_CTX
*xctx
= (PROV_SM4_XTS_CTX
*)ctx
;
37 OSSL_xts_stream_fn stream
= NULL
;
38 OSSL_xts_stream_fn stream_gb
= NULL
;
41 XTS_SET_KEY_FN(HWSM4_set_encrypt_key
, HWSM4_set_decrypt_key
,
42 HWSM4_encrypt
, HWSM4_decrypt
, stream
, stream_gb
);
45 #endif /* HWSM4_CAPABLE */
46 #ifdef VPSM4_EX_CAPABLE
47 if (VPSM4_EX_CAPABLE
) {
48 stream
= vpsm4_ex_xts_encrypt
;
49 stream_gb
= vpsm4_ex_xts_encrypt_gb
;
50 XTS_SET_KEY_FN(vpsm4_ex_set_encrypt_key
, vpsm4_ex_set_decrypt_key
,
51 vpsm4_ex_encrypt
, vpsm4_ex_decrypt
, stream
, stream_gb
);
54 #endif /* VPSM4_EX_CAPABLE */
57 stream
= vpsm4_xts_encrypt
;
58 stream_gb
= vpsm4_xts_encrypt_gb
;
59 XTS_SET_KEY_FN(vpsm4_set_encrypt_key
, vpsm4_set_decrypt_key
,
60 vpsm4_encrypt
, vpsm4_decrypt
, stream
, stream_gb
);
63 #endif /* VPSM4_CAPABLE */
68 XTS_SET_KEY_FN(ossl_sm4_set_key
, ossl_sm4_set_key
, ossl_sm4_encrypt
,
69 ossl_sm4_decrypt
, stream
, stream_gb
);
74 static void cipher_hw_sm4_xts_copyctx(PROV_CIPHER_CTX
*dst
,
75 const PROV_CIPHER_CTX
*src
)
77 PROV_SM4_XTS_CTX
*sctx
= (PROV_SM4_XTS_CTX
*)src
;
78 PROV_SM4_XTS_CTX
*dctx
= (PROV_SM4_XTS_CTX
*)dst
;
81 dctx
->xts
.key1
= &dctx
->ks1
.ks
;
82 dctx
->xts
.key2
= &dctx
->ks2
.ks
;
86 static const PROV_CIPHER_HW sm4_generic_xts
= {
87 cipher_hw_sm4_xts_generic_initkey
,
89 cipher_hw_sm4_xts_copyctx
91 const PROV_CIPHER_HW
*ossl_prov_cipher_hw_sm4_xts(size_t keybits
)
93 return &sm4_generic_xts
;