From a21bdf02b2b8553fc6ad7acb02d39519cb2d0ee6 Mon Sep 17 00:00:00 2001 From: Zhi Guan Date: Wed, 10 Jun 2026 22:12:38 +0800 Subject: [PATCH] Update block_cipher.c --- src/block_cipher.c | 53 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/src/block_cipher.c b/src/block_cipher.c index f1172c20..e77a44d3 100644 --- a/src/block_cipher.c +++ b/src/block_cipher.c @@ -8,17 +8,54 @@ */ - #include #include #include #include -#include +#include #include +#include +const BLOCK_CIPHER *block_cipher_from_name(const char *name) +{ + if (!name) { + error_print(); + return NULL; + } + if (!strcmp(name, "sm4")) { + return BLOCK_CIPHER_sm4(); +#ifdef ENABLE_AES + } else if (!strcmp(name, "aes128")) { + return BLOCK_CIPHER_aes128(); +#endif + } + error_print(); + return NULL; +} + +const char *block_cipher_name(const BLOCK_CIPHER *cipher) +{ + if (!cipher) { + error_print(); + return NULL; + } + switch (cipher->oid) { + case OID_sm4: return "sm4"; +#ifdef ENABLE_AES + case OID_aes128: return "aes128"; +#endif + } + error_print(); + return NULL; +} + int block_cipher_set_encrypt_key(BLOCK_CIPHER_KEY *key, const BLOCK_CIPHER *cipher, const uint8_t *raw_key) { + if (!key || !cipher || !cipher->set_encrypt_key || !raw_key) { + error_print(); + return -1; + } memset(key, 0, sizeof(BLOCK_CIPHER_KEY)); cipher->set_encrypt_key(key, raw_key); key->cipher = cipher; @@ -27,6 +64,10 @@ int block_cipher_set_encrypt_key(BLOCK_CIPHER_KEY *key, const BLOCK_CIPHER *ciph int block_cipher_set_decrypt_key(BLOCK_CIPHER_KEY *key, const BLOCK_CIPHER *cipher, const uint8_t *raw_key) { + if (!key || !cipher || !cipher->set_decrypt_key || !raw_key) { + error_print(); + return -1; + } memset(key, 0, sizeof(BLOCK_CIPHER_KEY)); cipher->set_decrypt_key(key, raw_key); key->cipher = cipher; @@ -35,12 +76,20 @@ int block_cipher_set_decrypt_key(BLOCK_CIPHER_KEY *key, const BLOCK_CIPHER *ciph int block_cipher_encrypt(const BLOCK_CIPHER_KEY *key, const uint8_t *in, uint8_t *out) { + if (!key || !key->cipher || !key->cipher->encrypt|| !in || !out) { + error_print(); + return -1; + } key->cipher->encrypt(key, in, out); return 1; } int block_cipher_decrypt(const BLOCK_CIPHER_KEY *key, const uint8_t *in, uint8_t *out) { + if (!key || !key->cipher || !key->cipher->decrypt|| !in || !out) { + error_print(); + return -1; + } key->cipher->decrypt(key, in, out); return 1; }