How to download a key and encrypt with RSA Swift

How can you load a public or private key from a file and then encrypt or decrypt the data using Swift when using libraries or APIs?

+3


source to share


2 answers


You can use OS Xs built-in OpenSSL to generate and encrypt or OS X and Swift combo.

OpenSSL commands:

  • openssl genrsa -out rsaPrivateKey.pem 4096 (2048 is probably too much too - dealer choice)
  • openssl rsa -in rsaPrivateKey.pem -out rsaPrivateKey.key
  • openssl req -new -key rsaPrivateKey.key -out rsaCertReq.crt (this step requires basic information and iOS requires a password, so set one when it asks)
  • openssl x509 -req -days 10000 -in rsaCertReq.crt -signkey rsaPrivateKey.key -out rsaCert.crt
  • openssl x509 -outform der -in rsaCert.crt -out publicKey.der
  • openssl pkcs12 -export -out privateKey.pfx -inkey rsaPrivateKey.key -in rsaCert.crt

After all, the important files from an iOS perspective are publicKey.der and privateKey.pfx. You will use publicKey.der to encrypt data and privateKey.pfx to decrypt.


IOS encryption

On iOS, in addition to providing helper functions for encryption and decoding keys, the Certificate, Key and Trusted Services API also provides basic encryption, decryption, signing, and validation of data blocks using the following SecKey functions:

SecKeyEncrypt - encrypts the data block using the specified key.



SecKeyDecrypt -decrypts a block of data using the specified key.

SecKeyRawSign - assigns a block of data using the specified key.

SecKeyRawVerify - verifies the signature against the data block and the specified key.

Apple Docs
Data Encryption and Hashing

You can find examples of using these features in the Apple docs Certificate, Key and Trusted Services Objectives for iOS

import UIKit
import CoreFoundation

      

Use the bridging header file for Security.h

#import <Security/Security.h>

      

+4


source


Ok I did some research for you and here's what I came up with (based on the answers I see in this related question ).

Swift has an open source GitHub project called Heimdall , which is a great wrapper around Apple's security infrastructure. The ReadMe on the GitHub page says "Swift 1.2", but Xcode 7 and Swift 2.0 will be completed any day, so hopefully will be updated soon.



If you want to skip using open source content, you need to contact Apple's infrastructure directly. Take a look at this sample code, which includes the following calls: SecKeyEncrypt

as well SecKeyDecrypt

.

These two calls (and everything in SecKey.h) appear to be C functions, but the Apple documentation I linked to seems to indicate that a Swift API may be available.

+1


source







All Articles