自己踏入Windows, Mac OS X, Linux / Deep Leaning, Machine Leaning / Spark, 在研究所.. 等等所學習到的知識和筆記做一些心得整理分享!版權與智慧財產權聲明 : 保留所有法律權利。我在寫文章時如果有引用到其他人的地方,會盡量說明參考出處,如果有遺漏的地方請告訴我,會馬上註明! 而轉貼我的文章時也請您註明出處!
Apple iOS and macOS Cryptographic Services Guide 2018-06-04
Apple iOS and macOS Cryptographic Services Guide 2018-06-04 From: https://developer.apple.com/library/archive/documentation/Security/Conceptual/cryptoservices/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011172-CH1-SW1 Introduction
Next
About Cryptographic Services
macOS and iOS contain a number of technologies that provide cryptographic services—encryption and decryption, hashing, random number generation, secure network communication, and so on. These technologies can be used to secure data at rest (when stored on your hard drive or other media), secure data in transit, determine the identity of a third party, and build additional security technologies.
At a Glance
Some of the cryptographic services provided by iOS and macOS include:
Encryption and decryption (both general-purpose and special-purpose)
Key management using keychains
Cryptographically strong random number generation
Secure communication (SSL and TLS)
Secure storage using FileVault and iOS File Protection
Encryption, Signing and Verifying, and Digital Certificates Can Protect Data from Prying Eyes
There are two main types of encryption: symmetric encryption, in which a single shared key is used for encrypting and decrypting data, and asymmetric encryption, in which you use one key to encrypt data and a separate (but related) key to decrypt the data. You can use a hash to detect modifications to a piece of data. You can combine hashes with asymmetric keys to create a digital signature that, when verified against a digital certificate, proves the source of a piece of data. Digital certificates, in turn, are verified by verifying the signature of the party that signed the certificate, then verifying that party’s certificate, and so on until you reach a certificate that you trust inherently, called an anchor certificate.
macOS and iOS Provide Encryption and Hashing APIs
macOS and iOS provide a number of APIs for encrypting and hashing data, including Keychain Services; Cryptographic Message Syntax Services; Certificate, Key, and Trust Services; and Security Transforms.
Keychains Help You Store Secret Information
If your app stores encryption keys, passwords, certificates, and other security-related information, use a keychain. Keychains provide secure storage for small pieces of information so that is not accessible by other apps running on the system, and so that it is accessible only after the user has logged in or unlocked the device. macOS and iOS provide two APIs for working with the keychain and keys obtained from the keychain: Certificate, Key, and Trust Services and Keychain Services.
macOS and iOS Provide Cryptographically Secure Random Number Generation
Some cryptographic tasks require you to generate cryptographically strong pseudorandom numbers. Use the Randomization Services API to generate these numbers.
macOS and iOS Provide Secure Network Communication APIs
Transmitting data securely requires a secure communications channel. macOS and iOS provide a number of APIs for establishing secure communications channels, including the URL Loading System, socket streams in Core Foundation and Foundation, and Secure Transport.
Deprecated Technologies
Although the CDSA and CSSM API is deprecated in macOS 10.7 and later, its documentation is provided as an appendix.
Prerequisites
Before reading this document, you should be familiar with the concepts in Security Overview and Secure Coding Guide.
See Also
For more information about macOS authentication and authorization (built on top of encryption technologies), read Authentication, Authorization, and Permissions Guide.
Cryptography Concepts In Depth
The word cryptography (from Greek kryptos, meaning hidden) at its core refers to techniques for making data unreadable to prying eyes. However, cryptography can also be used for other purposes. Cryptography includes a range of techniques that can be used for verifying the authenticity of data (detecting modifications), determining the identity of a person or other entity, determining who sent a particular message or created a particular piece of data, sending data securely across a network, locking files securely behind a password or passphrase, and so on.
This chapter describes a number of these techniques, beginning with basic encryption, then moving on to other cryptographic constructs built on top of it.
What Is Encryption?
Encryption is the transformation of data into a form in which it cannot be made sense of without the use of some key. Such transformed data is referred to as ciphertext. Use of a key to reverse this process and return the data to its original (cleartext or plaintext) form is called decryption. Most of the security APIs in macOS and iOS rely to some degree on encryption of text or data. For example, encryption is used in the creation of certificates and digital signatures, in secure storage of secrets in the keychain, and in secure transport of information.
Encryption can be anything from a simple process of substituting one character for another—in which case the key is the substitution rule—to a complex mathematical algorithm. For purposes of security, the more difficult it is to decrypt the ciphertext, the better. On the other hand, if the algorithm is too complex, takes too long to do, or requires keys that are too large to store easily, it becomes impractical for use in a personal computer. Therefore, some balance must be reached between strength of the encryption (that is, how difficult it is for someone to discover the algorithm and the key) and ease of use.
For practical purposes, the encryption only needs to be strong enough to protect the data for the amount of time the data might be useful to a person with malicious intent. For example, if you need to keep your bid on a contract secret only until after the contract has been awarded, an encryption method that can be broken in a few weeks will suffice. If you are protecting your credit card number, you probably want an encryption method that cannot be broken for many years.
Types of Encryption
There are two main types of encryption in use in computer security, referred to as symmetric key encryption and asymmetric key encryption. A closely related process to encryption, in which the data is transformed using a key and a mathematical algorithm that cannot be reversed, is called cryptographic hashing. The remainder of this section discusses encryption keys, key exchange mechanisms (including the Diffie-Hellman key exchange used in some secure transport protocols), and cryptographic hash functions.
Symmetric Keys
Symmetric key cryptography (also called secret key cryptography) is the classic use of keys that most people are familiar with: The same key is used to encrypt and decrypt the data. The classic, and most easily breakable, version of this is the Caesar cipher (named for Julius Caesar), in which each letter in a message is replaced by a letter that is a fixed number of positions away in the alphabet (for example, “a” is replaced by “c”, “b” is replaced by “d”, and so forth). In the Caesar cipher, the key used to encrypt and decrypt the message is simply the number of places by which the alphabet is rotated and the direction of that rotation. Modern symmetric key algorithms are much more sophisticated and much harder to break. However, they share the property of using the same key for encryption and decryption.
There are many different algorithms used for symmetric key cryptography, offering anything from minimal to nearly unbreakable security. Some of these algorithms offer strong security, easy implementation in code, and rapid encryption and decryption. Such algorithms are very useful for such purposes as encrypting files stored on a computer to protect them in case an unauthorized individual uses the computer. They are somewhat less useful for sending messages from one computer to another, because both ends of the communication channel must possess the key and must keep it secure. Distribution and secure storage of such keys can be difficult and can open security vulnerabilities.
In 1968, the USS Pueblo, a U.S. Navy intelligence ship, was captured by the North Koreans. At the time, every Navy ship carried symmetric keys for a variety of code machines at a variety of security levels. Each key was changed daily. Because there was no way to know how many of these keys had not been destroyed by the Pueblo’s crew and therefore were in the possession of North Korea, the Navy had to assume that all keys being carried by the Pueblo had been compromised. Every ship and shore station in the Pacific theater (that is, several thousand installations, including ships at sea) had to replace all of their keys by physically carrying code books and punched cards to each installation.
The Pueblo incident was an extreme case. However, it has something in common with the problem of providing secure communication for commerce over the Internet. In both cases, codes are used for sending secure messages—not between two locations, but between a server (the Internet server or the Navy’s communications center) and a large number of communicants (individual web users or ships and shore stations). The more end users who are involved in the secure communications, the greater the problems of distribution and protection of the secret symmetric keys.
Although secure techniques for exchanging or creating symmetric keys can overcome this problem to some extent (for example, Diffie-Hellman key exchange, described later in this chapter), a more practical solution for use in computer communications came about with the invention of practical algorithms for asymmetric key cryptography.
Asymmetric Keys
In asymmetric key cryptography, different keys are used for encrypting and decrypting a message. The asymmetric key algorithms that are most useful are those in which neither key can be deduced from the other. In that case, one key can be made public while the other is kept secure. This arrangement is often referred to as public key cryptography, and provides some distinct advantages over symmetric encryption: the necessity of distributing secret keys to large numbers of users is eliminated, and the algorithm can be used for authentication as well as for cryptography.
The first public key algorithm to become widely available was described by Ron Rivest, Adi Shamir, and Len Adleman in 1977, and is known as RSA encryption from their initials. Although other public key algorithms have been created since, RSA is still the most commonly used. The mathematics of the method are beyond the scope of this document, and are available on the Internet and in many books on cryptography. The algorithm is based on mathematical manipulation of two large prime numbers and their product. Its strength is believed to be related to the difficulty of factoring a very large number. With the current and foreseeable speed of modern digital computers, the selection of long-enough prime numbers in the generation of the RSA keys should make this algorithm secure indefinitely. However, this belief has not been proved mathematically, and either a fast factorization algorithm or an entirely different way of breaking RSA encryption might be possible. Also, if practical quantum computers are developed, factoring large numbers will no longer be an intractable problem.
Other public key algorithms, based on different mathematics of equivalent complexity to RSA, include ElGamal encryption and elliptic curve encryption. Their use is similar to RSA encryption (though the mathematics behind them differs), and they will not be discussed further in this document.
To see how public key algorithms address the problem of key distribution, assume that Alice wants to receive a secure communication from Bob. The procedure is illustrated in Figure 1-1.
Figure 1-1 Asymmetric key encryption
The secure message exchange illustrated in Figure 1-1 has the following steps:
Alice uses one of the public key algorithms to generate a pair of encryption keys: a private key, which she keeps secret, and a public key. She also prepares a message to send to Bob.
Alice sends the public key to Bob, unencrypted. Because her private key cannot be deduced from the public key, doing so does not compromise her private key in any way.
Alice can now easily prove her identity to Bob (a process known as authentication). To do so, she encrypts her message (or any portion of the message) using her private key and sends it to Bob.
Bob decrypts the message with Alice’s public key. This proves the message must have come from Alice, as only she has the private key used to encrypt it.
Bob encrypts his message using Alice’s public key and sends it to Alice. The message is secure, because even if it is intercepted, no one but Alice has the private key needed to decrypt it.
Alice decrypts the message with her private key.
Since encryption and authentication are subjects of great interest in national security and protecting corporate secrets, some extremely smart people are engaged both in creating secure systems and in trying to break them. Therefore, it should come as no surprise that actual secure communication and authentication procedures are considerably more complex than the one just described. For example, the authentication method of encrypting the message with your private key can be got around by a man-in-the-middle attack, in which someone with malicious intent (usually referred to as Eve in books on cryptography) intercepts Alice’s original message and replaces it with their own, so that Bob is using not Alice’s public key, but Eve’s. Eve then intercepts each of Alice’s messages, decrypts it with Alice’s public key, alters it (if she wishes), and reencrypts it with her own private key. When Bob receives the message, he decrypts it with Eve’s public key, thinking that the key came from Alice.
Although this is a subject much too broad and technical to be covered in detail in this document, digital certificates and digital signatures can help address these security problems. These techniques are described later in this chapter.
Diffie-Hellman Key Exchange
The Diffie-Hellman key exchange protocol is a way for two ends of a communication session to generate a shared symmetric key securely over an insecure channel. Diffie-Hellman is usually implemented using mathematics similar to RSA public key encryption. However, a similar technique can also be used with elliptic curve encryption. The basic steps are listed below:
Alice and Bob exchange public keys.
For RSA, these keys must have the same modulo portion, p.
For elliptic curve encryption, the domain parameters used for encryption must be agreed upon.
As a rule, you should use the modulo or domain parameter values specified in RFC 5114.
Alice and Bob each encrypt a shared, non-secret value, g, using their private keys, and they exchange these encrypted values.
The value for g is also usually taken from RFC 5114, but if another value is chosen when using RSA, the value for g must be a primitive root mod p—that is, any number that shares no common divisors with p other than 1, is congruent to a power of g mod p.
Alice encrypts the encrypted value received from Bob with her private key, and vice versa. These values are used as a shared session key.
At this point, even though neither side knows the other side’s private key, both sides’ session keys are identical. A third party intercepting the public keys but lacking knowledge of either private key cannot generate a session key. Therefore, data encrypted with the resulting session key is secure while in transit.
Although Diffie-Hellman key exchange provides strong protection against compromise of intercepted data, it provides no mechanism for ensuring that the entity on the other end of the connection is who you think it is. That is, this protocol is vulnerable to a man-in-the-middle attack. Therefore, it is sometimes used together with some other authentication method to ensure the integrity of the data.
Diffie-Hellman key exchange is supported by Apple Filing Protocol (AFP) version 3.1 and later and by Apple’s Secure Transport API. Because RSA encryption tends to be slower than symmetric key methods, Diffie-Hellman (and other systems where public keys are used to generate symmetric private keys) can be useful when a lot of encrypted data must be exchanged.
Cryptographic Hash Functions
A cryptographic hash function takes any amount of data and applies an algorithm that transforms it into a fixed-size output value. For a cryptographic hash function to be useful, it has to be extremely difficult or impossible to reconstruct the original data from the hash value, and it must be extremely unlikely that the same output value could result from any other input data.
Sometimes it is more important to verify the integrity of data than to keep it secret. For example, if Alice sent a message to Bob instructing him to shred some records (legally, of course), it would be important to Bob to verify that the list of documents was accurate before proceeding with the shredding. Since the shredding is legal, however, there is no need to encrypt the message, a computationally expensive and time-consuming process. Instead, Alice could compute a hash of the message (called a message digest) and encrypt the digest with her private key. When Bob receives the message, he decrypts the message digest with Alice’s public key (thus verifying that the message is from Alice) and computes his own message digest from the message text. If the two digests match, Bob knows the message has not been corrupted or tampered with.
The most common hash function you will use is SHA-1, an algorithm developed and published by the U.S. Government that produces a 160-bit hash value from any data up to 2**64 bits in length. There are also a number of more exotic algorithms such as SHA-2, elliptic-curve-based algorithms, and so on.
For compatibility with existing systems and infrastructure, you may occasionally need to use older algorithms such as MD5, but they are not recommended for use in new designs because of known weaknesses.
Digital Signatures
Digital signatures are a way to ensure the integrity of a message or other data using public key cryptography. Like traditional signatures written with ink on paper, they can be used to authenticate the identity of the signer of the data. However, digital signatures go beyond traditional signatures in that they can also ensure that the data itself has not been altered. This is like signing a check in such a way that if someone changes the amount of the sum written on the check, an “Invalid” stamp becomes visible on the face of the check.
Before a signer can create a digital signature, the signer must first have a digital identity—a public-private key pair and a corresponding digital certificate that proves the authenticity of the signer’s public key.
The signer generates a message digest of the data and then uses the private key to encrypt the digest. The signer includes the encrypted digest and information about the signer’s digital certificate along with the message. The combination of the encrypted digest and the digital certificate is a digital signature.
The certificate can later be used by the recipient to verify the signature; the certificate includes the public key needed to decrypt the digest and the algorithm used to create the digest. To verify that the signed document has not been altered, the recipient uses the same algorithm to create a digest of the message as received, then uses the public key to decrypt the encrypted digest from the message signature. If the two digests are identical, then the message cannot have been altered and must have been sent by the owner of the public key.
To ensure that the person who provided the signature is not only the same person who provided the data but is also who he or she claims to be, the certificate is also signed—in this case by the certification authority who issued the certificate. (More on certification authorities later.)
Digital signatures play a key role in code signing. Developers are encouraged to sign their apps. On execution, each app’s signature is checked for validity. Digital signatures are required on all apps for iOS. Read Code Signing Guide for details about how code signing is used by macOS and iOS.
Figure 1-2 illustrates the creation of a digital signature.
Figure 1-2 Creating a digital signature
Figure 1-3 illustrates the verification of a digital signature. The recipient gets the signer’s public key from the signer’s certificate and uses that to decrypt the digest. Then, using the algorithm indicated in the certificate, the recipient creates a new digest of the data and compares the new digest to the decrypted copy of the one delivered in the signature. If they match, then the received data must be identical to the original data created by the signer.
Figure 1-3 Verifying a digital signature
Digital Certificates
A digital certificate is a collection of data used to verify the identity of the holder or sender of the certificate.
For example, an X.509 certificate contains such information as:
Structural information—version, serial number, the message digest algorithm used to create the signature, and so on
A digital signature from a certification authority (CA)—a person or organization that issued the certificate—to ensure that the certificate has not been altered and to indicate the identity of the issuer
Information about the certificate holder—name, email address, company name, the owner’s public key, and so on
Validity period (the certificate is not valid before or after this period)
Certificate extensions—attributes that contain additional information such as allowable uses for this certificate
The careful reader will have noticed that a digital signature includes the certificate of the signer, and that the signer’s certificate, in turn, contains a digital signature that includes another certificate.
In general, each certificate is verified through the use of another certificate, creating a chain of trust—a chain of certificates, each of which is digitally signed by the next certificate in the chain, ending with a root certificate. The owner of this root certificate is called the root certification authority. Figure 1-4 illustrates the parts of a digital certificate.
Figure 1-4 Anatomy of a digital certificate
The root certificate is self-signed, meaning the signature of the root certificate was created by the root certification authority themselves. Figure 1-5 and Figure 1-6illustrate how a chain of certificates is created and used. Figure 1-5 shows how the root certification authority creates its own certificate and then creates a certificate for a secondary certification authority.
Figure 1-5 Creating the certificates for the root CA and a secondary CA
Figure 1-6 shows how the secondary certification authority creates a certificate for an end user and how the end user uses it to sign a document.
Figure 1-6 Creating the certificate for an end user and signing a document with it
In Figure 1-6, the creator of the document has signed the document. The signature indicates the certificate of the document’s creator (labeled User in the figure). The document’s creator signs the document with a private key, and the signing certificate contains the corresponding public key, which can be used to decrypt the message digest to verify the signature (described earlier in Digital Signatures). This certificate—together with the private and public keys—was provided by a certification authority (CA).
In order to verify the validity of the user’s certificate, the certificate is signed using the certificate of the CA. The certificate of the CA includes the public key needed to decrypt the message digest of the user’s certificate. Continuing the certificate chain, the certificate of the CA is signed using the certificate of the authority who issued that certificate. The chain can go on through any number of intermediate certificates, but in Figure 1-5 the issuer of the CA’s certificate is the root certification authority. Note that the certificate of the root CA, unlike the others, is self-signed—that is, it does not refer to a further certification authority but is signed using the root CA’s own private key.
When a CA creates a certificate, it uses its private key to encrypt the certificate’s message digest. The signature of every certificate the CA issues refers to its own signing certificate. The CA’s public key is in this certificate, and the app verifying the signature must extract this key to verify the certificate of the CA. So it continues, on down the certificate chain, to the certificate of the root CA. When a root CA issues a certificate, it, too, signs the certificate. However, this signing certificate was not issued by another CA; the chain stops here. Rather, the root CA issues its own signing certificate, as shown in Figure 1-5.
The certificate of the root CA can be verified by creating a digest and comparing it with one widely available. Typically, the root certificate and root CA’s public key are already stored in the app or on the computer that needs to verify the signature.
It’s possible to end a certificate chain with a trusted certificate that is not a root certificate. For example, a certificate can be certified as trusted by the user, or can be cross certified—that is, signed with more than one certificate chain. The general term for a certificate trusted to certify other certificates—including root certificates and others—is anchor certificate. Because most anchor certificates are root certificates, the two terms are often used interchangeably.
The confidence you can have in a given certificate depends on the confidence you have in the anchor certificate; for example, the trust you have in the certificate authorities and in their procedures for ensuring that subsequent certificate recipients in the certificate chain are fully authenticated. For this reason, it is always a good idea to examine the certificate that comes with a digital signature, even when the signature appears to be valid. In macOS and iOS, all certificates you receive are stored in your keychain. In macOS, you can use the Keychain Access utility to view them.
Certain attributes of a digital certificate (known as certificate extensions) provide additional information about the certificate. Some of these extensions describe how the certificate was intended to be used. For example, a certificate extension might indicate that a key can be used for code signing, or might provide a list of additional domain names for which a TLS certificate is valid. Other extensions provide signed time stamps indicating when the certificate was used to sign a particular document, thus allowing you to verify that a now-expired certificate was valid when it was used to sign the document. Still others provide information used for checking whether a certificate has been revoked. And so on.
These certificate extensions are interpreted in the context of a trust policy—a set of rules that specify how a particular extension affects whether the certificate should be trusted for a given use. For example, a trust policy might specify that in order to be trusted to verify a digitally signed email message, a certificate must contain an email address that matches the address of the sender of the email.
Encrypting and Hashing Data
You typically use asymmetric encryption for sending data across trust boundaries, such as one person sending another person an encrypted email. You also use it for sending a symmetric session key across an insecure communication channel so that you can then use symmetric encryption in further communication. On the other hand, you often use symmetric encryption for data at rest—on your hard drive, for example—and as a session key in a number of encrypted networking schemes.
Encryption Technologies Common to macOS and iOS
macOS and iOS provide a number of encryption technologies, including:
Keychain Services. Use this API, described in Keychain Services Reference, to encrypt and store passwords, keys, and other small secrets in a special database called a keychain. By storing user secrets this way, you ensure that they are kept secure, including in device backups, without having to implement your own encryption algorithms or storage protocols. On a Mac, you can use the Keychain Access app to inspect keychains, as described in Keychain Access in Security Overview.
Certificate, Key, and Trust Services. This interface provides cryptographic support services, including methods for general encryption and decryption, as well as trust validation. See Certificate, Key, and Trust Services Reference for details.
Cryptographic Message Syntax. Use this service to encrypt or add a digital signature to S/MIME messages. S/MIME is a standard for encrypting and signing messages, most commonly used with email. See Cryptographic Message Syntax Services Reference for more information.
Encryption Technologies Specific to macOS
macOS provides a few additional APIs for performing encryption:
Security Transforms API. Based on the concept of data flow programming, the Security Transforms API lets you construct graphs of transformations that feed into one another, transparently using Grand Central Dispatch to schedule the resulting work efficiently across multiple CPUs. As the data objects pass through the object graph, callbacks within each individual transform operate on that data, then pass it on to the transform’s output, which may be connected to the input of another transform object, and so on.
Using the built-in transforms, the Security Transforms API allows you to read files, perform symmetric encryption and decryption, perform asymmetric signing and verifying, and perform Base64 encoding. The Security Transforms API also provides support for creating custom transforms that perform other operations on data. For example, you might create a transform that byte swaps data prior to encrypting it or a transform that encodes the resulting encrypted data for transport.
For more information, see Security Transforms Reference.
CDSA/CSSM. This open source security architecture provides a wide array of security services, including fine-grained access permissions, authentication of users’ identities, encryption, and secure data storage. However, this interface is deprecated starting in macOS 10.7, and should not be used for any new apps.
Managing Keys, Certificates, and Passwords
The keychain provides storage for passwords, encryption keys, certificates, and other small pieces of data. Some of these items are inherently secret, like private keys and passwords, while others are not, such as certificates. After storing data in the keychain, you can be confident that untrusted apps cannot access that data. Further, device backups contain only encrypted versions of the secret data.
Use the following APIs to work with keychain items:
Keychain Services. Use Keychain Services to explicitly add, delete, and edit keychain items, and—in macOS only—manage collections of keychains. See Keychain Services Reference for details.
Certificate, Key, and Trust Services. Manage certificates, public and private keys, symmetric keys, and trust policies. In particular, you can:
Create certificates and asymmetric keys.
Add certificates and keys to keychains.
Retrieve information about a certificate, such as the private key associated with it, the owner, and so on.
Convert certificates to and from portable representations.
Create and manipulate trust policies and evaluate a specific certificate using a specified set of trust policies.
Add anchor certificates.
Generate or verify a digital signature for a block of data.
Encrypt or decrypt a block of data.
Certificate, Key, and Trust Services operates on certificates that conform to the X.509 ITU standard, uses the keychain for storage and retrieval of certificates and keys, and uses the trust policies provided by Apple. See Certificate, Key, and Trust Services Reference for more information.
Security Interface. To display the contents of a certificate in an macOS user interface, you can use the SFCertificatePanel and SFCertificateView classes. In addition, the SFCertificateTrustPanel class displays trust decisions and lets the user edit trust decisions.
Generating Random Numbers
Many encryption algorithms rely on cryptographically strong pseudorandom numbers. Use Randomization Services to generate these numbers. For more information, read Randomization Services Reference.
Transmitting Data Securely
One important aspect of computer security is the secure communication of data over a network. Although you can devise your own security protocols and use low-level APIs to implement them, it’s best to use standard protocols as much as possible, and the highest level API that supports them.
The Secure Sockets Layer (SSL) protocol and its successor, the Transport Layer Security (TLS) protocol, provide support for secure communication over a network. They are commonly used over TCP/IP connections such as the Internet. They use certificate-based authentication to ensure that you are communicating with a valid server, they validate data to prevent tampering, and they can use public-key cryptography to guard against eavesdropping or message forgery.
SSL and TLS are built into all major browsers and web servers. Whenever you use a secure website—for example, to send your credit card number to a vendor over the Internet—and see a protocol identifier of https rather than http at the beginning of the URL, you are using SSL or TLS for communication.
There are several ways to take advantage of SSL and TLS:
At a high level, you can use an https URL with the URL Loading System (the NSURL class, CFURL functions, and related classes).
At a lower level, you can use the CFNetwork API to negotiate an SSL or TLS connection.
For maximum control, you can use the Secure Transport API in macOS or in iOS 5.0 and later.
In addition to these APIs, a number of open source tools use OpenSSL for secure networking. If you use OpenSSL in your publicly shipping apps, you must provide your own copy of the OpenSSL libraries, preferably as part of your app bundle; the OpenSSL libraries that macOS provides are deprecated.
Using the URL Loading System
The URL Loading System is a very high-level API that you can use to access the contents of HTTP://, HTTPS://, and FTP:// URLs. Because URL Loading System works with secure https:// URLs, it can be used for secure transport of data.
You should use the URL loading system when you need to download a resource from a remote server. Unlike CFNetwork, this API does not maintain a continuous data stream. This makes it a better choice for mobile use when it meets your needs (particularly with cellular networks, where your IP number may change as you switch from tower to tower).
CFNetwork
CFNetwork is an API for creating, sending, and receiving serialized messages over a network. It provides a higher-level interface than Secure Transport that can be used by apps to set up and maintain a secure SSL or TLS networking session and to add authentication information to a message.
CFNetwork includes the following security-related components:
CFHTTPMessage, which you can use to create, serialize, deserialize, and manage HTTP protocol messages. You should use the CFHTTPMessage API instead of other CFHTTP APIs if you need to add authentication information to a message.
CFHTTPAuthentication, which applies authentication credentials to challenged HTTP messages. You use this API in conjunction with CHTTPMessage.
CFStream Socket Additions, which allocates read and write streams and provides constants used with the CFReadStream and CFWriteStream APIs to set security protocols. You should use CFStream objects if you need to set up a streaming data connection (as opposed to an HTTP request).
CFFTPStream, which you can use to perform FTP file transfers using the file transfer protocol (FTP). This component lets you send passwords to FTP servers.
In addition to the CFNetwork API, you use the CFReadStream and CFWriteStream APIs in the Core Foundation framework to create and manage the read and write streams that CFNetwork depends on. You can specify an SSL or TLS protocol version to encrypt and decrypt the data stream. Note that CFReadStream and CFWriteStream are “toll-free bridged” with their Cocoa Foundation counterparts, the classes NSInputStream and NSOutputStream. This means that each Core Foundation type is interchangeable in function or method calls with the corresponding bridged Foundation object, so you can use either C or Objective C interfaces, whichever is most convenient for you.
Secure Transport
Secure Transport is a low-level API for working with SSL and TLS. With Secure Transport, your code must set up the network connection and provide callback functions that Secure Transport calls to perform I/O operations over the network.
The CFNetwork and URL Loading System APIs are built on top of Secure Transport.
You can use the Secure Transport API to set parameters for a secure session, open and maintain a session, and close a session. However, because Secure Transport is a fairly complex API, you should generally use Secure Transport directly only if you need more control than you can get with CFNetwork.
The Secure Transport API lets you:
Choose which protocols (SSL/TLS versions) and cipher suites should be allowed, and (after connecting) determine which protocol and cipher suite were actually negotiated.
Specify Diffie-Hellman parameters for key exchange
Specify whether client-side authentication should be required, and obtain that identification.
Manage certificates and trust policies—specify certificates to use for client or server identification, specify the domain name to use when determining whether the other host’s certificate is valid, provide trust policies for expired certificates and unknown or expired root certificates, add additional trusted root certificates, and so on.
Secure Transport has no transport-layer dependencies; it can be used with BSD sockets, Open Transport, or any other transport-layer protocol available.
OpenSSL
macOS includes a low-level command-line interface to the OpenSSL open-source cryptography toolkit; this interface is not available in iOS.
Although OpenSSL is commonly used in the open source community, it doesn’t provide a stable API from version to version. For this reason, the programmatic interface to OpenSSL is deprecated in macOS and is not provided in iOS. Use of the Apple-provided OpenSSL libraries by apps is strongly discouraged.
To ensure compatibility, if your app depends on OpenSSL, you should compile it yourself and statically link a known version of OpenSSL into your app. Such use works on both iOS and macOS.
In general, however, you should use the CFNetwork API for secure networking and the Certificate, Key, and Trust Services API for cryptographic services. Alternatively, in macOS, you can use the Secure Transport API.
To Learn More
To learn about other security issues related to network communication, read Using Networking Securely in Networking Overview.
For more information on the TLS standard, see IETF's TLS Working Group site.
To learn more about CFNetwork, read CFNetwork Programming Guide.
To get started with Secure Transport, see Secure Transport Reference.
CDSA Overview
CDSA is an Open Source security architecture adopted as a technical standard by the Open Group. Apple has developed its own Open Source implementation of CDSA, available as part of Darwin at Apple’s Open Source site. The core of CDSA is CSSM (Common Security Services Manager), a set of Open Source code modules that implement a public application programming interface called the CSSM API. CSSM provides APIs for cryptographic services (such as creation of cryptographic keys, encryption and decryption of data), certificate services (such as creation of digital certificates, reading and evaluation of digital certificates), secure storage of data, and other security services (see Apple CDSA Plug-ins for a more complete list).
CSSM also defines an interface for plug-ins that implement security services for a particular operating system and hardware environment. The implementation on a given platform can optionally supply a middleware layer that provides an operating-system-specific API for apps. Whether such a layer is present or not, apps can call the CSSM API directly.
OS X implements nearly all the standard features of CSSM, plus a set of middleware security services to provide an OS X-standard interface for app programmers. In addition, to enhance the security of the most sensitive operations, the OS X implementation runs a Security Server daemon as a separate process. The Security Server daemon launches another process, the Security Agent, which serves as the user interface for Security Server.
Figure A-1 illustrates the OS X implementation of CDSA. The CDSA standard defines a four-layer architecture, with the top layer being the apps that use the CDSA security features. Figure A-1 shows the first three layers: the CDSA plug-ins, CSSM, and the OS X security APIs, which constitute the middleware layer referred to in the specification. The OS X Authorization Services API, the Security Server daemon, and the Security Agent shown in the figure are technically outside of CDSA, but they are shown here for completeness because they constitute an integral part of the OS X security architecture.
Figure A-1 OS X implementation of CDSA
Security contexts (see Figure A-1) are data structures used by CSSM to assist apps in managing the many parameters used in security operations. The CSSM managers implement the standard CSSM API. (A fifth manager defined in the CDSA standard, called the Authorization Computation Services Manager, is not implemented in OS X. Instead of using a CSSM API, OS X Authorization Services calls the Security Server daemon directly.)
The CDSA plug-ins shown in Figure A-1 are those provided as part of OS X. The CDSA specification allows any number of plug-ins. As long as a plug-in follows the rules for interfacing with the CSSM managers, it can implement any portion of the CDSA feature set, including a combination of features associated with two or more of the CSSM managers. (See AppleCSP/DL Module for an example of a multiservice CDSA plug-in.) The CDSA specification even allows for the expansion of CDSA by the addition of elective module managers and associated plug-ins. Plug-ins can call each other as well as being called by the CSSM managers—in fact, it is common for them to do so.
For an introduction to CDSA, see CDSA Explained, second edition, from the Open Group. The CDSA/CSSM technical standard is Common Security: CDSA and CSSM, version 2 (with corrigenda), also from the Open Group.
As long as you use the OS X security APIs, you don’t have to worry about the details of the OS X CDSA implementation. However, because a call to the CSSM API allows you to specify the plug-in module to which you want to direct your request, if you want to call CSSM directly you should have some understanding of the OS X CDSA plug-ins.
Apple CDSA Plug-ins
The OS X implementation of CDSA includes five CDSA plug-ins (see Figure A-1):
AppleCSP cryptographic service provider
AppleFileDL data storage library
AppleCSP/DL encrypted data storage provider
AppleX509CL certificate library
AppleX509TP trust policy library
This section briefly describes the purpose and function of each of these modules. (See the glossary for explanations of any unfamiliar terms.)
AppleCSP Module
All secure communications and authentication protocols are based on keys and encryption. The Apple cryptographic service provider (AppleCSP) is a basic plug-in module used by several of the security services for creating cryptographic keys and encrypting or decrypting data. Digital signatures also use the AppleCSP module to create message digests used to create and verify the signature. A CSP can use any number of algorithms.
AppleFileDL Module
A data storage library (DL) module provides secure storage—that is, storage of encrypted data on disk or another medium that persists when the power is turned off. The CDSA standard allows a DL module to use any sort of database or other data store. Keeping things simple, the AppleFileDL module stores its data in files in the OS X file system. It provides lower-level services used by the AppleCSP/DL plug-in for storing secrets on the keychain, Apple’s database used to store encrypted passwords, private keys, and other secrets.
AppleCSP/DL Module
The AppleCSP/DL plug-in is a multifunction module that combines cryptographic service and data storage functions to implement the Apple keychain, used for storage of passwords, keys, and other secrets. The AppleCSP/DL module calls the AppleFileDL module to perform file I/O, and the Security Server daemon to encrypt and decrypt secrets.
AppleX509CL Module
A certificate library (CL) module performs operations on digital certificates. Digital certificates are used to establish or confirm the identity of an entity such as a website or the sender of a digitally signed message. They do so by using a digital signature to ensure that only the identified entity could have provided the certificate (see Digital Certificates). A CL module performs such functions as creating new certificates (in memory), creating certificate revocation lists (that indicate which certificates are no longer valid), verifying the digital signature contained in a certificate, and extracting information from a certificate. CL modules do not store persistent copies of certificates. Rather, a DL module is used for that purpose.
The AppleX509CL plug-in performs these functions for certificates that conform to the X.509 standard promulgated by the International Telecommunication Union (ITU). The X.509 ITU standard is widely used on the Internet and throughout the information technology industry for designing secure apps based on a public key infrastructure (the set of hardware, software, people, policies, and procedures needed to create and manage digital certificates that are based on public key cryptography). See Asymmetric Keys for more information on public keys.
AppleX509TP Module
A digital certificate has a level of trust associated with it, based on attributes of the certificate. A trust policy is a set of rules that specify the actions that can be taken given a specific level of trust. In other words, the purpose of establishing a level of trust for a certificate is to answer the question “Should I trust this certificate for this action?”
The issuer of a digital certificate adds a digital signature to the certificate to ensure that the certificate has not been altered and to verify the identity of the issuer. In general, a digital signature is verified through the use of another certificate. Consequently, each certificate is typically part of a chain of certificates that ends with a root certificate, which can be verified without recourse to another certificate (see Digital Certificates).
A trust policy (TP) plug-in performs two main functions: it assembles the chain of certificates needed to verify a given certificate, and it determines the level of trust that can be accorded the certificate.
The AppleX509TP module performs these functions on X.509 certificates, using trust policies established by Apple.
CSSM Services
Although the OS X security APIs provide all the capabilities you are ever likely to need for developing secure apps, nearly all the standard CSSM APIs are also available for your use. This section briefly describes the functions provided by each CSSM service. For details, see Common Security: CDSA and CSSM, version 2 (with corrigenda), from the Open Group.
Cryptographic Services
Cryptographic Services in CSSM provides functions to perform the following tasks:
Encrypting and decrypting text and data
Creating and verifying digital signatures
Creating a cryptographic hash (used for message digests and other purposes)
Generating symmetric and asymmetric pairs of cryptographic keys
Generating pseudorandom numbers
Controlling access to the CSP for creation of keys
To see exactly which security protocols and algorithms are supported by Apple’s CSP implementation, see the documentation provided with the Open Source security code, which you can download at Apple’s Open Source site, and the Security Release Notes in the latest Xcode Tools from Apple.
Data Store Services
CSSM Data Store Services provides an API for storing and retrieving data that is independent of the type of storage used. If there is more than one DL module installed, the caller can query Data Store Services to learn the capabilities of each and select which one to use in a particular call. The Apple implementation of Data Store Services supports any standard CDSA DL plug-in module. The AppleFileDL Data Storage Library and AppleCSP/DL Encrypted Data Storage module both implement functions called by Data Store Services.
Certificate Services
Certificate Services as specified by CDSA performs the following functions:
Verifies the signatures on certificates and certificate revocation lists
Creates certificates and certificate revocation lists
Signs certificates and certificate revocation lists
Extracts values of fields from certificates and certificate revocation lists
Searches certificate revocation lists for specified certificates
Apple’s implementation of Certificate Services supports all of the CL API functions in the CDSA/CSSM specification.
Trust Policy Services
The OS X implementation of CSSM Trust Policy Services provides functions to verify certificates, to determine what attributes they contain and therefore the level of trust they can be given, and to construct a chain of related certificates. It does not implement other trust policy functions in the CSSM standard. Documentation for the CSSM trust policy functions supported by Apple’s TP implementation can be found with the Open Source security code, which you can download at Apple’s Open Source site.
Authorization Computation Services
Apple’s implementation of CSSM does not include the Authorization Computation Services defined in the CDSA standard. Instead, the Authorization Services API calls the Security Server daemon directly (see Figure A-1).
Glossary
anchor certificate
A digital certificate trusted to be valid, which can then be used to verify other certificates. An anchor certificate can be a root certificate, a cross-certified certificate (that is, a certificate signed with more than one certificate chain), or a locally defined source of trust.
CDSA
Abbreviation for Common Data Security Architecture. An open software standard for a security infrastructure that provides a wide array of security services, including fine-grained access permissions, authentication of users, encryption, and secure data storage. CDSA has a standard application programming interface, called CSSM. In addition, OS X includes its own security APIs that call the CDSA API for you.
certificate
See digital certificate.
certificate chain
See chain of trust.
certificate extension
A data field in a digital certificate containing information such as allowable uses for the certificate.
Certificate, Key, and Trust Services
An API you can use to create, manage, and read certificates; add certificates to a keychain; create encryption keys; and manage trust policies. In iOS, you can also use this API to encrypt, decrypt, and sign data.
certification authority (CA)
The issuer of a digital certificate. In order for the digital certificate to be trusted, the certification authority must be a trusted organization that authenticates an applicant before issuing a certificate.
chain of trust
A set of digital certificates in which each certificate signs the next certificate, ending in a root certificate that is also a trusted anchor certificate. A chain of trust can be used to verify the validity of a digital certificate.
cipher
A scheme for encrypting data.
ciphertext
Text or other data that has been encrypted. Compare cleartext.
cleartext
Ordinary, unencrypted data. Compare ciphertext.
cryptographic hashing
The process whereby data is transformed into a much smaller value that can take the place of the original data for cryptographic purposes. A hashing algorithm takes any amount of data and transforms it into a fixed-size output value. For a cryptographic hash function to be useful for security, it has to be extremely difficult or impossible to reconstruct the original data from the hash value, and it must be extremely unlikely that the same output value could result from any similar input data. See also message digest.
CSSM
Abbreviation for Common Security Services Manager. A public application programming interface for CDSA. CSSM also defines an interface for plug-ins that implement security services for a particular operating system and hardware environment.
decryption
The transformation of encrypted data back into the original cleartext. Compare encryption.
Diffie-Hellman key exchange
A protocol that provides a way for two ends of a communication session to generate a symmetric shared secret key through the exchange of public keys.
digest
See message digest.
digital certificate
A collection of data used to verify the identity of the holder or sender of the certificate. OS X and iOS support the X.509 standard for digital certificates. See also certificate chain.
digital signature
A way to ensure the integrity of a message or other data using public key cryptography. To create a digital signature, the signer generates a message digest of the data and then uses a private key to encrypt the digest. The signature includes the encrypted digest and identifies the signer. Anyone wanting to verify the signature uses the signer’s digital certificate, which contains the public key needed to decrypt the digest and specifies the algorithm used to create the digest.
encryption
The transformation of data into a form in which it cannot be made sense of without the use of some key. Such transformed data is referred to as ciphertext. Use of a key to reverse this process and return the data to its original (cleartext) form is called decryption.
hash algorithm
See cryptographic hashing.
identity
A digital certificate together with an associated private key.
keychain
A database in OS X and iOS used to store encrypted passwords, private keys, and other secrets. It is also used to store certificates and other non-secret information that is used in cryptography and authentication. Apps can use the Keychain Services API (or the legacy Keychain Manager API) to manipulate data in the keychain. Users can also access keychain data using the Keychain Access utility.
man-in-the-middle attack
An attack on a communication channel in which the attacker can intercept messages going between two parties without the communicating parties’ knowledge. Typically, the man in the middle substitutes messages and even cryptographic keys to impersonate one party to the other.
message digest
The result of applying a cryptographic hash function to a message or other data. A cryptographically secure message digest cannot be transformed back into the original message and cannot (or is very unlikely to) be created from a different input. Message digests are used to ensure that a message has not been corrupted or altered. For example, they are used for this purpose in digital signatures. The digital signature includes a digest of the original message, and the recipient prepares their own digest of the received message. If the two digests are identical, then the recipient can be confident that the message has not been altered or corrupted.
plaintext
See cleartext.
private key
A cryptographic key that must be kept secret, usually used in the context of public key cryptography. Although this term can also be used in the context of symmetric key cryptography, the term “secret key” (or “shared secret”) is preferred.
pseudorandom number
A number generated by an algorithm that produces a series of numbers with no discernible pattern. It should be impossible or nearly impossible to deduce the algorithm from such a series. However, unlike a truly random number generator, a pseudorandom number generator always produces the same series if the algorithm is given the same starting value or values.
public-private key pair
A pair of mathematically related keys that cannot be derived from one another used in public key cryptography. One of these keys (the public key) is made public while the other (the private key) is kept secure. Data encrypted with one key must be decrypted with the other.
public key
A cryptographic key that can be shared or made public without compromising the cryptographic method—generally, the public portion of a public-private key pair. See also public key cryptography.
public key certificate
See digital certificate.
public key cryptography
A cryptographic method using a public-private key pair. If the public key is used to encrypt the data, only the holder of the private key can decrypt it; therefore the data is secure from unauthorized use. If the private key is used to encrypt the data, anyone with the public key can decrypt it. Because only the holder of the private key could have encrypted it, such data can be used for authentication. See also digital certificate; digital signature. Compare symmetric key cryptography.
root certificate
A certificate that can be verified without recourse to another certificate. Rather than being signed by a further certification authority (CA), a root certificate is verified using the widely available public key of the CA that issued the root certificate. Compare anchor certificate.
root certification authority
The certification authority that owns the root certificate.
RSA encryption
A system of public key cryptography, named for its inventors: Ron Rivest, Adi Shamir, and Leonard Adleman. The RSA algorithm takes two large prime numbers, finds their product, and then derives a public-private key pair from the prime numbers and their product. The strength of this algorithm depends on the difficulty of factoring the resulting product and upon reasonable assurance of the primality of the values used in constructing the keys.
secret key
A cryptographic key that cannot be made public without compromising the security of the cryptographic method. In symmetric key cryptography, a secret key is used both to encrypt and decrypt data, and is often called a shared secret. Although the term “secret key” can be used in the context of public key cryptography, the term “private key” is preferred.
Secure Sockets Layer (SSL)
A protocol that provides secure communication over a TCP/IP connection such as the Internet. It uses digital certificates for authentication and digital signatures to ensure message integrity, and can use public key cryptography to ensure data privacy. An SSL service negotiates a secure session between two communicating endpoints. SSL is built into all major browsers and web servers. SSL has been superseded by Transport Layer Security (TLS).
secure storage
Storage of encrypted data on disk or another medium that persists when the power is turned off.
Secure Transport
The OS X and iPhone implementation of Secure Sockets Layer (SSL) and Transport Layer Security (TLS), used to create secure connections over TCP/IP connections such as the Internet. Secure Transport includes an API that is independent of the underlying transport protocol. The CFNetwork and URL Loading System APIs use the services of Secure Transport.
session key
A cryptographic key calculated or issued for use only for the duration of a specific communication session. Session keys are used, for example, by the SSL and Kerberos protocols, and are often obtained using Diffie-Hellman key exchange.
SSL
See Secure Sockets Layer (SSL).
strength
A measure of the amount of effort required to break a security system. For example, the strength of RSA encryption is believed to be related to the difficulty of factoring the product of two large prime numbers.
symmetric key cryptography
Cryptography that uses a single shared key to encrypt and decrypt data. See also secret key. Compare public key cryptography.
TLS
See Transport Layer Security (TLS).
Transport Layer Security (TLS)
A protocol that provides secure communication over a TCP/IP connection such as the Internet. It uses certificates for authentication and signatures to ensure message integrity, and can use public key cryptography to ensure data privacy. A TLS service negotiates a secure session between two communicating endpoints. TLS is built into recent versions of all major browsers and web servers. TLS is the successor to SSL. Although the TLS and SSL protocols are not interoperable, Secure Transport can back down to SSL 3.0 if a TLS session cannot be negotiated.
trust policy
A set of rules that specify the appropriate uses for a certificate based on its certificate extensions and other trust criteria. For example, a standard trust policy specifies that the user should be prompted for permission to trust an expired certificate. However, a custom trust policy might override that behavior in some specific set of circumstances, such as when verifying the signature on a document that you know was generated while the certificate was still valid.
X.509
A standard for digital certificates promulgated by the International Telecommunication Union (ITU). The X.509 ITU standard is widely used on the Internet and throughout the information technology industry for designing secure apps based on a public key infrastructure (PKI).
Document Revision History
This table describes the changes to Cryptographic Services Guide.
Date
Notes
2018-06-04
Streamline, and remove some outdated material.
2018-04-26
Use Randomization Services to generate pseudorandom numbers on all platforms.
2014-07-15
Updated the random number generation code in "Generating Random Numbers in OS X".
2012-12-13
Incorporated additional editorial feedback and revised the intro chapter.
2012-09-19
Updated artwork and made minor editorial fixes.
2012-01-09
New document that describes the encryption, decryption, signing, hashing, and other cryptographic technologies in OS X and iOS.
留言
張貼留言