Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare two secKey (public keys) in ios Swift

I want to ssl public key pinning in swift, I read lot of examples how to do that, last think who I can't find is How to compare two public keys in SecKey object format. Example:

let serverPublicKey = SecTrustCopyPublicKey(secTrust) /*return SecKey object from actual SecTrust*/
let clientPublicKey = getLocalPublicKeyFromDer() /*return SecKey from .der local*/

how to compare them? At now I do that and it works:

if(serverPublicKey! as AnyObject).isEqual(clientPublicKey){
  /*Key is the same, pinning OK!*/
}

find it way on gitHub: https://github.com/teamcarma/IOS-AlamofireDomain/blob/master/Source/ServerTrustPolicy.swift

but is cast to AnyObject a good idea? How to work isEqual on casted SecKey? Can any explain me?

ps. Another idea is getting base64 from SecKey - I try and it also works, but it require a KeyChain temp operations and look no profesional.

like image 532
luky0007 Avatar asked Jan 26 '16 07:01

luky0007


2 Answers

Cited from the headers:

"Most SecKeychainItem functions will work on an SecKeyRef."*

You may cast SecKeyRef to a SecKeychainItem. If this is a valid operation (that is, the key is a keychain item), you may apply function

SecKeychainItemCreatePersistentReference

and get a CFData object, filled with attributes and data. Then check with memcpyon the bytes or cast it to a NSData object and check with isEqualToData. Don't forget to release the CFData object.

Edit

On iOS, as far as I known, the only reliable approach is to copy the data (or secret) into the keychain, using a temporary key, so that you can find it again, and then extract the data. It's cumbersome, but if you just implement it in a minimalistic way, it should not take more than 30 lines of code. I have a working example.

I The usual disclaimer: Use this at your own risk, and always be careful with security stuff.

like image 163
CouchDeveloper Avatar answered Nov 06 '22 08:11

CouchDeveloper


iOS10 added:

CFDataRef _Nullable SecKeyCopyExternalRepresentation(SecKeyRef key, CFErrorRef *error)

so you can now create two Data (NSData) objects, then compare those.

like image 30
David H Avatar answered Nov 06 '22 07:11

David H