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

macos:CCCrypt()解密输出与原始明文不匹配,macos,encryption,Macos,Encryption,在下面的代码中,解密的文本与原始明文不匹配。前12个字节搞乱了。请注意,已禁用分组密码填充。我尝试了不同的BUF_大小值,都是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

在下面的代码中,解密的文本与原始明文不匹配。前12个字节搞乱了。请注意,已禁用分组密码填充。我尝试了不同的BUF_大小值,都是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 failure\n");
        return -1;
    }
    printf("outlen=%d\n", 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 failure\n");
        return -1;
    }
    printf("outlen=%d\n", outlen);
    dumpbuf("dec buf", plainBuf, sizeof(plainBuf));
    return 0;
}
#包括
#包括
#包括
静态空隙
dumpbuf(常量字符*标签,常量无符号字符*pkt,无符号整数len)
{
const int bytesPerLine=16;
如果(标签){
printf(“%s[%d]:\n”,标签,len);
}
对于(int i=0;i
谢谢,
哈里

@owlstead,谢谢你的回复。CBC是默认的-您不需要在选项中指定任何特殊的内容来启用它


以前使用CCCrypt()的代码也是一样。我不知道发生了什么变化-可能是在更新过程中安装了新的库。我现在使用的不是方便函数CCCrypt(),而是Create/Update/Final API—它可以工作,所以我有一个解决方法。

outlen应该是size\u t,而不是int。

我目前还没有看到错误,我想您必须调试代码才能看到错误。我知道在选项中指定IV而不指定CBC模式没有什么意义。