gpt4 book ai didi

c - 如何将 IV(初始化 vector )添加到 AES-256 ECB 加密以创建 AES-256 CBC 模式?

转载 作者:太空宇宙 更新时间:2023-11-04 04:18:44 25 4
gpt4 key购买 nike

我有以下代码使用我发现的面向字节的简单 AES-256 库进行 AES-256 ECB 加密 here .

主要内容:

#define DUMP(s, i, buf, sz)  {printf(s); \
for (i = 0; i < (sz);i++) \
printf("%02x ", buf[i]); \
printf("\n");}

int main (int argc, char *argv[])
{
aes256_context ctx;
uint8_t key[32] = "39P8TXDMBCYF4C1NI1CDFJ1WL6P5TTKZ";
uint8_t buf[16] = "KUC7EWG6M2D1WW8F";
uint8_t i;

DUMP("txt: ", i, buf, sizeof(buf));
DUMP("key: ", i, key, sizeof(key));
printf("---\n");

aes256_init(&ctx, key);
aes256_encrypt_ecb(&ctx, buf);

DUMP("enc: ", i, buf, sizeof(buf));

aes256_init(&ctx, key);
aes256_decrypt_ecb(&ctx, buf);
DUMP("dec: ", i, buf, sizeof(buf));

aes256_done(&ctx);
return 0;
}

加密函数:

void aes256_encrypt_ecb(aes256_context *ctx, uint8_t *buf)
{
uint8_t i, rcon;
aes_addRoundKey_cpy(buf, ctx->enckey, ctx->key);
for(i = 1, rcon = 1; i < 14; ++i)
{
aes_subBytes(buf);
aes_shiftRows(buf);
aes_mixColumns(buf);
if( i & 1 ) aes_addRoundKey( buf, &ctx->key[16]);
else aes_expandEncKey(ctx->key, &rcon), aes_addRoundKey(buf, ctx->key);
}
aes_subBytes(buf);
aes_shiftRows(buf);
aes_expandEncKey(ctx->key, &rcon);
aes_addRoundKey(buf, ctx->key);
} /* aes256_encrypt */

我想向该程序添加 IV 以创建 AES-256 CBC 模式。据我了解,IV实现如下:

  1. 将第一个 block 与 IV 异或。
  2. XOR 所有后续 block 与前一个 block 的密文。

我的问题是逻辑是什么样的?我如何将其实现到我的代码中?

最佳答案

逻辑和解释可以在几个地方找到。例如:ECB vs CBCBlock cipher mode of operation .

CBC = 密码 block 链接是一种将 block 连接在一起的方法。

它所做的不是单独处理每个 block ,而是将每个 block 与加密的前一个 block 进行异或运算。这实际上意味着每个 block 都取决于前一个 block 的输出。

每个 block 都与前一个 block 的密文进行异或,正如引用文章中的图表所解释的那样。

在实践中,一旦一个 block 被 ECB encription 加密:

 Cipher((state_t*)buf, ctx->RoundKey);

如在

void AES_ECB_encrypt(struct AES_ctx *ctx,const uint8_t* buf)
{
// The next function call encrypts the PlainText with the Key using AES algorithm.
Cipher((state_t*)buf, ctx->RoundKey);
}

CBC 是通过 XOR 与 block 上的 IV 和同一 block 上的 ECB 并沿着缓冲区中的 block 移动来实现的。

与 IV 的异或示例:

static void XorWithIv(uint8_t* buf, uint8_t* Iv)
{
uint8_t i;
for (i = 0; i < AES_BLOCKLEN; ++i) // The block in AES is always 128bit no matter the key size
{
buf[i] ^= Iv[i];
}
}

使用 XOR 与 IV 和 ECB 的 CBC 示例:

void AES_CBC_encrypt_buffer(struct AES_ctx *ctx,uint8_t* buf, uint32_t length)
{
uintptr_t i;
uint8_t *Iv = ctx->Iv;
for (i = 0; i < length; i += AES_BLOCKLEN)
{
XorWithIv(buf, Iv);
Cipher((state_t*)buf, ctx->RoundKey);
Iv = buf;
buf += AES_BLOCKLEN;
//printf("Step %d - %d", i/16, i);
}
/* store Iv in ctx for next call */
memcpy(ctx->Iv, Iv, AES_BLOCKLEN);
}

以上实现来自tiny-AES你可能想研究它并根据你的需要进行调整。希望对您有所帮助。

关于c - 如何将 IV(初始化 vector )添加到 AES-256 ECB 加密以创建 AES-256 CBC 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48855287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com