iOS AES Encryption - Fail to Encrypt

前端 未结 1 443
花落未央
花落未央 2020-11-28 15:03

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
{
         


        
相关标签:
1条回答
  • 2020-11-28 15:43

    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;
    }
    
    0 讨论(0)
提交回复
热议问题