CommonCrypto • The C library • Part of the system (iOS and OS X) • Can be used with Swift (thanks to C interoperability) ‣ Unsafe pointers • Sources available at opensource.apple.com
A cryptographic hash function allows one to easily verify that some input data matches a stored hash value, but makes it hard to construct any data that would hash to the same value or find any two unique data pieces that hash to the same value. CryptoSwift - hash
“In cryptography, a cipher (or cypher) is an algorithm for performing encryption or decryption—a series of well-defined steps that can be followed as a procedure.” CryptoSwift - ciphers
CryptoSwift - ciphers • AES • The Advanced Encryption Standard, the symmetric block cipher ratified as a standard by National Institute of Standards and Technology of the United States (NIST) • Hardware acceleration (not for Swift) ‣ Advanced Encryption Standard Instruction Set (AES-NI)
import CryptoSwift let key = "1234567890123456" // key let iv = "1234567890123456" // random if let aes = AES(key: key, iv: iv, blockMode: .CBC) { if let encrypted = aes.encrypt([1,2], padding: PKCS7()) { let data = NSData.withBytes(encrypted) } } CryptoSwift - ciphers
CryptoSwift - ciphers • ChaCha20 ‣ The stream cipher by D. J. Bernstein, built on a pseudorandom function based on add-rotate-xor operations ‣ Adopted by Apple with HomeKit, by Google with Chrome (replace RC4) ‣ Lack of official support in OpenSSL. Patches are waiting to be merged.
import CryptoSwift let key = "1234567890123456" // key let iv = "1234567890123456" // random if let chacha = ChaCha20(key: key, iv: iv) { if let encrypted = chacha.encrypt([1,2]) { let data = NSData.withBytes(encrypted) } } CryptoSwift - ciphers
CryptoSwift - block mode • Cipher-block Chaining CBC ‣ Sequence of encrypted blocks, every following block uses encrypted data as a key to the cipher. decryption is parallelizable
Authenticators The message authentication code is a short piece of information used to authenticate a message and to provide integrity and authenticity assurances on the message
CryptoSwift - authenticators • Poly1305 - a one-time authenticator ‣ takes a 32-byte one-time key and a message and produces the 16-byte tag. • HMAC - Keyed-Hashing for Message Authentication ‣ takes a key and message and produces a tag with one of the hash functions (MD5, SHA)
Performance • CryptoSwift implementation is significantly slower than CommonCrypto • It’s better with the new version of Swift • NSMutableData is slow • memory allocation is slow if the “unsafe pointer” is not used. • Array enumeration is significantly visible.