Caesar Cipher in Swift

If you are at all interested in encryption and its history, then you undoubtedly heard of Caesarian cipher. The Caesar cipher was developed and used by Julius Caesar to encrypt messages between him and his generals. The mechanics behind it is to encrypt plain text by shifting each letter in the plaintext a certain number of places down the alphabet. For example, we could shift alphabet down 3 letters so that A would become D, B would become C… A would become X, etc.

I should mention that Caesarian cipher is extremely easy to decrypt. Don’t use it to encrypt sensitive data. However, I would consider it an “additional step” to already secured information. For example, when storing access token in keychain, we could encrypt it using Caesarian cipher to provide an additional layer of security. After all, it is possible to get information stored in a keychain especially if you know / get a hold of / a Mac password (this assumes keychain being synched).

With a little bit of twist, we will build an app that takes in text to be encrypted, keyword to use for encryption and then perform substitution. The results will produce encrypted text that looks something like this:

The way I am going to implement this is as follows:

  1. Generate a unique set of characters from supplied keyword. For example, “hello” would produce “helo“.
  2. Create unique alphabet by enumerating all of the characters in my key and placing them at the beginning of my newly created, substitution alphabet while removing encountered characters from their actual position in the english alphabet. I am also going to reverse my alphabet just for fun.
  3. Create encryption / decryption map to encrypt or decrypt text.

Let’s begin by creating our class and two functions:

Next step would be to write a function that takes in the supplied key and creates a unique string of characters.

Next, we will need to write two functions. First one will create an array of alphabet characters and another will reverse that array to allow for “minimal” encryption even if they key is not supplied.

Next, we need to create encryption and decryption map.

Last step is to simply implement the two functions we declared earlier:

Please note that this was written as a Playground. There are a couple of things that one might improve… moving some logic implementation to extensions, generalizing functions, etc. Feel free to make those changes if you wish.

Fully working Swift playground can be found here.

Caesar Cipher in Swift

One thought on “Caesar Cipher in Swift

Leave a Reply

Your email address will not be published. Required fields are marked *