iOS AES加密 - 无法加密

时间:2014-05-13 17:10:52

标签: ios encryption cryptography

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

- (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为null。我在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)  ????

为什么转换后的字符串为空?请帮忙。感谢

1 个答案:

答案 0 :(得分:4)

没有必要使加密如此复杂,这是一个基本的加密/解密方法。 iv和key必须是正确的长度。值上下文可以是kCCEncryptkCCDecrypt

+ (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;
}