Skip to content

A simple wrapper of RSA encryption and decryption in Swift.

License

Notifications You must be signed in to change notification settings

nebuhtit/SwiftRSA

 
 

Repository files navigation

SwiftRSA

codebeat badge

SwiftRSA is a simple wrapper of Apple Security API which makes RSA encryption and decryption easy to use. It is motivated by creating the app of boxueio.com.

Features

  • Fully tested.
  • Inituitive interface.
  • Updated to Swift 5.

SwiftRSA 101

Create a public / private key

With a PEM encoded string

let pemPrivate = """
  -----BEGIN RSA PRIVATE KEY-----
  MIIEowIBAAKCAQEA0HRZppSvYCAFTo+ie5z7EXmzFJ9rSpuUJUAAvikOq/lGVqaK
  ...
  2bhAIUk7eWJTorZYujzXO+HmDt+8/ha+RBAtgQPDFPGHG/QaZik8
  -----END RSA PRIVATE KEY-----
  """
let pemPublic = """
  -----BEGIN PUBLIC KEY-----
  MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0HRZppSvYCAFTo+ie5z7
  ...
  mwIDAQAB
  -----END PUBLIC KEY-----
  """

guard let privateKey = PrivateKey(pemEncoded: pem) else {
  // Invalid pem string
}

guard let publicKey = PublicKey(pemEncoded: pemPublic) else {
  // Invalid pem string
}

With a DER encoded string

guard let privateKey = PrivateKey(der: data) else {
  // Invalid DER data
}

guard let publicKey = PublicKey(der: data) else {
  // Invalid DER data
}

Encrypt with a public key

let ct = ClearText(string: "Hello world")
let encrypted = try ct.encrypted(with: publicKey, by: .rsaEncryptionOAEPSHA512)
/// `encrypted` is an `EncryptedText` object.

Decrypt with a private key

/// `originText` is a `ClearText` object
let originText = try encrypted.decrypted(with: privateKey)

Get data from an EncryptedText object

let data = encrypted.data

Get string from a ClearText object

let string = originText.stringValue

Installation

To integrate SwiftRSA into your Xcode project using Carthage, speicify the following line in your Cartfile:

github "puretears/SwiftRSA" ~> 0.1

Requirements

  • iOS 10.0+
  • Swift 4.0+

Next Steps

  • Cocoapods and SPM support;
  • More RSA algorithm support;
  • Add X.509 certificate support;
  • Add sign and verify support;

Release History

  • 0.1
    • Initial release

License

SwiftRSA is released under the MIT license. See LICENSE for details.

About

A simple wrapper of RSA encryption and decryption in Swift.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Swift 98.0%
  • Objective-C 2.0%