Bennett Bennett - 8 months ago 91
Swift Question

How to Load a Key and Encrypt With RSA Swift

How could you load a public or private key from a file, and then encrypt or decrypt data with it in Swift while using no libraries or APIs?


You could use OS X’s built-in OpenSSL to generate and encrypt or a combo of OS X and Swift.

OpenSSL commands:

  1. openssl genrsa -out rsaPrivateKey.pem 4096 (2048 is likely fine too – dealers choice)
  2. openssl rsa -in rsaPrivateKey.pem -out rsaPrivateKey.key
  3. openssl req -new -key rsaPrivateKey.key -out rsaCertReq.crt (this step requires basic info, and iOS requires a password, so set one when it asks)
  4. openssl x509 -req -days 10000 -in rsaCertReq.crt -signkey rsaPrivateKey.key -out rsaCert.crt
  5. openssl x509 -outform der -in rsaCert.crt -out publicKey.der
  6. openssl pkcs12 -export -out privateKey.pfx -inkey rsaPrivateKey.key -in rsaCert.crt

In the end, the important files from an iOS standpoint are publicKey.der and privateKey.pfx. You will use publicKey.der to encrypt data, and privateKey.pfx to decrypt.

Encryption in iOS

In iOS, in addition to providing support functions for encoding and decoding keys, the Certificate, Key, and Trust Services API also provides basic encryption, decryption, signing, and verifying of blocks of data using the following SecKey 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.

Apple Docs
Encrypting and Hashing Data

You can find examples of how to use these functions in Apple docs Certificate, Key, and Trust Services Tasks for iOS

import UIKit
import CoreFoundation

Use a bridging header file for Security.h

#import <Security/Security.h>