iOS AES加密 - 加密失败

3

在我的项目中,我需要实现AES 128 CBC加密。我使用的是基于NSData的Category。这是我的加密代码:

- (NSData*)AES128Decrypt
{
    char ivPtr[kCCKeySizeAES128 + 1];
    bzero(ivPtr, sizeof(ivPtr));

    // fetch iv data
    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];


    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES128 + 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];   // dataLength = 19

    //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, 0,
                                          keyPtr, kCCKeySizeAES128,
                                          ivPtr,
                                          [self bytes], dataLength, 
                                          buffer, bufferSize, 
                                          &numBytesDecrypted);  // buffer = 0 & numBytesDecrypted = 0

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

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

这是我从视图类中调用它的方式:
- (void) testActuallyEncrypting :(NSString*) hexString {
    NSLog(@"String to Encrypt : %@", hexString); // prints test12

    @try {
    //Convert NSString to NSData
    NSData *data = [self dataFromHexString:hexString];  // [hexString dataUsingEncoding:NSUTF8StringEncoding];  //
    // // Prepare the NSDAta obj to store the encrypted pswd
    NSData *encryptedData = [NSData dataWithBytes:[data bytes] length:[data length]];  // 6bytes
    NSData *decryptedData = [encryptedData AES128Decrypt];  // 0bytes
    NSString *decryptedString = [NSString stringWithUTF8String:[decryptedData bytes]];  // NULL Exception
    NSLog(@"Decrypted String : %@", decryptedString);

    decryptedString = [self addPaddingToString:decryptedString];
    decryptedData = [NSData dataWithBytes:[decryptedString UTF8String] length:[[decryptedString dataUsingEncoding:NSUTF8StringEncoding] length]];
    encryptedData = [decryptedData AES128Encrypt];
    if (encryptedData!=nil)
    {
        NSString *encryptedHexString = [self hexStringFromData:encryptedData];
        NSLog(@"Encrypted HexString : %@",encryptedHexString);

     }
    }@catch (NSException *ex) {
        NSLog(@"Exception : %@", ex);
    }
}

我正在传递一个字符串"test12"进行加密。调用AES128Decrypt后,decryptedData为0,因此下一行decryptedString会抛出空异常-Exception : *** +[NSString stringWithUTF8String:]: NULL cString
请问有人能帮我知道为什么decryptedData为空吗? 我在AES128Decrypt方法中哪里出错了?
请帮帮我。我已经卡在这里2天了。在互联网上搜索了很多,但找不到解决方法。非常感谢任何帮助。
更新:在我的类中添加了@Zaph的方法并进行了调用。
NSLog(@"String to Encrypt : %@", hexString);
NSString *iv = @"fedcba9876543210";
NSString *key = @"0123456789abcdef";

// Convert str to encrypt, iv & key from NSString to NSData
NSData *dataIn = [hexString dataUsingEncoding:NSUTF8StringEncoding];
NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
NSData *symKey = [key dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;

NSData *result = [LoginViewController doCipher:dataIn iv:ivData key:symKey context:kCCEncrypt error:&error]; // result = 16bytes

if (result != nil) {
    // Convert result to satring
    NSString *resultStr = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    NSLog(@"Encrypted Str = %@", resultStr );  // Encrypted Str = (null)  ????

为什么转换后的字符串为null?请帮忙解决。谢谢。

2
除了捕获编程错误之外,请勿使用@try@catch。在Objective-C中,它们不是控制结构。 - zaph
我发现将NSData转换为NSString时,使用NSUTF8StringEncoding编码会返回null。我尝试使用NSASCIIStringEncoding,它返回值。但是字符串值和数据值是不同的。它们应该是相同的,不是吗? - Tvd
并非所有数据都是有效的UTF-8编码。对于数据的字符串表示,常见的约定是使用Base64编码。不要使用NSString *resultStr = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];,而应该使用Base64编码:NSString *resultBase64Str = [result base64EncodedStringWithOptions:0]; 如果使用NSASCIIStringEncoding,则会得到无法显示的字符,这可能不是您想要的结果。 - zaph
1个回答

4

不需要让加密技术变得如此复杂,以下是一种基本的加密/解密方法。IV和密钥必须具有正确的长度。值上下文可以是 kCCEncrypt 或者 kCCDecrypt

+ (NSData *)doCipher:(NSData *)dataIn
                  iv:(NSData *)iv
                 key:(NSData *)symmetricKey
             context:(CCOperation)encryptOrDecrypt
               error:(NSError **)error
{
    CCCryptorStatus ccStatus   = kCCSuccess;
    size_t          cryptBytes = 0;
    NSMutableData  *dataOut    = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeAES128];

    ccStatus = CCCrypt( encryptOrDecrypt,
                       kCCAlgorithmAES128,
                       kCCOptionPKCS7Padding,
                       symmetricKey.bytes, 
                       kCCKeySizeAES128,
                       iv.bytes,
                       dataIn.bytes,
                       dataIn.length,
                       dataOut.mutableBytes,
                       dataOut.length,
                       &cryptBytes);

    if (ccStatus == kCCSuccess) {
        dataOut.length = cryptBytes;
    }
    else {
        if (error) {
            *error = [NSError errorWithDomain:@"kEncryptionError"
                                         code:ccStatus
                                     userInfo:nil];
        }
        dataOut = nil;
    }

    return dataOut;
}

感谢您提供的代码。我将其添加到我的viewController类中。以NSData形式传递iv、key和str(iv和key为16字节),并调用方法- NSData *result = [LoginViewController doCipher:dataIn iv:ivData key:symKey context:kCCEncrypt error:&error]; 但是,当我将其转换为NSString时,结果为null。您能否检查一下上面的代码-我已将其添加到更新中。错误也为nil-因此没有错误。为什么字符串为空?您能否帮忙找出原因。 - Tvd
在获取结果后,我将其转换为字符串(只能通过NSASCIIStringEncoding工作)。然后我尝试将字符串转换回NSData。对于其中的3个值,我得到了不同的结果。它们不应该是相同的吗,或者至少都是NSData吗?毫无疑问,在解密结果并转换为字符串后,我得到了原始字符串,并且它可以正常工作。但是出于知识和好奇,我想知道这个问题的答案。谢谢。 - Tvd
在你的代码中,你使用了kCCOptionPKCS7Padding,我想这将是用于PKCS实现。我需要使用CBC。有没有关于CBC的特殊设置或参数值? - Tvd
1
kCCOptionPKCS7Padding选项适用于AES。如果输入的明文数据长度不是块大小的精确倍数,则需要该选项。 - zaph
2
并非所有数据都是有效的UTF-8字符串。通常的解决方案是使用base64编码,即将加密数据转换为base64字符串。上述代码提供了针对数据(特别是NSData)的加密/解密,也就是加密所做的事情,数据加密。如果需要其他格式,则需要在加密/解密之前和之后进行格式转换。 - zaph
非常感谢您的支持和指导。谢谢。 - Tvd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接