SwiftKeyEncoder

Tool for encoding embedded keys in Swift projects.

Why do we need to encode our secrets in code?

Storing keys as strings in Swift code is very insecure because they can be parsed easily using reverse engineering software. This utility helps to embed your key as an encoded array of bytes, which is almost impossible to reverse engineer.

How to use

  1. Generate a random set of bytes that will be used to XOR your key. The size of this mask must be greater than or equal to the length of your key. Use the following command to generate a random set of 32 bytes in macOS Terminal:
head -c32 /dev/random | xxd -i

If you need a mask larger than 32 bytes, replace 32 in the command arguments.

  1. Open the SwiftKeyEncoder.playground in Xcode
  2. Copy the generated mask from the Terminal to the mask variable
  3. Put your key and variable name as arguments to the printEncodedKey function.
  4. Run the playground
  5. Copy encoded key and the mask from the Console Output to your code
  6. Copy KeyDecoder.swift to your project
  7. Use func decode(bytes: [UInt8], mask: [UInt8]) -> String public method in your project to decode the key to a string.

Example:

let mask: [UInt8] = [
    0x3a, 0x4c, 0x09, 0xf8, 0xfb, 0x8d, 0x84, 0xa0, 0x36, 0xeb, 0x53, 0x03, 0x3c, 0xb4, 0x95, 0xd8, 0x90, 0xf8, 0xd4,
    0x22, 0x3c, 0xc8, 0xe8, 0x97, 0x7e, 0x82, 0x53, 0xd7, 0x29, 0xd3, 0xa8, 0x57
]

let keyCoder = KeyCoder(saltSize: 20, mask: mask)
keyCoder.printEncodedKey("1234567890abcdefghi", named: "myKey")

You should get the similar output (we have 20 randomly generated bytes at the beginning and end of the encoded key):

? Encoding completed successfully.

You can copy the following output directly into your code:

var myKey = [0x46, 0x3f, 0x0a, 0xd6, 0xe5, 0xa3, 0x19, 0xdd, 0xbe, 0xec, 0x96, 0xa2, 0x56, 0xe0, 0xb0, 0x69, 0xf8, 0xf5, 0x6d, 0x5f, 0x6a, 0x0d, 0x5a, 0xac, 0xbe, 0xd2, 0xdd, 0xef, 0x63, 0xb9, 0x0c, 0x48, 0x79, 0xed, 0xca, 0x90, 0xd5, 0xaa, 0x91, 0x54, 0x05, 0xb5, 0xbd, 0xf8, 0x5f, 0xd1, 0x6d, 0x65, 0x97, 0xe7, 0xb4, 0xe0, 0xd2, 0x8e, 0x41, 0x48, 0xce, 0x31, 0x02]

GitHub

View Github