Can I get the modulus or exponent from a SecKeyRef object in Swift?

后端 未结 9 2052
灰色年华
灰色年华 2020-12-05 13:34

In Swift, I created a SecKeyRef object by calling SecTrustCopyPublicKey on some raw X509 certificate data. This is what this SecKeyRef object looks like.

<
9条回答
  •  猫巷女王i
    2020-12-05 14:23

    Update The answer below might result in your app being rejected due to usage of non-public API's.

    The answer lies in the SecRSAKey.h file from Apple's opensource website (Security is part of the code that Apple opensourced). The file is not big, and among other stuff it declares the following two important functions:

    CFDataRef SecKeyCopyModulus(SecKeyRef rsaPublicKey);
    CFDataRef SecKeyCopyExponent(SecKeyRef rsaPublicKey);
    

    You can add those functions to your bridging header to be able to call them from Swift, also while doing this you can switch from CFDataRef to NSData* as the two types toll-free bridged:

    NSData* SecKeyCopyModulus(SecKeyRef rsaPublicKey);
    NSData* SecKeyCopyExponent(SecKeyRef rsaPublicKey);
    

    Demo Swift usage:

    let key = bytesToPublicKey(keyData)
    let modulus = SecKeyCopyModulus(key)
    let exponent = SecKeyCopyExponent(key)
    print(modulus, exponent)
    

    This is a private API though, and there might be a chance it will no longer be available at some point, however I looked over the versions of Security made public (http://www.opensource.apple.com/source/Security), and looks like the two functions are present in all of them. More, since Security is a critical component of the OS, it's unlikely Apple will do major changes over it.

    Tested on iOS 8.1, iOS 9.2, and OSX 10.10.5, and the code works on all three platforms.

提交回复
热议问题