macOS:CCCrypt() 解密输出与原始明文不匹配



在下面的代码中,解密的文本与原始明文不匹配。前 12 个字节搞砸了。请注意,块密码填充已被禁用。我已经为BUF_SIZE尝试了不同的值,都是 16 的倍数 - 每次解密数据的前 12 个字节都是错误的。下面是输出:

    plain buf[32]:
    11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11
    11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11
    outlen=32
    outlen=32
    dec buf[32]:
    0C 08 01 46 6D 3D FC E9 98 0A 2D E1 AF A3 95 3A
    0B 31 1B 9D 11 11 11 11 11 11 11 11 11 11 11 11

代码如下:

#include <stdio.h>
#include <string.h>
#include <CommonCrypto/CommonCryptor.h>
static void
dumpbuf(const char* label, const unsigned char* pkt, unsigned int len)
{
    const int bytesPerLine = 16;
    if (label) {
        printf("%s[%d]:n", label, len);
    }
    for (int i = 0; i < int(len); i++) {
        if (i && ((i % bytesPerLine) == 0)) {
            printf("n");
        }
        unsigned int c = (unsigned int)pkt[i] & 0xFFu;
        printf("%02X ", c);
    }
    printf("n");
}
int main(int argc, char* argv[])
{
    unsigned char key[16];
    unsigned char iv[16];
    memset(key, 0x22, sizeof(key));
    memset(iv, 0x33, sizeof(iv));
#define BUF_SIZE  32
    unsigned char plainBuf[BUF_SIZE];
    unsigned char encBuf[BUF_SIZE];
    memset(plainBuf, 0x11, sizeof(plainBuf));
    dumpbuf("plain buf", plainBuf, sizeof(plainBuf));
    int outlen;
    CCCryptorStatus status;
    status = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, 0,
            key, kCCKeySizeAES128, iv, plainBuf, sizeof(plainBuf),
            encBuf, sizeof(encBuf), (size_t*)&outlen);
    if (kCCSuccess != status) {
        fprintf(stderr, "FEcipher: CCCrypt failuren");
        return -1;
    }
    printf("outlen=%dn", outlen);
    status = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0,
            key, kCCKeySizeAES128, iv, encBuf, sizeof(encBuf),
            plainBuf, sizeof(plainBuf), (size_t*)&outlen);
    if (kCCSuccess != status) {
        fprintf(stderr, "FEcipher: CCCrypt failuren");
        return -1;
    }
    printf("outlen=%dn", outlen);
    dumpbuf("dec buf", plainBuf, sizeof(plainBuf));
    return 0;
}

谢谢哈里

@owlstead,感谢您的回复。CBC 是默认值 - 您无需在选项中指定任何特殊内容即可启用它。

使用 CCCrypt() 的相同代码以前也在工作。我不知道发生了什么变化 - 可能是在更新期间安装了新库。我现在使用的是创建/更新/最终 API - 它有效,所以我有一个解决方法,而不是使用便利函数 CCCrypt() - 它有效,所以我有一个解决方法。

outlen应该是size_t,而不是int。

最新更新