in Encryption, Objective-C, Programming

Encrypt data using AES and 256-bit keys

AES stands for Advanced Encryption Standard and is an industry-standard algorithm for encrypting data symmetrically which even the US government has approved for SECRET documents. If you don’t know what symmetrical encryption is, it means that you use the same key or password to encrypt the data as you do to unencrypt it. So you need to keep the key extremely secret however it’s still incredibly useful. I’ll show you how to use openssl to encrypt some data and decrypt it using the Common Crypto libraries on iOS.

AES Key Size

First a bit about key size… a key can be considered a password to decrypt the data with except with a password you are limited to characters you can type, to keep it simple lets say this was 26 letters + 10 numbers or 36 characters, if you had a password that was 1 character long you’d have 36 possible combinations to try to un-encrypt your data with. If you had a 2 character password you’d have 36 x 36 (362) which would be 1,296 combinations, and 3 characters would mean 36 x 36 x 36 (363) or 46,656 combinations. This increases exponentially with the length of the password.

Now characters are just represented as numbers on most computers these days so why not just skip straight to numbers? If you had a key which was one bit long (21), you’d have 2 combinations as it could just be a 0 or a 1. If you had a key which was 2 bits long (22) you’d have 4 combinations, 3 bits long (23 ) so with a 128 bit key you’d have (2128) 340,282,366,920,938,463,463,374,607,431,768,211,456 combinations. To put that into perspective, it’s estimated the whole world has 5,000,000,000,000,000,000,000 grains of sand and with a 128-bit key you’d still have to search every grain of sand on 68,000,000,000,000,000 earth-like planets. That means 128-bit keys are pretty secure if someone was to try every single combination (a brute force attack). Now imagine how many combinations there must be for a 256-bit key… yes basically 2256 possible combinations and don’t forget that even going from a 128-bit key to a 129-bit key would not just double the combinations, it would increase it exponentially! In summary if you’re going for key size, a 128-bit key would be more than enough and a 256-bit key would be so huge it would probably slow down even a quantum brute-force attack… probably! However bigger isn’t always better and a 256-bit key uses more processing power so it’s something to think about…

IV – the bit twister

It gets a bit complicated but the CommonCrypto library defaults to using Cipher Block Chaining (CBC) for the Block Cipher Mode. Without going into too much detail, the plaintext you’d like to encrypt gets broken up into small blocks of data and starting with the first block of data the AES algorithm gets applied and used in the calculation for encrypting the next block. That means each block is dependant on the previous block being calculated – hence the “chaining” of blocks. However this exposes a problem: if you have two pieces of data you encrypt using the same key and the first few blocks are the same you’ll find that with the two encrypted pieces of data the beginning of both pieces are the same. This might not seem like a big deal at first but an attacker will know you used the same key and could use this to work out statistical differences with each block and in turn predict the contents and/or work out the key.

For AES, regardless of key size the block size is 128-bits long which if we assume 8-bits per character would mean each block is 16 characters in length. Enough theory, lets see it in action with OpenSSL in the terminal on Mac OS X!

We use a key of secretpassword and use interactive mode which allows Ctrl+D to finish and output the encrypted cipher text in Base64 format.

Now lets try another message using the same settings:

By comparing the two ciphertexts above you can see the beginning block ‘VVklkPrL5fczxmu4vZ93B’ is the same:

If we knew the contents of one of the messages, perhaps lets say from a captured U-Boat, we could work out when a message was addressed to Mr Warrender without ever knowing the key! The same principle holds true for file formats, transfer protocols and other data you encrypt but how do you fix it?

The solution is to use a unique Initialisation Vector or an IV with CBC mode. This adjusts the initial plaintext block by a certain amount and since each block is chained, every subsequent block is different every time even if you encrypt the same message twice. As long as you use a different IV for every message it will result in a completely different ciphertext.

Typically for AES the IV is the size of a block so the IV is 128-bits long. With openssl you can specify the IV using hex.

By comparing the results with the same message, same key and different IV we can see the blocks don’t match which is just what we wanted!

