Swiftpack.co - Package - VirgilSecurity/virgil-sdk-x

Virgil Core SDK Objective-C/Swift

Build Status CocoaPods Compatible Carthage compatible Platform GitHub license

Introduction | SDK Features | Installation | Configure SDK | Usage Examples | Docs | Support


Virgil Security provides a set of APIs for adding security to any application. In a few simple steps you can encrypt communications, securely store data, and ensure data integrity. Virgil Security products are available for desktop, embedded (IoT), mobile, cloud, and web applications in a variety of modern programming languages.

The Virgil Core SDK is a low-level library that allows developers to get up and running with Virgil Cards Service API quickly and add end-to-end security to their new or existing digital solutions.

In case you need additional security functionality for multi-device support, group chats and more, try our high-level Virgil E3Kit framework.

SDK Features


Virgil Core SDK is provided as a set of frameworks. These frameworks are distributed via Carthage and CocoaPods. In this guide you'll also find one more package - Virgil Crypto Library, that is used by the SDK to perform cryptographic operations.

All frameworks are available for:

  • iOS 9.0+
  • macOS 10.11+
  • tvOS 9.0+
  • watchOS 2.0+


CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

$ gem install cocoapods

To integrate VirgilSDK into your Xcode project using CocoaPods, specify it in your Podfile:

target '<Your Target Name>' do

  pod 'VirgilSDK', '~> 7.2'

Then, run the following command:

$ pod install


Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate VirgilSDK into your Xcode project using Carthage, create an empty file with name Cartfile in your project's root folder and add following lines to your Cartfile

github "VirgilSecurity/virgil-sdk-x" ~> 7.2

Linking against prebuilt binaries

To link prebuilt frameworks to your app, run following command:

$ carthage update --no-use-binaries

This will build each dependency or download a pre-compiled framework from github Releases.

Building for iOS/tvOS/watchOS

On your application targets’ “General” settings tab, in the “Linked Frameworks and Libraries” section, add following frameworks from the Carthage/Build folder inside your project's folder:

  • VirgilSDK
  • VirgilCrypto
  • VirgilCryptoFoundation
  • VSCCommon
  • VSCFoundation

On your application targets’ “Build Phases” settings tab, click the “+” icon and choose “New Run Script Phase.” Create a Run Script in which you specify your shell (ex: /bin/sh), add the following contents to the script area below the shell:

/usr/local/bin/carthage copy-frameworks

and add the paths to the frameworks you want to use under “Input Files”, e.g.:

Building for macOS

On your application target's “General” settings tab, in the “Embedded Binaries” section, drag and drop following frameworks from the Carthage/Build folder on disk:

  • VirgilSDK
  • VirgilCrypto
  • VirgilCryptoFoundation
  • VSCCommon
  • VSCFoundation

Additionally, you'll need to copy debug symbols for debugging and crash reporting on macOS.

On your application target’s “Build Phases” settings tab, click the “+” icon and choose “New Copy Files Phase”. Click the “Destination” drop-down menu and select “Products Directory”. For each framework, drag and drop corresponding dSYM file.

Configure SDK

This section contains guides on how to set up Virgil Core SDK modules for authenticating users, managing Virgil Cards and storing private keys.

Set up authentication

Set up user authentication with tokens that are based on the JSON Web Token standard with some Virgil modifications.

