iOS AES128 Encryption and Decryption

Why I am giving the following steps instead of direct link is. The link is changing frequently I guess or they are updating the article or code itself. I saw the method names got changed.

Follow the steps.

  1. Go to http://iphonedevcentral.blogspot.in.
  2. Top left corner, you see search box. Search for Strong Encryption.
  3. Read the article and down the data from the link provided.

 

Code:

kCCOptionECBMode : Electronic Code Book (ECB). Electronic Code Book (ECB) is a mode of operation for a block cipher, with the characteristic that each possible block of plaintext has a defined corresponding ciphertext value and vice versa. In other words, the same plaintext value will always result in the same ciphertext value. Electronic Code Book is used when a volume of plaintext is separated into several blocks of data, each of which is then encrypted independently of other blocks. In fact, Electronic Code Book has the ability to support a separate encryption key for each block type.

Cited the above definition from http://searchsecurity.techtarget.com/definition/Electronic-Code-Book.

CCCrypt is the apple api that actually encrypts or decrypts based on the parameters passed to it.

kCCAlgorithmAES128 is the algorithm to use to encrypt or decrypt. It will successfully encrypt or decrypt only 15 characters, because the buffer size accepts 16 characters. Last character space is for termination character ‘\0’.

If you send more than 15 characters then you will face issue in decryption. So in order to encrypt more than 15 characters then you need to pass kCCOptionECBMode in options. That will internally split the characters and encrypt and provide you the result. In decryption also you mention this mode.

   CCCryptorStatus cryptStatus = CCCrypt( kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode + kCCOptionPKCS7Padding,

                                          keyPtr, kCCKeySizeAES256,

                                          NULL /* initialization vector (optional) */,

                                          [self bytes], dataLength, /* input */

                                          buffer, bufferSize, /* output */

                                          &numBytesEncrypted );

Useful Links:

  1. https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
  2. https://de.wikipedia.org/wiki/Electronic_Code_Book_Mode
  3. https://www.tutorialspoint.com/cryptography/block_cipher_modes_of_operation.htm
Advertisements

UIPageViewController that has UIPageControl with different dot colours

 Customise page control

  1. Create page control subclassing UIView
  2. Draw the coloured dots in - (void) drawRect:(CGRect) rect
  3. Control the touch events using - (void) touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event
  4. Inform page view controller when user touch it using delegation.

Customise page view controller

  1. Override - (void) viewDidLayoutSubviews and search all the subviews and find the UIPageControl instance.
  2. Hide the UIPageControl instance and add the custom page control instance to its superview.
  3. Set the UIPageControl instance frame to custom page control.
  4. Bring the custom page control using [self.view bringSubviewToFront:pageControl];
  5. When custom page control informs you about the user touch then call the method - (void)setViewControllers:(nullable NSArray *)viewControllers direction:(UIPageViewControllerNavigationDirection)direction animated:(BOOL)animated completion:(void (^ __nullable)(BOOL finished))completion; to move to right or left page.

Page view controller delegate

  1. Update custom control page dots/index using
    - (void) pageViewController:(COPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *) previousViewControllers transitionCompleted:(BOOL) completed
  2. This method - (void) pageViewController:(COPageViewController *)pageViewController willTransitionToViewControllers:(NSArray *) pendingViewControllers will start when user swipes the page. What I did is maintained a variable that tells whether the page is still in transition, based on that I will allow the user interaction with custom page control.

 

Present notification from foreground

iOS 10 adds the UNUserNotificationCenterDelegate protocol for handling notifications while your app is in the foreground.

- (void) userNotificationCenter:(UNUserNotificationCenter *) center
willPresentNotification:(UNNotification *) notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions options)) completionHandler
{
NSLog(@"Present notification from foreground");
completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound);
}

iPv6 Network not available issue

+ (instancetype)  reachabilityForInternetConnection
{

Reachability *reach = NULL;
NetworkStatus status = NotReachable;

struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;

reach = [self reachabilityWithAddress: (const struct sockaddr *) &zeroAddress];

if  (reach != NULL)
{

status = [reach currentReachabilityStatus];

if (status != NotReachable)
{

NSLog(@”Connected to Ipv4 Environment”);

return reach;

}

}

if  ([[UIDevice currentDevice].systemVersion floatValue] < 9.0)
{

// check whether you are in iPv6 environment

struct sockaddr_in6 zeroAddress1;
bzero(&zeroAddress1, sizeof(zeroAddress1));
zeroAddress1.sin6_len = sizeof(zeroAddress1);
zeroAddress1.sin6_family = AF_INET6;

reach = [self reachabilityWithAddress: (const struct sockaddr *) &zeroAddress1];

if  (reach != NULL)
{

status = [reach currentReachabilityStatus];

if (status != NotReachable)
{

NSLog(@”Connected to Ipv6 Environment”);

}

}

}

return reach;

}

CoreTelephony CTCallCenter

The [[CTCallCenter alloc] init] must be run in the main queue. Is it thread safe ??? Better call it on main thread only.

There is an iOS bug that causes instances of the CTCallCenter class to sometimes get notifications after they have been deallocated. Instead of instantiating, using, and releasing instances you must instead retain and never release them to work around the bug.

static CTCallCenter *netInfo; static dispatch_once_t dispatchToken; if (!netInfo) { dispatch_once(&dispatchToken, ^{ netInfo = [[CTCallCenter alloc] init]; }); }

 

How to programmatically know Bluetooth headset is connected to iOS device

Call this method to find out the bluetooth headset is connected or not.

 

- (BOOL) isBluetoothHeadsetConnected
{
    AVAudioSession *session = [AVAudioSession sharedInstance];
    AVAudioSessionRouteDescription *routeDescription = [session currentRoute];

    DEBUGLOG(@"Current Routes : %@", routeDescription);

    if (routeDescription)
    {
        NSArray *outputs = [routeDescription outputs];

        if (outputs && [outputs count] > 0)
        {
            AVAudioSessionPortDescription *portDescription = [outputs objectAtIndex:0];
            NSString *portType = [portDescription portType];

            DEBUGLOG(@"dataSourceName : %@", portType);

            if (portType && [portType isEqualToString:@"BluetoothA2DPOutput"])
            {
                return YES;
            }
        }
    }

    return NO;
}

How to enable or disable Proximity sensor programmatically in iPhone

Use the following API to enable/disable the proximity sensor.

[UIDevice currentDevice].proximityMonitoringEnabled = NO; // Disables the Proximity Sensor

[UIDevice currentDevice].proximityMonitoringEnabled = YES; // Enables the Proximity Sensor

Not all iOS devices have proximity sensors. To determine if proximity monitoring is available, attempt to enable it. If the value of the proximityMonitoringEnabled property remains NO, proximity monitoring is not available.