I was wondering what the correct way is to store an AES key to the KeyChain. I have read articles about people losing key data and also about people not having access to keys.
I know there is an API available to do AES encryption for you, but I want to have direct access to the key data, I just have to. I have seen objective-C implementation using CSSM_ALGID_AES, but that variable is not available in Swift. Furthermore, the documentation says that the kSecAttrKeyTypeAES is not available (or at least no longer) available on iOS.
I managed to create a key dictionary that will create a key as if it is an AES key, as the CSSM_ALGID_AES value equals 2147483649, meaning, I am able to create a key with that type and it is added correctly (read more, correctly might not be correctly).
let aesKey: [String: Any] = [
String(kSecClass): kSecClassKey,
String(kSecAttrKeyType): 2147483649,
String(kSecAttrKeySizeInBits): 128,
String(kSecAttrEffectiveKeySize): 128,
String(kSecAttrCanEncrypt): true,
String(kSecAttrCanDecrypt): true,
String(kSecAttrCanDerive): false,
String(kSecAttrCanSign): false,
String(kSecAttrCanVerify): false,
String(kSecAttrCanWrap): false,
String(kSecAttrCanUnwrap): false,
String(kSecValueData): "1234567887654321".data(using: .utf8)!
]
var result: CFTypeRef? = nil
let status = SecItemAdd(aesKey as CFDictionary, &result)
if status != errSecSuccess {
print("Error occured during key add: \(status)")
} else {
print("Created key!")
print(result ?? "Still no result though")
}It is interesting to see that this is one working way to store an AES key, however, I am never able to retrieve the SecKeyRef (it also appears it's not created when calling SecItemAdd).
So, is this the correct way to store a key like this, or am I better of creating a kSecClassGenericPassword (as it appears to have the same effect).
Is it also correct to create a key with the kSecAttrKeyType value set to 2147483649, or am I really only allowed to create it with the predefined kSecAttrKeyTypes (EC, ECSECPrimeRandom, RSA).
Are there any other consequences to creating and storing a key like this, like losing access or key data?