iOS AES 加密 - 加密失败 [英] iOS AES Encryption - Fail to Encrypt

查看:32
本文介绍了iOS AES 加密 - 加密失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my project I got to implement AES 128 CBC Encryption. I am using Category and is based on NSData. This is my encryption code :

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

这就是我在视图类中调用它的方式:

And this is how I am calling it from my view class :

- (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 抛出 Null 异常 - Exception : *** +[NSString stringWithUTF8String:]: NULL cString.

I am passing "test12" string to be encrypted. On calling AES128Decrypt, decryptedData is 0, due to which the next line decryptedString throws Null exception - Exception : *** +[NSString stringWithUTF8String:]: NULL cString.

谁能帮我知道为什么解密数据为空.AES128Decrypt 方法哪里出错了?

Can anyone help me know why the decryptedData is null. Where am I going wrong in the AES128Decrypt method ?

请帮帮我.从过去 2 天开始,我一直坚持这一点.在互联网上搜索了很多,但无法找到任何解决方案来解决它.任何帮助都受到高度赞赏.谢谢.

Please help me. I am stuck on this from last 2 days. Searched on this a lot on internet, but couldn't get any solution to get thru it. Any help is highly appreciated. Thanks.

更新:-在我的班级中添加了@Zaph 的方法并正在调用它.

UPDATE :- Added @Zaph's method in my class and am calling it.

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)  ????

为什么转换后的字符串为空?请任何帮助.谢谢

Why the converted string is null ? Any help please. Thanks

推荐答案

没有必要让加密变得如此复杂,这里是一个基本的加密/解密方法.iv 和 key 的长度必须正确.值上下文是 kCCEncryptkCCDecrypt.

There is no need to make the crypto so complicated, here is a basic encrypt/decrypt method. The iv and key must be the correct length. The value context is either kCCEncrypt or 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;
}

这篇关于iOS AES 加密 - 加密失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