How to implement secure storage for sensitive data in iOS?

like user credentials and payment information

Brahim Siempay
3 min readFeb 10

--

Photo by Claudio Schwarz on Unsplash

iOS has always placed great emphasis on user privacy and security, making it a priority for developers to ensure that sensitive information such as user credentials and payment information is stored securely. In this article, we will explore two popular libraries for securing sensitive data in iOS — CryptoSwift and KeychainAccess, and also recommend the use of biometric authentication for an added layer of security.

CryptoSwift is a library for iOS and macOS that provides cryptographic functionality, including data encryption and decryption. To use CryptoSwift, we need to first install the library using the CocoaPods package manager.

Here is an example of how to encrypt data using AES 256 encryption with CryptoSwift:

import CryptoSwift

let plainText = "secret data"
let key = "secretkey12345678"
let iv = "randomiv123456"

do {
let aes = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7)
let ciphertext = try aes.encrypt(Array(plainText.utf8))
print(ciphertext.toHexString())
} catch {
print(error)
}

The code above uses AES 256 encryption with CBC block mode and PKCS7 padding to encrypt the plain text. The encryption key and initialization vector (IV) are generated randomly and should be kept secret.

Once the data is encrypted, we need to store it securely. This is where KeychainAccess comes in. KeychainAccess is a simple Swift wrapper around the iOS Keychain to allow us to store and retrieve data securely.

Here is an example of how to store and retrieve data using KeychainAccess:

import KeychainAccess

let keychain = Keychain(service: "com.example.myapp")
try keychain.set("secret data", key: "secret_data")

let value = try keychain.get("secret_data")
print(value)

In this example, we created a Keychain object with a service name of “com.example.myapp” and used the set method to store a string value under the key "secret_data". To retrieve the value, we used the get method and passed the same key.

In addition to encryption and secure storage, biometric authentication such as Face ID can also be used to…

--

--

Brahim Siempay

Senior iOS engineer, Tech Geek, Writer, and Otako howtoinswift.tech