Xcode编译OpenSSL

从OS X 10.11开始,苹果SDK中不再提供OpenSSL标准库,官方文档中说明如下:

Although OpenSSL is commonly used in the open source community, OpenSSL does not provide a stable API from version to version. For this reason, although OS X provides OpenSSL libraries, the OpenSSL libraries in OS X are deprecated, and OpenSSL has never been provided as part of iOS. Use of the OS X OpenSSL libraries by apps is strongly discouraged.

If your app depends on OpenSSL, you should compile OpenSSL yourself and statically link a known version of OpenSSL into your app. This use of OpenSSL is possible on both OS X and iOS. However, unless you are trying to maintain source compatibility with an existing open source project, you should generally use a different API.

Common Crypto and Security Transforms are the recommended alternatives for general encryption. CFNetwork and Secure Transport are the recommended alternatives for secure communications.

虽然MacOS中自带有OpenSSL库,但在Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include路径下是找不到原有的OpenSSL目录的。

首先通过brew安装OpenSSL:

1
$ brew install openssl

第一次安装完成会有相关安装路径的提示,如果你错过了也没关系,使用brew查看即可:

1
$ brew info openssl

A CA file has been bootstrapped using certificates from the SystemRoots keychain. To add additional certificates (e.g. the certificates added in the System keychain), place .pem files in
  /usr/local/etc/openssl/certs
and run
  /usr/local/opt/openssl/bin/c_rehash

This formula is keg-only, which means it was not symlinked into
  /usr/local,
because Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries.

If you need to have this software first in your PATH run:
  echo ‘export PATH=”/usr/local/opt/openssl/bin:$PATH”‘ >> ~/.zshrc

For compilers to find this software you may need to set:
  LDFLAGS: -L/usr/local/opt/openssl/lib
  CPPFLAGS: -I/usr/local/opt/openssl/include
For pkg-config to find this software you may need to set:
  PKG_CONFIG_PATH: /usr/local/opt/openssl/lib/pkgconfig

现在我们需要以下步骤引入OpenSSL库:

  1. 在对应位置找到OpenSSL静态库

    1
    $ open /usr/local/opt/openssl/lib
  2. libcrypto.alibssl.a为文件拖入工程的Frameworks中

  3. Library Search Paths中添加$(inherited)$(SRCROOT)
  4. Header Search Paths中添加include(直接输入include即可,不需要加上SRCROOT类似的引用路径)
  5. Always Search User Path设置为Yes

如果是在iOS手机端开启MQTTKit(libmosquitto)中要开启加密,需要到build settings -> preprocessor中添加一个WITH_TLS即可:

Set a preprocessor flag in XCode “WITH_TLS” by clicking the project in XCode then click the target then click build settingsSearch for preprocessor macros and add “WITH_TLS” to debug and release

如果提示:

1
ld: '/Users/**/Framework/SDKs/PolymerPay/Library/mobStat/lib**SDK.a(**ForSDK.o)' does not contain bitcode. You must rebuild it with bitcode enabled (Xcodesetting ENABLE_BITCODE), obtain an updated library from the vendor, or disablebitcode for this target for architecture arm64

前往build settings -> enable bitcode设置为NO即可