In order to make calls to Virgil Services (for example, to publish user's Card on Virgil Cards Service), you need to have a JSON Web Token ("JWT") that contains the user's identity, which is a string that uniquely identifies each user in your application.

Credentials that you'll need:

|Parameter|Description| |--- |--- | |App ID|ID of your Application at Virgil Dashboard| |App Key ID|A unique string value that identifies your account at the Virgil developer portal| |App Key|A Private Key that is used to sign API calls to Virgil Services. For security, you will only be shown the App Key when the key is created. Don't forget to save it in a secure location for the next step|

Set up JWT provider on Client side

Use these lines of code to specify which JWT generation source you prefer to use in your project:

import VirgilSDK

// Get generated token from server-side
let authenticatedQueryToServerSide: ((String) -> Void) -> Void = { completion in

// Setup AccessTokenProvider
let accessTokenProvider = CallbackJwtProvider { tokenContext, completion in
    authenticatedQueryToServerSide { jwtString in
        completion(jwtString, nil)

Generate JWT on Server side

For this subsection we've created a sample backend that demonstrates how you can set up your backend to generate the JWTs. To set up and run the sample backend locally, head over to your GitHub repo of choice:

Node.js | Golang | PHP | Java | Python and follow the instructions in README.

Set up Card Verifier

Virgil Card Verifier helps you automatically verify signatures of a user's Card, for example when you get a Card from Virgil Cards Service.

By default, VirgilCardVerifier verifies only two signatures - those of a Card owner and Virgil Cards Service.

Set up VirgilCardVerifier with the following lines of code:

import VirgilSDK
import VirgilCrypto

// initialize Crypto library
let cardCrypto = VirgilCardCrypto()

let yourBackendVerifierCredentials =
    VerifierCredentials(signer: "YOUR_BACKEND",
                        publicKey: Data(base64Encoded: publicKeyStr)!)

let yourBackendWhitelist =
    try! Whitelist(verifiersCredentials: [yourBackendVerifierCredentials])

let cardVerifier = VirgilCardVerifier(cardCrypto: cardCrypto,
                                      whitelists: [yourBackendWhitelist])

Set up Card Manager

This subsection shows how to set up a Card Manager module to help you manage users' public keys.

With Card Manager you can:

  • specify an access Token (JWT) Provider.
  • specify a Card Verifier used to verify signatures of your users, your App Server, Virgil Services (optional).

Use the following lines of code to set up the Card Manager:

// initialize cardManager and specify accessTokenProvider, cardVerifier
let cardManagerParams = CardManagerParams(cardCrypto: cardCrypto,
                                          accessTokenProvider: accessTokenProvider,
                                          cardVerifier: cardVerifier)

let cardManager = CardManager(params: cardManagerParams)

Usage Examples

Before you start practicing with the usage examples, make sure that the SDK is configured. See the Configure SDK section for more information.

Generate and publish Virgil Cards at Cards Service

Use the following lines of code to create a user's Card with a public key inside and publish it at Virgil Cards Service:

import VirgilSDK
import VirgilCrypto

// save a private key into key storage
let data = try! crypto.exportPrivateKey(keyPair.privateKey)
let entry = try! keychainStorage.store(data: data, withName: "Alice", meta: nil)

// publish user's card on the Cards Service
cardManager.publishCard(privateKey: keyPair.privateKey, publicKey: keyPair.publicKey).start { result in
    switch result {
        // Card is created
        case .success(let card): break
        // Error occured
        case .failure(let error): break

Sign then encrypt data

Virgil Core SDK allows you to use a user's private key and their Virgil Cards to sign and encrypt any kind of data.

In the following example, we load a private key from a customized key storage and get recipient's Card from the Virgil Cards Service. Recipient's Card contains a public key which we will use to encrypt the data and verify a signature.

import VirgilSDK
import VirgilCrypto

// prepare a message
let messageToEncrypt = "Hello, Bob!"
let dataToEncrypt = messageToEncrypt.data(using: .utf8)!

// prepare a user's private key
let alicePrivateKeyEntry = try! keychainStorage.retrieveEntry(withName: "Alice")
let alicePrivateKey = try! crypto.importPrivateKey(from: alicePrivateKeyEntry.data)

// using cardManager search for user's cards on Cards Service
cardManager.searchCards(identities: ["Bob"]).start { result in
    switch result {
    // Cards are obtained
    case .success(let cards):
        let bobRelevantCardsPublicKeys = cards
            .map { $0.publicKey }

        // sign a message with a private key then encrypt on a public key
        let encryptedData = try! crypto.signAndEncrypt(dataToEncrypt,
                                                       with: alicePrivateKey,
                                                       for: bobRelevantCardsPublicKeys)

    // Error occured
    case .failure(let error): break

Decrypt data and verify signature

Once the user receives the signed and encrypted message, they can decrypt it with their own private key and verify the signature with the sender's Card:

import VirgilSDK
import VirgilCrypto

// prepare a user's private key
let bobPrivateKeyEntry = try! keychainStorage.retrieveEntry(withName: "Bob")
let bobPrivateKey = try! exporter.importPrivateKey(from: bobPrivateKeyEntry.data)

// using cardManager search for user's cards on Cards Service
cardManager.searchCards(identities: ["Alice"]).start { result in
    switch result {
    // Cards are obtained
    case .success(let cards):
        let aliceRelevantCardsPublicKeys = cards.map { $0.publicKey }

        // decrypt with a private key and verify using a public key
        let decryptedData = try! crypto.decryptAndVerify(encryptedData, 
                                                         with: bobPrivateKey,
                                                         usingOneOf: aliceRelevantCardsPublicKeys)

    // Error occured
    case .failure(let error): break

Get Card by its ID

Use the following lines of code to get a user's card from Virgil Cloud by its ID:

import VirgilSDK

// using cardManager get a user's card from the Cards Service
cardManager.getCard(withId: "f4bf9f7fcbedaba0392f108c59d8f4a38b3838efb64877380171b54475c2ade8").start { result in
    switch result {
    // Card is obtained
    case .success(let card): break
    // Error occurred
    case .failure(let error): break

Get Card by user's identity

For a single user, use the following lines of code to get a user's Card by a user's identity:

import VirgilSDK

// using cardManager search for user's cards on Cards Service
cardManager.searchCards(identity: "Bob").start { result in
    switch result {
    // Cards are obtained
    case .success(let cards): break
    // Error occurred
    case .failure(let error): break

Revoke Card

You can revoke user's Card in case they don't need it anymore. Revoked Card can still be obtained using its identifier, but this card won't appear during search query.

import VirgilSDK

let result = cardManager.revokeCard(withId: card.identifier).start { result in
    switch result {
        // Card is revoked
        case .success: break
        // Error occured
        case .failure(let error): break

Generate key pair using VirgilCrypto

You can generate a key pair and save it in a secure key storage with the following code:

import VirgilCrypto

let crypto = try! VirgilCrypto()

let keyPair = try! crypto.generateKeyPair()

Save and retrieve key using keychain storage

import VirgilSDK
import VirgilCrypto

let storageParams = try! KeychainStorageParams.makeKeychainStorageParams()
let keychainStorage = KeychainStorage(storageParams: storageParams)

// export key to Data
let data = try! crypto.exportPrivateKey(keyPair.privateKey)

let identity = "Alice"

// save key data
let entry = try! keychainStorage.store(data: data, withName: identity, meta: nil)

// retrieve key data
let retrievedEntry = try! keychainStorage.retrieveEntry(withName: identity)

// import key from Data
let privateKey = try! exporter.importPrivateKey(from: retrievedEntry.data)


Virgil Security has a powerful set of APIs, and the Developer Documentation can get you started today.


This library is released under the 3-clause BSD License.


Our developer support team is here to help you. Find out more information on our Help Center.

You can find us on Twitter or send us email support@VirgilSecurity.com.

Also, get extra help from our support team on Slack.


Stars: 26


Used By

Total: 0


v7.2.1 - 2020-05-21 09:03:05


  • Required version of VirgilCrypto

v7.2.0 - 2020-04-16 16:22:02


  • SQLite support

v7.1.0 - 2020-01-14 12:41:43


  • Updated dependencies

v7.0.3 - 2019-11-06 13:06:36


  • Returned errors

v7.0.2 - 2019-10-23 09:08:37


  • VirgilCrypto dependency version requirement

v7.0.1 - 2019-10-21 14:56:45


  • Updated dependencies
  • Switched FileSystem encryption to authEncryption

v7.0.0 - 2019-08-13 11:38:59


  • KeyknoxClient adopted to new Keyknox Service v2


  • getOudated method to CardManager and CardClient
  • import and export Card as Data
  • biometric feature to KeychainStorage

v6.0.0 - 2019-07-10 10:59:28


  • Got rid of VirgilCryptoAPI
  • Added retries for network requests (handles 5xx service errors and connectivity problems)
  • Moved KeyknoxSDK to VirgilSDK
  • Replaced GenericOperation Result with built-in type

v5.8.0 - 2019-05-30 07:20:41


  • Card revocation

v5.7.2 - 2019-04-09 19:20:32


  • Increased macOS minimum deployment target to 10.11
  • Migrated to Xcode 10.2 and Swift 5.0

v5.7.1 - 2019-03-21 10:01:56


  • Updated README to use new crypto v5


  • CachedJwtProvider TokenContext.forceReload behavior

v5.7.0 - 2019-01-17 16:08:51


  • SandboxedKeychainStorage to separate keys using namespaces
  • Mutex class

v5.6.1 - 2019-01-15 12:59:35


  • Migrated to Xcode 10.1
  • Updated copyright

v5.6.0 - 2018-12-07 23:17:21


  • Search using multiple identities
  • Added possibility to use custom app name for KeychainStorageParams (for key sharing between app and extensions)

v5.5.0 - 2018-10-25 15:58:24


  • CachingJwtProvider is now can be initialized with initial value


  • CachingJwtProvider is now thread-safe

v5.4.1 - 2018-10-09 22:57:42


  • Carthage release binaries on github

v5.4.0 - 2018-10-09 20:32:59


  • Fixed KeychainStorage.retrieveAllEntries() bug when external libraries also use Keychain
  • Small fixes


  • Migrated to Xcode 10 / Swift 4.2

v5.3.0 - 2018-07-10 15:05:44


  • KeychainStorage

v5.2.0 - 2018-06-27 15:22:40


  • Made part of API public
  • Improved ServiceRequest API
  • Result.getResult now rethrows error
  • Added static functions to CardManager


  • Made embedded callback escaping in Jwt Providers

Http Headers Keys Bug Fix - 2018-06-18 13:12:05


  • Http headers keys are now compared case-insensitively in accordance with RFC 2616.

Virgil Objective-C/Swift SDK v5.1.0 - 2018-05-21 15:13:37


  • Added CachingJwtProvider
  • Enabled Bitcode for tvOS, macOS, watchOS
  • Improved GenericOperation usability
  • Made part of API public to allow usage from other frameworks
  • Migrated to Xcode 9.3


  • License headers

Virgil Objective-C/Swift SDK v4.8.0 - 2018-02-28 16:32:47

Virgil Objective-C/Swift SDK v5.0.0 - 2018-02-21 22:42:22


  • Switched to Virgil v5 services
  • Rewritten in Swift

Virgil Objective-C/Swift SDK v4.7.0 - 2017-09-29 20:19:27


  • Updated project&configuration for Xcode 9

Virgil Objective-C/Swift SDK v4.6.3 - 2017-09-29 16:09:24

Virgil Objective-C/Swift SDK v4.6.2 - 2017-09-04 11:17:27

Virgil Objective-C/Swift SDK v4.6.1 - 2017-08-31 19:00:16

Virgil Objective-C/Swift SDK v4.6.0 - 2017-07-05 13:50:06

Virgil Objective-C/Swift SDK v4.5.0 - 2017-06-08 09:47:19


  • Introduced macOS support


  • Fixed AppStore submission problem when using Carthage