Now you can store the IV with the key or prepend it to the encrypted payload, it doesn’t matter too much as long as you use the same IV to decrypt with and obviously the key should always remain private. However make sure you use a unique IV for each message!

Wait… The IV is not a key!

It’s tempting to think that the IV is an extra layer of encryption except it isn’t. In-fact you don’t even need the IV to decrypt the majority of a message. Remember how block chaining worked? You took the ciphertext from the current block and used that to help you encrypt the plaintext for the next block…

When decrypting we work backwards and because we used the adjacent ciphertext block before encrypting, we need to remove it. However as you can see below, we already have the ciphertext because we’re decrypting! Hence only block 1 gets corrupted because we don’t know the IV to remove.

Decrypting AES in iOS

So you have your hex-encoded AES 256-bit key:

You have your hex-encoded IV and your Base64-encoded ciphertext:

Now to decrypt it… place the following code into a category named NSData+AES256Encryption.

Now in your view controller or wherever you want to decrypt place the following code:

As you can see in the code we set the ciphertext, key and IV examples we created using openssl earlier and decoded them. Run the code and you should see “Decrypted Result: Hello Mr Warrender, This is good news” printed twice in the console. Congratulations, you just decoded encrypted text using AES-256 encryption!

CommonCrypto’s CCCrypt C function looks very scary but it’s actually really easy to use. Most of the code in the category involves getting the raw bits from the hex strings and putting them into C byte arrays. As we’re using C functions we have to calculate how long our arrays are since we just pass around pointers to them.

The 1st parameter is a constant to tell the CCCrypt function to decrypt your text.

The 2nd parameter is a const which specifies which algorithm to use – that’s where you specify to use the AES cipher.

The 3rd parameter needs some explaining, this specifies we want to use PKCS #7 Padding. AES is a block cipher because we break our plaintext up into blocks, however if our data doesn’t evenly fit into a block we’ll have to pad it with null characters which would work for printing simple C strings because a null character indicates the end of a string but for images or other data this isn’t what we want. Instead we specify to use the PKCS #7 padding algorithm to pad the block and get back the same data we encrypted. Note: openssl uses PKCS #5 padding algorithm but they are basically the same, that might save you a few hours!

The 4th parameter is a pointer containing your raw key byte array.

The 5th parameter specifies how long your key is – you can use AES256 or AES128 enum consts here.

The 6th parameter is the raw IV byte array pointer. You don’t need a size/length here because it will always be the same as the block size.

The 7th and 8th parameters are the raw byte array pointer and array size of the ciphertext.

The 9th and 10th parameters are the buffer byte pointer and buffer size of where the plaintext will go.

The 11th parameter is an size pointer that will be populated with the size of the data that was decrypted.

Encrypting AES in iOS

Lets test the encryption from the iOS code. Now to ensure everything is correct, we encrypted a message back using a new IV but with the same details. Cut and paste the following from the console and paste into a file called test.enc.

Now we’ll use the -d (switch to decrypt) and -in (load a file) options of the openssl enc command to decrypt the message stored in test.enc using our previous key. Note we’re using a different IV!

Type the following into the terminal:

Awesome, that’s great! We’ve successfully decoded our message using openssl we encrypted using iOS. Hopefully that’s shown you how to encrypt and decrypt AES protected data with 256-bit keys. You should also now understand about keys, block cipher modes and a bit about why IVs help protect data. Have fun and good luck protecting your user data.

Write a Comment

Comment

  1. In this situation when we get success in either encrypting or decrypting data
    if( cryptStatus == kCCSuccess )
    {
    // The returned NSData takes ownership of the buffer and will free it on deallocation
    return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }
    We did not free the buffer. Why?

    • In the NSData docs under Discussion it says [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted] takes ownership of the bytes pointer and frees it on deallocation. Hence it only needs to be freed if the cryptStatus fails.

      In other words once we wrap the bytes up in NSData we can let the system free it. Hope that helps!

  2. why getting garbage data after decryption
    if( cryptStatus == kCCSuccess )
    {
    // The returned NSData takes ownership of the buffer and will free it on deallocation
    return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }