PKCS#7 C 中 AES 加密的填充问题

问题描述 投票:0回答:1

这个问题已经解决了,我在帖子底部包含了解决方案代码。

Python 和 C# 有两个程序,我正在尝试用 C 语言制作一个版本。我正在尝试使用 Tiny AES Library 创建一个在 CBC 模式下使用 AES-256 加密文本的函数。我把Python和C#,以及我自己的C代码放在下面。

Python 代码

import os
from cryptography.hazmat.primitives.ciphers import (algorithms, modes, Cipher)
from cryptography.hazmat.primitives.padding import PKCS7

text = "6bcdax94cvrdnhvo"
key = "7copiqupo7cpaq7c9u7qab84rpc16gvk"

encodedText = text.encode()
encodedKey = key.encode()

iv = encodedKey[:16]

cipher = Cipher(algorithms.AES(encodedKey), modes.CBC(iv))
encryptor = cipher.encryptor()

padder = PKCS7(128).padder()
pad = padder.update(encodedText) + padder.finalize()
print(encryptor.update(pad))

C# 代码

using System.Text;
using System.Security.Cryptography;

string text = "6bcdax94cvrdnhvo";
string key = "7copiqupo7cpaq7c9u7qab84rpc16gvk";

byte[] byteKey= Encoding.ASCII.GetBytes(key);

Aes aesAlg = Aes.Create();
aesAlg.Mode = CipherMode.CBC;
aesAlg.Key = byteKey;
aesAlg.IV = byteKey[0..16];

ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
byte[] encrypted = encryptor.TransformFinalBlock(Encoding.ASCII.GetBytes(text), 0, Encoding.ASCII.GetBytes(text).Length);
encryptor.Dispose();

string plainText = BitConverter.ToString(encrypted);
plainText = plainText.Replace("-", "");

Console.WriteLine($@"{plainText}");

C 代码

#include <stdint.h>
#include "aes.h"

int main()
{
    uint8_t text[16] = "6bcdax94cvrdnhvo";
    uint8_t key[32] = "7copiqupo7cpaq7c9u7qab84rpc16gvk";
    uint8_t iv[16];

    int i;
    for (i = 0; i < 16; i++) {
        iv[i] = key[i];
    }

    struct AES_ctx ctx;

    AES_init_ctx_iv(&ctx, key, iv);
    AES_CBC_encrypt_buffer(&ctx, text, 16);

    for (i = 0; i < 16; i++) {
        printf("%.2x", text[i]);
    }

    return 0;
}

Python 和 C# 程序都将“9192D9DACF7E02D06F00DB82DFED3E3764C159683BE158F76D95114288F512EA”打印到标准输出(控制台)。

虽然我的 C 程序打印“9192d9dacf7e02d06f00db82dfed3e37”并增加 for 循环的长度不会返回正确的值,但仅返回随机其他十六进制数据,例如(9192d9dacf7e02d06f00db82dfed3e3737636f70697175706f376370617137 63).

需要明确的是,问题在于程序输出之间的最后 16 个字符之间的差异。 它应该是 - 9192D9DACF7E02D06F00DB82DFED3E3764C159683BE158F76D95114288F512EA 但实际上是 - 9192d9dacf7e02d06f00db82dfed3e3737636f70697175706f37637061713763

我已尝试尽可能多地进行研究,我认为问题与 PKCS#7 填充有关,但我不完全确定。

任何有助于实现所需输出的帮助都会很棒,提前谢谢您。

编辑:修复粗体文本

c# c aes pkcs#7
1个回答
0
投票

通过手动将 0x10 值插入数组末尾解决了这个问题。

int main()
{
    uint8_t text[32 + 1] = "6bcdax94cvrdnhvo";
    uint8_t key[32 + 1] = "7copiqupo7cpaq7c9u7qab84rpc16gvk";
    uint8_t iv[16 + 1];

    int i;
    for (i = 0; i < 32; i++) {
        if (i >= 16) {
            text[i] = 0x10;
        }
    }

    for (i = 0; i < 16; i++) {
        iv[i] = key[i];
    }

    struct AES_ctx ctx;

    AES_init_ctx_iv(&ctx, key, iv);
    AES_CBC_encrypt_buffer(&ctx, text, 32);

    for (i = 0; i < 32; i++) {
        printf("%.2x", text[i]);
    }
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.