1 /*
2 * This file is part of the openHiTLS project.
3 *
4 * openHiTLS is licensed under the Mulan PSL v2.
5 * You can use this software according to the terms and conditions of the Mulan PSL v2.
6 * You may obtain a copy of Mulan PSL v2 at:
7 *
8 * http://license.coscl.org.cn/MulanPSL2
9 *
10 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13 * See the Mulan PSL v2 for more details.
14 */
15
16 #include "hitls_build.h"
17 #if defined(HITLS_CRYPTO_SM4) && defined(HITLS_CRYPTO_XTS)
18
19 #include "bsl_err_internal.h"
20 #include "crypt_sm4.h"
21 #include "crypt_errno.h"
22 #include "modes_local.h"
23 #include "crypt_modes_xts.h"
24
MODES_SM4_XTS_Encrypt(MODES_CipherXTSCtx * ctx,const uint8_t * in,uint8_t * out,uint32_t len)25 int32_t MODES_SM4_XTS_Encrypt(MODES_CipherXTSCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len)
26 {
27 return CRYPT_SM4_XTS_Encrypt(ctx->ciphCtx, in, out, len, ctx->tweak);
28 }
29
MODES_SM4_XTS_Decrypt(MODES_CipherXTSCtx * ctx,const uint8_t * in,uint8_t * out,uint32_t len)30 int32_t MODES_SM4_XTS_Decrypt(MODES_CipherXTSCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len)
31 {
32 if (ctx == NULL || in == NULL || out == NULL) {
33 BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
34 return CRYPT_NULL_INPUT;
35 }
36 return CRYPT_SM4_XTS_Decrypt(ctx->ciphCtx, in, out, len, ctx->tweak);
37 }
38
SM4_XTS_Update(MODES_XTS_Ctx * modeCtx,const uint8_t * in,uint32_t inLen,uint8_t * out,uint32_t * outLen)39 int32_t SM4_XTS_Update(MODES_XTS_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen)
40 {
41 return MODES_CipherStreamProcess(modeCtx->enc ? MODES_SM4_XTS_Encrypt : MODES_SM4_XTS_Decrypt, &modeCtx->xtsCtx,
42 in, inLen, out, outLen);
43 }
44
SM4_XTS_InitCtx(MODES_XTS_Ctx * modeCtx,const uint8_t * key,uint32_t keyLen,const uint8_t * iv,uint32_t ivLen,bool enc)45 int32_t SM4_XTS_InitCtx(MODES_XTS_Ctx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv,
46 uint32_t ivLen, bool enc)
47 {
48 int32_t ret;
49 if (key == NULL || iv == NULL) {
50 BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
51 return CRYPT_NULL_INPUT;
52 }
53 if (enc) {
54 ret = CRYPT_SM4_XTS_SetEncryptKey(modeCtx->xtsCtx.ciphCtx, key, keyLen);
55 } else {
56 ret = CRYPT_SM4_XTS_SetDecryptKey(modeCtx->xtsCtx.ciphCtx, key, keyLen);
57 }
58 if (ret != CRYPT_SUCCESS) {
59 BSL_ERR_PUSH_ERROR(ret);
60 return ret;
61 }
62 ret = MODES_XTS_SetIv(&modeCtx->xtsCtx, iv, ivLen);
63 if (ret != CRYPT_SUCCESS) {
64 (void)MODES_XTS_DeInitCtx(modeCtx);
65 return ret;
66 }
67
68 modeCtx->enc = enc;
69 return ret;
70 }
71 #endif