iDev: 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).


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)


  • 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];



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


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;


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 ..


Happy Coding 🙂

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s