I'm trying to create Curve25519 keys using the KeyChain on iOS. I am aware of the existence of CryptoKit, unfortunately, that is not available for iOS 12. Is there a way to create a Curve25519 key pre CryptoKit, maybe a parameter I'm missing when generating it in the KeyChain? The code below will only generate the P-256 keys.
let attributes: [String: Any] = [
String(kSecClass): kSecClassKey,
String(kSecAttrKeyType): kSecAttrKeyTypeECSECPrimeRandom,
String(kSecAttrKeySizeInBits): 256
]
var error: Unmanaged<CFError>?
let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error)
print(privateKey ?? error!.takeUnretainedValue())
Apple's old core crypto lib
CommonCryptodoesn't support modern curves likecurve25519and quite frankly is a total mess, littered with insecure ciphers, they aren't even clear on the actual curve equations being used.Additionally, although
CryptoKitsupportscurve25519for key exchange, it's still limited, for example, you cannot use the "Secure Enclave" to generatecurve25519keys, onlyP-256, which is likely backdoored (just look at the curve co-efficients), despite all financial institutions seemingly loving it.Ultimately a
curve25519private key is just a large (2^256) number (though it is "clamped" before use), so if you just need to generate keys, you can do this withSecRandomCopyBytes.Though, if as I suspect you want to do some
X25519KEX orEdDSAsignature over25519, then just uselibsodium. It's the goto library forNaCl, there is a really great interface inSwiftwritten by the originallibsodiumauthor, calledswift-sodium, I've used it and it's great. It also supports iOS 12+.Generating keys in
libsodiumforcurve25519is as simple as:You can then manually store in KeyChain.
Shout if you need further help, and good choice using
25519.