2011-10-10 185 views
0

我希望聪明的家伙会帮我:)解密的NSString与AES128加密

我收到从C#服务器加密后的文本,我不能正确解密: 我一直有一个空字符串。通常情况下,解密密钥必须

(16time)

我使用AES128算法的解密和后端给出的设置(谁加密这段文字的人)如下:

  • 填充:PKCS7Padding
  • 密钥大小:128
  • InitVector:空
  • 模式: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; 

}

感谢名单很多事先为您提供帮助。我在这个问题上很长一段时间没有在我面前回答...

回答

0

您使用的测试输入似乎没有使用PKCS7填充 - 它使用没有填充。我得到了一个成功的解密使用:

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

+0

我得到了和你相同的结论。我会尽力解决明天的问题。但如何能够使用CCCrypt没有填充。 – Amnysia

+1

只需为'options'参数传递0而不是'kCCOptionPKCS7Padding'。请注意,如果消息长度不是块大小的精确倍数,则可能必须去除尾随零字节。 – duskwuff

+0

这是工作! thanx很多 – Amnysia