【问题标题】:Decrypt NSString with AES128 encryption使用 AES128 加密解密 NSString
【发布时间】:2011-10-11 03:58:36
【问题描述】:

我希望聪明的人能帮助我:)

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

1111111111111111

(16次)

我使用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;

}

非常感谢您的帮助。我在这个问题上很久了,我面前没有答案......

【问题讨论】:

    标签: iphone ios encryption


    【解决方案1】:

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

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

    【讨论】:

    • 我得出的结论和你一样。明天我会尽力解决这个问题。但是如何能够在没有填充的情况下使用 CCCrypt。
    • 只需为 options 参数传递 0 而不是 kCCOptionPKCS7Padding。请注意,如果消息长度不是块大小的精确倍数,您可能必须去除尾随的零字节。
    • 但是正如你所说,当消息长度不是块大小的确切倍数时存在问题。我敢肯定这是一个愚蠢的问题,但是:你如何去掉尾随的零字节?我是加密主题的新手。非常感谢您的帮助。非常感谢
    猜你喜欢
    • 2011-03-12
    • 1970-01-01
    • 2013-03-01
    • 2020-04-07
    • 2011-02-18
    • 2011-12-10
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    相关资源
    最近更新 更多