Use of symmetric and asymmetric encryption algorithms under Mac and IOS

Source: Internet
Author: User
Tags asymmetric encryption

Share symmetric and asymmetric encryption algorithms used on Mac and IOS. Includes RSA,DSA, AES, DES, 3DES and Blowfish, and more.
Because to implement the SSH protocol, so the use of these algorithms, these algorithms on the Mac and iOS interface is difficult to use, I spent a lot of time, here to share, I hope to help everyone.
(This does not mention the interface of OpenSSL on Apple)

The main references to Apple's documentation are:

Cryptographic Services Guide

Apple Encrypting and Hashing Data

Let's outline the overall situation first:
Basically, the encryption and decryption on these two platforms are inseparable from the keychain service. Keychain is a storage area on Mac and iOS that stores sensitive information such as certificates, passwords, keys, and so on. There are specialized APIs to access these interfaces. Sometimes in order to get an instance of a key, we have to find a way to import the data into keychain before we can get an instance of the key through keychain. Say it later.

On the Mac, there are three ways to implement the cryptographic decryption signature service:

    1. Security Transforms api-a Core-foundation-level API that provides support for signing and verifying, symmetric cryptograp HY, and BASE64 encoding and decoding.
      Is the Corefoundation level API, which provides the most complete functionality and algorithmic support. Includes symmetric, asymmetric algorithms. Implement encryption, Signature function. Unfortunately, this interface is only valid on Mac. Not on iOS. But some features have to be used, so implementing cross-platform code requires some patching.

    2. Common Crypto-a C-level API that can perform most symmetric encryption and decryption tasks
      This is a C-style interface. The good news is that it's available on both Mac and iOS and can be cross-platform. But the bad news is that it contains only symmetric cryptographic algorithms, but no asymmetric algorithms. Therefore, you can only encrypt and decrypt, not sign and verify. In fact, there was a Comoncryptorsa module on Apple before, but somehow it disappeared.

    3. Cdsa/cssm-a Legacy API that should is used only to perform tasks not supported by the other APIs, such as asymmetric Encryption
      This is a scary name, Common data Security Architecture (CDSA) general purpose. It's strange that it was discarded by Apple soon after it was accepted. It's not recommended anymore. So I won't mention it.

On IOS, there are basically two ways of doing this:

    1. Common Crypto. This has been said on the above. Symmetric algorithm interface.

    2. Implement encryption, decryption, signing, and validation using the system-specific APIs:

The system provides the following 4 functions:

SecKeyEncrypt—encrypts a block of data using the specified key.SecKeyDecrypt—decrypts a block of data using the specified key.SecKeyRawSign—signs a block of data using the specified key.SecKeyRawVerify—verifies a signature against a block of data and a specified key.

Based on the above analysis, we hold the principle of minimizing code duplication and cross-platform development: The symmetric algorithm uses the "Common Crypto" module. Because there are two platforms. Instead of symmetry, they need to be implemented separately.

Here are some details to share:

One, asymmetric encryption algorithm, signature and verification. (RSA/DSA signature and Verity)

This needs to be developed independently on two platforms.

    1. MAC platform.

On the Mac platform, we use its Security Transforms API.

Reference here: Security Transforms programming guide-signing and verifying

There's a good code snippet on it. It is important to note how to turn RSA parameters into Seckeyref objects required by the API.

