AES Encryption for an NSString on the iPhone

前端 未结 5 1440
陌清茗
陌清茗 2020-11-22 05:56

Can anybody point me in the right direction to be able to encrypt a string, returning another string with the encrypted data? (I\'ve been trying with AES256 encryption.) I w

5条回答
  •  囚心锁ツ
    2020-11-22 06:51

    I waited a bit on @QuinnTaylor to update his answer, but since he didn't, here's the answer a bit more clearly and in a way that it will load on XCode7 (and perhaps greater). I used this in a Cocoa application, but it likely will work okay with an iOS application as well. Has no ARC errors.

    Paste before any @implementation section in your AppDelegate.m or AppDelegate.mm file.

    #import 
    
    @implementation NSData (AES256)
    
    - (NSData *)AES256EncryptWithKey:(NSString *)key {
        // 'key' should be 32 bytes for AES256, will be null-padded otherwise
        char keyPtr[kCCKeySizeAES256+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 numBytesEncrypted = 0;
        CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                         keyPtr, kCCKeySizeAES256,
                                         NULL /* initialization vector (optional) */,
                                         [self bytes], dataLength, /* input */
                                         buffer, bufferSize, /* output */
                                         &numBytesEncrypted);
        if (cryptStatus == kCCSuccess) {
            //the returned NSData takes ownership of the buffer and will free it on deallocation
            return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
        }
    
        free(buffer); //free the buffer;
        return nil;
    }
    
    - (NSData *)AES256DecryptWithKey:(NSString *)key {
        // 'key' should be 32 bytes for AES256, will be null-padded otherwise
        char keyPtr[kCCKeySizeAES256+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, kCCKeySizeAES256,
                                         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;
    }
    
    @end
    

    Paste these two functions in the @implementation class you desire. In my case, I chose @implementation AppDelegate in my AppDelegate.mm or AppDelegate.m file.

    - (NSString *) encryptString:(NSString*)plaintext withKey:(NSString*)key {
        NSData *data = [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
        return [data base64EncodedStringWithOptions:kNilOptions];
    }
    
    - (NSString *) decryptString:(NSString *)ciphertext withKey:(NSString*)key {
        NSData *data = [[NSData alloc] initWithBase64EncodedString:ciphertext options:kNilOptions];
        return [[NSString alloc] initWithData:[data AES256DecryptWithKey:key] encoding:NSUTF8StringEncoding];
    }
    

提交回复
热议问题