Skip to content

Commit

Permalink
Change iv behavior in sm4_cbc_encrypt_blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
guanzhi committed May 13, 2024
1 parent 1e2b75f commit a98be7f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 9 deletions.
4 changes: 2 additions & 2 deletions src/sm4.c
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ void sm4_encrypt_blocks(const SM4_KEY *key, const uint8_t *in, size_t nblocks, u
void sm4_cbc_encrypt_blocks(const SM4_KEY *key, uint8_t iv[16],
const uint8_t *in, size_t nblocks, uint8_t *out)
{
uint8_t *piv = iv;
const uint8_t *piv = iv;

while (nblocks--) {
size_t i;
Expand All @@ -190,7 +190,7 @@ void sm4_cbc_encrypt_blocks(const SM4_KEY *key, uint8_t iv[16],
void sm4_cbc_decrypt_blocks(const SM4_KEY *key, uint8_t iv[16],
const uint8_t *in, size_t nblocks, uint8_t *out)
{
uint8_t *piv = iv;
const uint8_t *piv = iv;

while (nblocks--) {
size_t i;
Expand Down
20 changes: 14 additions & 6 deletions src/sm4_arm64.c
Original file line number Diff line number Diff line change
Expand Up @@ -184,34 +184,42 @@ void sm4_encrypt_blocks(const SM4_KEY *key, const uint8_t *in, size_t nblocks, u
}
}

void sm4_cbc_encrypt_blocks(const SM4_KEY *key, const uint8_t iv[16],
void sm4_cbc_encrypt_blocks(const SM4_KEY *key, uint8_t iv[16],
const uint8_t *in, size_t nblocks, uint8_t *out)
{
const uint8_t *piv = iv;

while (nblocks--) {
size_t i;
for (i = 0; i < 16; i++) {
out[i] = in[i] ^ iv[i];
out[i] = in[i] ^ piv[i];
}
sm4_encrypt(key, out, out);
iv = out;
piv = out;
in += 16;
out += 16;
}

memcpy(iv, piv, 16);
}

void sm4_cbc_decrypt_blocks(const SM4_KEY *key, const uint8_t iv[16],
void sm4_cbc_decrypt_blocks(const SM4_KEY *key, uint8_t iv[16],
const uint8_t *in, size_t nblocks, uint8_t *out)
{
const uint8_t *piv = iv;

while (nblocks--) {
size_t i;
sm4_encrypt(key, in, out);
for (i = 0; i < 16; i++) {
out[i] ^= iv[i];
out[i] ^= piv[i];
}
iv = in;
piv = in;
in += 16;
out += 16;
}

memcpy(iv, piv, 16);
}

static void ctr_incr(uint8_t a[16]) {
Expand Down
5 changes: 4 additions & 1 deletion tests/sm4_cbc_mactest.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ static int test_sm4_cbc_mac(void)
SM4_KEY sm4_key;
SM4_CBC_MAC_CTX ctx;
uint8_t key[16];
uint8_t iv[16] = {0};
const uint8_t civ[16] = {0};
uint8_t iv[16];
uint8_t m[128];
uint8_t c[128];
uint8_t mac1[16];
Expand All @@ -34,6 +35,7 @@ static int test_sm4_cbc_mac(void)
sm4_set_encrypt_key(&sm4_key, key);

// test 1
memcpy(iv, civ, 16);
sm4_cbc_encrypt_blocks(&sm4_key, iv, m, sizeof(m)/16, c);
memcpy(mac1, c + sizeof(m) - 16, 16);

Expand All @@ -56,6 +58,7 @@ static int test_sm4_cbc_mac(void)

// test 2
m[sizeof(m) - 1] = 0;
memcpy(iv, civ, 16);
sm4_cbc_encrypt_blocks(&sm4_key, iv, m, sizeof(m)/16, c);
memcpy(mac1, c + sizeof(m) - 16, 16);

Expand Down

0 comments on commit a98be7f

Please sign in to comment.