Skip to main content

iOS Dev: Encryption in Objective-C

Hello Friends:
In this Article/Post, I introduced the one encryption technique in Objective-C. 

images (1)

Encryption Component Features in all 

  • Symmetric Encryption: AES, Blowfish, Twofish, RC2, ARC4, DES, 3DES, PBES1, PBES2.
  • Hash AlgorithmsSHA-1, SHA256, SHA384, SHA512, MD2, MD4, MD5, HAVAL.
  • Hash Algorithms: RIPEMD128, RIPEMD160, RIPEMD256, RIPEMD320.
  • Encoding: Base64, hex, quoted-printable, URL-encoding.
  • HMAC with any supported hash algorithm: HMAC-MD5, HMAC-SHA1, etc.
  • Password-based Key Derivation Functions: PBKDF1, PBKDF2
  • PKCS7 -- P7S and P7M creation, decryption, verification.
  • Public key encryption/decryption with digital certificates.
  • Digital signature creation/verification with digital certificates.
  • Bzip2 in-memory compression.
  • Encrypt / decrypt strings or byte data.
  • Return encrypted data as Base64, quoted-printable, or hex-encoded strings.
  • Hash strings or binary data using SHA1, MD2, MD5, HAVAL, SHA384, or SHA512.
  • Public-key encryption with digital certificates.
  • Create and verify digital signatures.
  • Pre-convert Unicode strings to ANSI (single-byte/char) before encrypting.
  • Pre-convert Unicode strings to any charset before encrypting, compressing, or hashing.
  • Base64 encode strings or byte data.
  • Hex-encode encode strings or byte data.
  • Compress strings or byte data with the BZIP2 compression algorithm.
  • Implements FIPS81 padding scheme for AES.
  • Up to 256-bit encryption is supported.
  • Set binary secret-key directly for symmetric encryption algorithms.
  • Initialization vectors.
  • CBC (Cipher Block Chaining) Mode
  • ECB (Electronic Cookbook) Mode
  • Random byte data generation.
  • Streaming hashing (pass data to hashing functions in chunks).
  • Streaming encryption (pass data to encryption functions in chunks).

Introduction

imagesHMAC is not an encryption mechanism, but an authentication digest. It uses an underlying message digest function such as SHA-1, SHA-256, MD5 etc, with a secret key to generate a code that can be used to authenticate data.
Generating an HMAC digest is extremely simple. Here is the description from RFC2104 (via Wikipedia)
Let:
  • H(·) be a cryptographic hash function (ie. SHA-1, SHA-256, MD5 etc)
  • K be a secret key padded to the right with extra zeros to the input block size of the hash function, or the hash of the original key if it's longer than that block size
  • m be the message to be authenticated
  • | denote concatenation
  • ⊕ denote exclusive or (XOR)
  • opad be the outer padding (0x5c5c5c…5c5c, one-block-long hexadecimal constant)
  • ipad be the inner padding (0x363636…3636, one-block-long hexadecimal constant)
Then HMAC(K,m) is mathematically defined by:
HMAC(K,m) = H((K ⊕ opad) | H((K ⊕ ipad) | m)).

For the underlying digest function you can help yourself to one of the C implementations from OpenSSL. In fact it also has a C implementation of HMAC_MD5 that you can probably just use like this.

Example :

Sometimes it is necessary to implement some cryptographic functions for security reasons within your iOS apps. In one of our projects I was faced with the problem of implementing some kind of a two-step registration/confirmation process with a iOS app and a corresponding server-side interface. We decided to implement this by using a generated confirmation code based on HMAC and MD5. Since there is no native support of the iOS framework to realize this, I needed to implement it on my own.
Due to this post Implementing HMAC encryption algorithm in iPhone application it was quite easy to implement a simple category for NSString to provide this functionality. The following code creates a HMAC+MD5 encrypted string based on a given secret and returns it in a hexadecimal string representation.
Code :
@implementation NSString (HMAC_MD5)
- (NSString*) HMAC_MD5_WithSecretString:(NSString*)secret{
    CCHmacContext    ctx;
    const char       *key = [secret UTF8String];
    const char       *str = [self UTF8String];
    unsigned char    mac[CC_MD5_DIGEST_LENGTH];
    char             hexmac[2 * CC_MD5_DIGEST_LENGTH + 1];
    char             *p;
    CCHmacInit( &ctx, kCCHmacAlgMD5, key, strlen( key ));
    CCHmacUpdate( &ctx, str, strlen(str) );
    CCHmacFinal( &ctx, mac );
    p = hexmac;
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++ ) {
        snprintf( p, 3, "%02x", mac[ i ] );
        p += 2;
    }
    return [NSString stringWithUTF8String:hexmac];
}
@end

Calling Technique:

NSString *stringToEncrypt  = @"encryptedTextByNiketanMishra";
NSString *secret           = @"SECRET_KEY";
NSString *hexHmac          = [stringToEncrypt HMAC_MD5_WithSecretString:secret];
NSLog(@"HMAC_MD5 in hex is %@", hexHmac);

Output : HMAC_MD5 in hex is 193e7a3ee3ec7bcc70bf3ddbcdd63fdf

Download Here

Other Information:
Use the Common Crypto functions (See Apple Links). They're in libSystem on iOS and Mac OS X, so no need to add another library or framework to your project. As you can see from the example below, the API is very similar to
OpenSSL's.

Here the original Code :

#include <CommonCrypto/CommonHMAC.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
extern int      errno;
    int
main( int ac, char *av[] )
{
    CCHmacContext    ctx;
    char             *key = "secret";
    char             buf[ 8192 ];
    unsigned char    mac[ CC_MD5_DIGEST_LENGTH ];
    char             hexmac[ 2 * CC_MD5_DIGEST_LENGTH + 1 ];
    char             *p;
    int              fd;
    int              rr, i;
    if ( ac != 2 ) {
        fprintf( stderr, "usage: %s path\n", av[ 0 ] );
        exit( 1 );
    }
    if (( fd = open( av[ 1 ], O_RDONLY )) < 0 ) {
        fprintf( stderr, "open %s: %s\n", av[ 1 ], strerror( errno ));
        exit( 2 );
    }
download (1) 
Let me know if you have any problem and queries regarding this post.
Thanks ..
download
Happy Coding :)

Comments

Post a Comment

Popular posts from this blog

WPF-MVVM: RelayCommand Implementation

In WPF if we are implementing MVVM pattern then we need to play with Command rather than Events. You can use ICommand interface to create each command class. Implementation of ICommand in a class gives you CanExecute(), Execute() methods which take part in the action performed by Command.   Rather than making Command Class for each Command we can implement a generic Relay Command to get Command. Below is a RelayCommand class that we will implement.   ///   <summary>      ///  To register commands in MMVM pattern      ///   </summary>      class   RelayCommands  :  ICommand     {          readonly   Action < object > _execute;          readonly   Predicate < object > _canExecute;  ...

Reactive Extensions (Rx)

Reactive Extensions (Rx) What is Rx Rx is a library for composing asynchronous and event-based programs using observable collections. Using Rx, developers represent asynchronous data streams with Observables, query asynchronous data streams using LINQ operators, and parameterize the concurrency in the asynchronous data streams using Schedulers. Simply put, Rx = Observables + LINQ + Schedulers. The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. Whether you are authoring a traditional desktop or web-based application, you have to deal with asynchronous and event-based programming from time to time. Desktop applications have I/O operations and computationally expensive tasks that might take a long time to complete and potentially block other active threads. Furthermore, handling exceptions, cancellation, and synchronization is difficult and error-prone. Thr...