This is its import fragment.

    params.keyUsage = NULL;    params.keyAttributes = NULL;    SecExternalItemType itemType = kSecItemTypeCertificate;    SecExternalFormat externalFormat = kSecFormatPEMSequence;    int flags = 0; oserr = SecItemImport(cfdataprivatekey,        NULL, // filename or extension        &externalFormat, // See SecExternalFormat for details        &itemType, // item type        flags, // See SecItemImportExportFlags for details        &params,        NULL, // Don‘t import into a keychain        &temparray);    if (oserr) {        fprintf(stderr, "SecItemImport failed (oserr=%d)\n", oserr);        CFShow(temparray);        exit(-1);    }    privatekey = (SecKeyRef)CFArrayGetValueAtIndex(temparray, 0);

This is to create a seckeyref instance. Import the data through Secitemimport. into a seckeyref instance. The data is placed in the Cfdataprivatekey. This data must be a certificate in PEM format. Because this case requires a private key, the certificate needs to contain the private key, which is in PEM format.

Here is a special introduction to how to import from SSH's public key format. In RSA, for example, the public key of RSA is actually a base e, and a large integer m,

e = [int32(len), bytes(value)]m = [int32(len), bytes(value)]

The structure of E and M is the same. The length of the first 4 bytes, followed by the sequence of bytes. Len is the big end of the front, with the usual small side is a difference.
The complete body is probably like this:

Binary = [0x00, 0x00, 0x00, 0x07, ‘ssh-rsa‘, e, m]keydata = ‘ssh-rsa‘ + Base64Encode(Binary)

This keydata can be used to build the parameters used above Cfdataprivatekey.

For DSA, the structure is similar to the above:

p = [int32(len), bytes(value)]q = [int32(len), bytes(value)]g = [int32(len), bytes(value)]y = [int32(len), bytes(value)]Binary = [0x00, 0x00, 0x00, 0x07, ‘ssh-dss‘, p, q, g, y]keydata = ‘ssh-dss‘ + Base64Encode(Binary)
    1. For IOS, the platform, we use the two functions described above to sign and verify:
SecKeyRawSign—signs a block of data using the specified key.SecKeyRawVerify—verifies a signature against a block of data and a specified key.

Both of these functions are desperately required for a seckeyref parameter, and there is really no direct way on IOS to create an instance of Seckeyref directly from a large integer.

or read through keychain. Alternatively, import the PKCS12-formatted certificate with the private key through the Secpkcs12import () function and obtain the SECIDENTITYREF instance. The private key is then exported to the Seckeyref instance using the Secidentitycopyprivatekey () function.

Osstatus Extractidentityandtrust (cfdataref inpkcs12data, Secidentityref *outidentity, Sectrustref *outtrust, Cfstringref Keypassword) {osstatus s    Ecurityerror = errsecsuccess;    const void *keys[] = {Ksecimportexportpassphrase};    const void *values[] = {Keypassword};    Cfdictionaryref optionsdictionary = NULL;  /* Create A dictionary containing the passphrase if one was specified. Otherwise, create an empty dictionary.                                                  */optionsdictionary = Cfdictionarycreate (NULL, Keys, Values, (Keypassword 1:0), NULL, NU  LL);    1 cfarrayref items = NULL;                                    Securityerror = Secpkcs12import (Inpkcs12data, Optionsdictionary,                    &items);   2 if (Securityerror = = 0) {//3 cfdictionaryref myidentityandtrust = Cfarra        Ygetvalueatindex (items, 0);        const void *tempidentity = NULL; tempidentity = Cfdictionarygetvalue (Myidentityandtrust, Ksecimporti        temidentity);        Cfretain (tempidentity);        *outidentity = (secidentityref) tempidentity;        const void *temptrust = NULL;        Temptrust = Cfdictionarygetvalue (Myidentityandtrust, ksecimportitemtrust);        Cfretain (Temptrust);    *outtrust = (sectrustref) temptrust;    } if (optionsdictionary)//4 cfrelease (optionsdictionary);    if (items) cfrelease (items); return securityerror;}

Another way is that Apple officially gives the sample code, forcing a patchwork seckeyref example.
Here is an example code for Seckeywrapper: seckeywrapper Instance Code

And can be downloaded here directly to the source code: Seckeywrapper Source

There are many examples of apple writing in this source code. Very good. Use this code to implement the sword.

Two, for symmetric encryption algorithm.
This is relatively simple, we use the Common Crypto module directly. You can cross-platform on Mac and iOS.

Please refer here: Apple Common Crypto Library

    1. Create Cccryptorref objects using Cccryptorcreate or Cccryptorcreatewithmode.
      The cccryptorupdate is then constantly called. For encryption/decryption.
      Last Call: Cccryptorfinal. Gets the last piece of encryption method.

It is recommended to use the Cccryptorcreatewithmode method. Because it can specify more parameters. such as the padding and ciphermode of cryptographic algorithms.

Finally, let's share a few more ways to generate cryptography-safe random numbers on Mac and iOS: Generating random Numbers

In simple terms. On a Mac, a /dev/random cryptographic security random number can be obtained through the fopen read device.

FILE *fp = fopen("/dev/random", "r");if (!fp) {    perror("randgetter");    exit(-1);}uint64_t value = 0;int i;for (i=0; i<sizeof(value); i++) {    value <<= 8;    value |= fgetc(fp);}fclose(fp);

On IOS, because the device cannot be read, it provides a special method: Secrandomcopybytes, it is very simple to use.

Welcome to my Independent blog https://blog.byneil.com

Use of symmetric and asymmetric encryption algorithms under Mac and IOS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.