Iphone 使用AES128加密解密NSString

Iphone 使用AES128加密解密NSString,iphone,ios,encryption,Iphone,Ios,Encryption,我希望一个聪明的人能帮助我: 我从C服务器收到加密文本,但无法正确解密: 我总是有一个空字符串。通常,解密的密钥应该是 1111111111111111 16次 我使用AES128算法进行解密,并使用后端提供的设置对该文本进行加密的人员如下所示: 填充:PKCS7Padding 密钥大小:128 InitVector:null 模式:CBC 要解密base64编码的文本:1vycDn3ktoyaUkPlRAIlsA== 钥匙:3a139b187647a66d 下面是我用于解密的代码 - (NSD

我希望一个聪明的人能帮助我:

我从C服务器收到加密文本,但无法正确解密: 我总是有一个空字符串。通常,解密的密钥应该是

1111111111111111

16次

我使用AES128算法进行解密,并使用后端提供的设置对该文本进行加密的人员如下所示:

填充:PKCS7Padding 密钥大小:128 InitVector:null 模式:CBC 要解密base64编码的文本:1vycDn3ktoyaUkPlRAIlsA== 钥匙:3a139b187647a66d 下面是我用于解密的代码

- (NSData *)AES256DecryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES2128+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

NSUInteger dataLength = [self length];

//See the doc: For block ciphers, the output size will always be less than or 
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);

size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                 keyPtr, kCCKeySizeAES128,
                                 NULL /* initialization vector (optional) */,
                                 [self bytes], dataLength, /* input */
                                 buffer, bufferSize, /* output */
                                 &numBytesDecrypted);

if (cryptStatus == kCCSuccess) {
    //the returned NSData takes ownership of the buffer and will free it on deallocation
    return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}

free(buffer); //free the buffer;
return nil;
}


谢谢你的帮助。我一直在讨论这个问题,很久没有答案了…

您使用的测试输入似乎没有使用PKCS7填充-它没有使用填充。我能够使用以下方法成功解密:

echo 1VYCDN3KTOOKPLRAILSA==| openssl enc-aes-128-cbc-d-a-K`echo 3a139b187647a66d | xxd-ps`-iv 0-nosalt-nopad


我得出的结论和你一样。我明天会设法解决这个问题。但是如何在没有填充的情况下使用CCCrypt。只需为options参数传递0,而不是kCCOptionPKCS7Padding。请注意,如果消息长度不是块大小的精确倍数,则可能必须去掉尾随的零字节。但正如您所说,当消息长度不是块大小的精确倍数时,会出现问题。我肯定这是个愚蠢的问题,但是:如何去掉零字节的跟踪?我对加密这门学科很陌生。谢谢你的帮助。我非常感激