Add more sm4 modes

Not tested yet
This commit is contained in:
Zhi Guan
2024-02-10 15:46:59 +08:00
parent b58ea74f96
commit 8ae03e8105
6 changed files with 533 additions and 2 deletions

95
src/sm4_ecb.c Normal file
View File

@@ -0,0 +1,95 @@
/*
* Copyright 2014-2024 The GmSSL Project. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
#include <gmssl/sm4.h>
#include <gmssl/mem.h>
#include <gmssl/error.h>
void sm4_ecb_encrypt(const SM4_KEY *key, const uint8_t *in, size_t nblocks, uint8_t *out)
{
while (nblocks--) {
sm4_encrypt(key, in, out);
in += SM4_BLOCK_SIZE;
out += SM4_BLOCK_SIZE;
}
}
typedef struct {
SM4_KEY sm4_key;
uint8_t block[SM4_BLOCK_SIZE];
size_t block_nbytes;
} SM4_ECB_CTX;
int sm4_ecb_encrypt_init(SM4_ECB_CTX *ctx, const uint8_t key[SM4_BLOCK_SIZE])
{
sm4_set_encrypt_key(&ctx->sm4_key, key);
memset(ctx->block, 0, SM4_BLOCK_SIZE);
ctx->block_nbytes = 0;
return 1;
}
int sm4_efb_encrypt_update(SM4_ECB_CTX *ctx,
const uint8_t *in, size_t inlen, uint8_t *out, size_t *outlen)
{
size_t left;
size_t nblocks;
size_t len;
if (ctx->block_nbytes >= SM4_BLOCK_SIZE) {
error_print();
return -1;
}
*outlen = 0;
if (ctx->block_nbytes) {
left = SM4_BLOCK_SIZE - ctx->block_nbytes;
if (inlen < left) {
memcpy(ctx->block + ctx->block_nbytes, in, inlen);
ctx->block_nbytes += inlen;
return 1;
}
memcpy(ctx->block + ctx->block_nbytes, in, left);
sm4_ecb_encrypt(&ctx->sm4_key, ctx->block, 1, out);
in += left;
inlen -= left;
out += SM4_BLOCK_SIZE;
*outlen += SM4_BLOCK_SIZE;
}
if (inlen >= SM4_BLOCK_SIZE) {
nblocks = inlen / SM4_BLOCK_SIZE;
len = nblocks * SM4_BLOCK_SIZE;
sm4_ecb_encrypt(&ctx->sm4_key, in, nblocks, out);
in += len;
inlen -= len;
out += len;
*outlen += len;
}
if (inlen) {
memcpy(ctx->block, in, inlen);
}
ctx->block_nbytes = inlen;
return 1;
}
int sm4_ecb_encrypt_finish(SM4_ECB_CTX *ctx, uint8_t *out, size_t *outlen)
{
if (ctx->block_nbytes >= SM4_BLOCK_SIZE) {
error_print();
return -1;
}
if (ctx->block_nbytes) {
error_puts("invalid total input length");
return -1;
}
*outlen = 0;
return 1;
}