CryptoSwift README

The project's README from github.com/krzyzanowskim/CryptoSwift. As one markdown file: README.md.

Platform

Swift support Swift Package Manager compatible Carthage compatible CocoaPods Deprecated

CryptoSwift

Pure Swift cryptographic primitives and utilities for Swift. (#PureSwift)

Note: The current release line builds with Swift 5.6 and newer toolchains. If you need an older compiler, use the matching legacy branch listed in Swift version support. Older branches are not actively maintained.


Requirements | Features | Recommended Defaults | Contribution | Installation | Swift Version Support | How-to | Author | License | Changelog

Support & Sponsors

The financial sustainability of the project is possible thanks to the ongoing contributions from our GitHub Sponsors

Premium Sponsors

None

Requirements

Good mood

Features

Hash (Digest)

MD5 | SHA1 | SHA2-224 | SHA2-256 | SHA2-384 | SHA2-512 | SHA3

Cyclic Redundancy Check (CRC)

CRC32 | CRC32C | CRC16

Cipher

AES-128, AES-192, AES-256 | ChaCha20 | XChaCha20 | Rabbit | Blowfish

RSA (public-key encryption algorithm)

Encryption, Signature

Message authenticators

Poly1305 | HMAC (MD5, SHA1, SHA256) | CMAC | CBC-MAC

Cipher mode of operation

Password-Based Key Derivation Function

Data padding

Authenticated Encryption with Associated Data (AEAD)

Why

Why? Because I can.

How do I get involved?

You want to help, great! Go ahead and fork our repo, make your changes and send us a pull request.

Contribution

Check out CONTRIBUTING.md for more information on how to help with CryptoSwift.

Installation

Swift Package Manager

CryptoSwift is primarily distributed as source through Swift Package Manager.

Add the package dependency:

dependencies: [
  .package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", from: "1.10.0")
]

Then add the product to the target that uses it:

.target(
  name: "MyTarget",
  dependencies: [
    .product(name: "CryptoSwift", package: "CryptoSwift")
  ]
)

If you profile crypto-heavy workloads from Xcode, compare Debug and Release builds before drawing conclusions. Debug builds can be dramatically slower than optimized Release builds.

XCFramework

If you prefer a prebuilt optimized binary for manual Xcode integration, build CryptoSwift.xcframework locally:

./scripts/build-framework.sh

The generated CryptoSwift.xcframework is an alternative to source-based Swift Package Manager integration. It is not used by the package defined in Package.swift.

Screen Shot 2020-10-27 at 00 06 32

Hardened Runtime (macOS) and Xcode

If you embed the prebuilt CryptoSwift.xcframework in a hardened macOS app, library validation can prevent the binary from loading when the app is signed with Sign to Run Locally.

To avoid that, use one of these options:

Xcode Project

To vendor CryptoSwift directly in an Xcode project, add it as a submodule from the top-level project directory:

git submodule add https://github.com/krzyzanowskim/CryptoSwift.git

Enable Whole-Module Optimization for best performance. Non-optimized builds of crypto-heavy code are significantly slower.

Legacy Package Managers

Carthage

You can use Carthage for existing projects. Specify in Cartfile:

github "krzyzanowskim/CryptoSwift"

Run carthage to build the framework and drag the built CryptoSwift.framework into your Xcode project. Follow the Carthage getting started guide. See common issues if the build fails.

CocoaPods

Note: CocoaPods is deprecated for new CryptoSwift integrations. Prefer Swift Package Manager. Keep CocoaPods only when you need it for an existing project.

You can still use CocoaPods.

pod 'CryptoSwift', '~> 1.10.0'

CocoaPods builds may need manual optimization settings if performance matters. You can adjust them after installation, or use the cocoapods-wholemodule plugin.

Embedded Framework

Embedded frameworks require a minimum deployment target of iOS 11.0 or macOS 10.13. Drag CryptoSwift.xcodeproj into your Xcode project, add the appropriate framework as a dependency, then embed CryptoSwift.framework in your app target.

Sometimes the embedded framework option is not available automatically. In that case, add a new build phase for the target.

iOS, macOS, watchOS, tvOS

In the project, you'll find single scheme for all platforms:

Swift Version Support

Legacy compiler branches:

How-to

For new designs, start with an AEAD construction such as AES-GCM, AES-CCM, or ChaCha20-Poly1305. Use raw block modes only when you need compatibility with an existing protocol.

Basics
import CryptoSwift

CryptoSwift uses array of bytes aka Array<UInt8> as a base type for all operations. Every data may be converted to a stream of bytes. You will find convenience functions that accept String or Data, and it will be internally converted to the array of bytes.

Data types conversion

For your convenience, CryptoSwift provides two functions to easily convert an array of bytes to Data or Data to an array of bytes:

Data from bytes:

let data = Data([0x01, 0x02, 0x03])

Data to Array<UInt8>

let bytes = data.byteArray                // [1,2,3]

Hexadecimal encoding:

let bytes = Array<UInt8>(hex: "0x010203")  // [1,2,3]
let hex   = bytes.toHexString()            // "010203"

Build bytes out of String

let bytes: Array<UInt8> = "cipherkey".bytes  // Array("cipherkey".utf8)

Also... check out helpers that work with Base64 encoded data:

"aPf/i9th9iX+vf49eR7PYk2q7S5xmm3jkRLejgzHNJs=".decryptBase64ToString(cipher)
"aPf/i9th9iX+vf49eR7PYk2q7S5xmm3jkRLejgzHNJs=".decryptBase64(cipher)
bytes.toBase64()
Calculate Digest

Hashing an array of bytes (Array<UInt8>)

let input: Array<UInt8> = [0x01, 0x02, 0x03]

let md5Digest = input.md5()
let md5Digest2 = Digest.md5(input)

Hashing Data

let data = Data([0x01, 0x02, 0x03])

let md5Digest = data.md5()
let sha1Digest = data.sha1()
let sha224Digest = data.sha224()
let sha256Digest = data.sha256()
let sha384Digest = data.sha384()
let sha512Digest = data.sha512()
do {
    var digest = MD5()
    _ = try digest.update(withBytes: [0x31, 0x32])
    _ = try digest.update(withBytes: [0x33])
    let result = try digest.finish()
} catch {
    print(error)
}

Hashing a String and printing result

let hash = "123".md5() // "123".bytes.md5()
Calculate CRC
let bytes: Array<UInt8> = [0x01, 0x02, 0x03]
let data = Data(bytes)

let bytesCRC16 = bytes.crc16()
let dataCRC16 = data.crc16()

let bytesCRC32 = bytes.crc32()
let dataCRC32 = data.crc32()
Message authenticators
// Calculate Message Authentication Code (MAC) for message
let key = Array<UInt8>(repeating: 0x01, count: 32)
let message = Array("authenticated message".utf8)

let poly1305 = try Poly1305(key: key).authenticate(message)
let hmac = try HMAC(key: key, variant: .sha2(.sha256)).authenticate(message)
let cmac = try CMAC(key: key).authenticate(message)
Password-Based Key Derivation Functions
let password: Array<UInt8> = Array("s33krit".utf8)
let salt: Array<UInt8> = Array("nacllcan".utf8)

let key = try PKCS5.PBKDF2(password: password, salt: salt, iterations: 4096, keyLength: 32, variant: .sha2(.sha256)).calculate()
let password: Array<UInt8> = Array("s33krit".utf8)
let salt: Array<UInt8> = Array("nacllcan".utf8)
// Scrypt implementation does not implement work parallelization, so `p` parameter will
// increase the work time even in multicore systems
let key = try Scrypt(password: password, salt: salt, dkLen: 64, N: 16384, r: 8, p: 1).calculate()
HMAC-based Key Derivation Function
let password: Array<UInt8> = Array("s33krit".utf8)
let salt: Array<UInt8> = Array("nacllcan".utf8)

let key = try HKDF(password: password, salt: salt, variant: .sha2(.sha256)).calculate()
Data Padding

Some content-encryption algorithms assume the input length is a multiple of k octets, where k is greater than one. For such algorithms, the input shall be padded.

let input = Array("hello".utf8)
let padded = Padding.pkcs7.add(to: input, blockSize: AES.blockSize)

Working with Ciphers

Examples below use [UInt8] keys, IVs or nonces, and messages of the correct length for the selected algorithm.

ChaCha20
let encrypted = try ChaCha20(key: key, iv: iv).encrypt(message)
let decrypted = try ChaCha20(key: key, iv: iv).decrypt(encrypted)
Rabbit
let encrypted = try Rabbit(key: key, iv: iv).encrypt(message)
let decrypted = try Rabbit(key: key, iv: iv).decrypt(encrypted)
Blowfish
let encrypted = try Blowfish(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).encrypt(message)
let decrypted = try Blowfish(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).decrypt(encrypted)
AES

For new designs, prefer AES-GCM unless you need compatibility with an existing CBC, CFB, OFB, or CTR protocol.

Notice regarding padding: Manual padding of data is optional, and CryptoSwift uses PKCS7 padding by default. If you need to manually disable or enable padding, configure the AES initializer explicitly.

Variant of AES encryption (AES-128, AES-192, AES-256) depends on given key length:

AES-256 example

let aes = try AES(key: [1,2,3 /* ... 32 bytes total */], blockMode: CBC(iv: [1,2,3 /* ... 16 bytes total */]), padding: .pkcs7)
let encryptedBytes = try aes.encrypt(Array("secret message".utf8))

Full example:

let password: [UInt8] = Array("s33krit".utf8)
let salt: [UInt8] = Array("nacllcan".utf8)

/* Generate a key from a `password`. Optional if you already have a key */
let key = try PKCS5.PBKDF2(
    password: password,
    salt: salt,
    iterations: 4096,
    keyLength: 32, /* AES-256 */
    variant: .sha2(.sha256)
).calculate()

/* Generate random IV value. IV is public value. Either need to generate, or get it from elsewhere */
let iv = AES.randomIV(AES.blockSize)

/* AES cryptor instance */
let aes = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7)

/* Encrypt Data */
let inputData = Data()
let encryptedBytes = try aes.encrypt(inputData.byteArray)
let encryptedData = Data(encryptedBytes)

/* Decrypt Data */
let decryptedBytes = try aes.decrypt(encryptedData.byteArray)
let decryptedData = Data(decryptedBytes)
All at once
do {
    let aes = try AES(key: "keykeykeykeykeyk", iv: "drowssapdrowssap") // aes128
    let ciphertext = try aes.encrypt(Array("Nullam quis risus eget urna mollis ornare vel eu leo.".utf8))
} catch { }
Incremental updates

Incremental operations use instance of Cryptor and encrypt/decrypt one part at a time, this way you can save on memory for large files.

do {
    var encryptor = try AES(key: "keykeykeykeykeyk", iv: "drowssapdrowssap").makeEncryptor()

    var ciphertext = Array<UInt8>()
    // aggregate partial results
    ciphertext += try encryptor.update(withBytes: Array("Nullam quis risus ".utf8))
    ciphertext += try encryptor.update(withBytes: Array("eget urna mollis ".utf8))
    ciphertext += try encryptor.update(withBytes: Array("ornare vel eu leo.".utf8))
    // finish at the end
    ciphertext += try encryptor.finish()

    print(ciphertext.toHexString())
} catch {
    print(error)
}
AES Advanced usage
let input: Array<UInt8> = [0,1,2,3,4,5,6,7,8,9]

let key: Array<UInt8> = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]
let iv: Array<UInt8> = [] // Random bytes of `AES.blockSize` length

do {
    let encrypted = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).encrypt(input)
    let decrypted = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).decrypt(encrypted)
} catch {
    print(error)
}

AES without data padding

let input: Array<UInt8> = [0,1,2,3,4,5,6,7,8,9]
let encrypted: Array<UInt8> = try! AES(key: Array("secret0key000000".utf8), blockMode: CBC(iv: Array("0123456789012345".utf8)), padding: .noPadding).encrypt(input)

Using convenience extensions

let plain = Data([0x01, 0x02, 0x03])
let encrypted = try! plain.encrypt(ChaCha20(key: key, iv: iv))
let decrypted = try! encrypted.decrypt(ChaCha20(key: key, iv: iv))
AES-GCM

The result of Galois/Counter Mode (GCM) encryption is ciphertext and authentication tag, which is later used for decryption.

encryption

do {
    // In combined mode, the authentication tag is directly appended to the encrypted message. This is usually what you want.
    let gcm = GCM(iv: iv, mode: .combined)
    let aes = try AES(key: key, blockMode: gcm, padding: .noPadding)
    let encrypted = try aes.encrypt(plaintext)
    let tag = gcm.authenticationTag
} catch {
    // failed
}

decryption

do {
    // In combined mode, the authentication tag is appended to the encrypted message. This is usually what you want.
    let gcm = GCM(iv: iv, mode: .combined)
    let aes = try AES(key: key, blockMode: gcm, padding: .noPadding)
    let decrypted = try aes.decrypt(encrypted)
} catch {
    // failed
}

Note: GCM instance is not intended to be reused. So you can't use the same GCM instance from encoding to also perform decoding.

AES-CCM

The result of Counter with Cipher Block Chaining-Message Authentication Code encryption is ciphertext and authentication tag, which is later used for decryption.

do {
    // `encrypted` contains ciphertext with the authentication tag appended.
	let tagLength = 8
	let ccm = CCM(iv: iv, tagLength: tagLength, messageLength: encrypted.count - tagLength, additionalAuthenticatedData: data)
    let aes = try AES(key: key, blockMode: ccm, padding: .noPadding)
    let decrypted = try aes.decrypt(encrypted)
} catch {
    // failed
}

Check documentation or CCM specification for valid parameters for CCM.

AEAD
let sealed = try AEADChaCha20Poly1305.encrypt(plaintext, key: key, iv: nonce, authenticationHeader: header)
let opened = try AEADChaCha20Poly1305.decrypt(
  sealed.cipherText,
  key: key,
  iv: nonce,
  authenticationHeader: header,
  authenticationTag: sealed.authenticationTag
)
RSA

RSA initialization from parameters

let input: Array<UInt8> = [0,1,2,3,4,5,6,7,8,9]

let n: Array<UInt8> = [] // RSA modulus
let e: Array<UInt8> = [] // RSA public exponent
let d: Array<UInt8> = [] // RSA private exponent

let rsa = RSA(n: n, e: e, d: d)

do {
    let encrypted = try rsa.encrypt(input)
    let decrypted = try rsa.decrypt(encrypted)
} catch {
    print(error)
}

RSA key generation

let rsa = try RSA(keySize: 2048) // This generates a modulus, public exponent and private exponent with the given size

RSA Encryption & Decryption Example

// Alice Generates a Private Key
let alicesPrivateKey = try RSA(keySize: 2048)
    
// Alice shares her **public** key with Bob
let alicesPublicKeyData = try alicesPrivateKey.publicKeyExternalRepresentation()
    
// Bob receives the raw external representation of Alice's public key and imports it
let bobsImportOfAlicesPublicKey = try RSA(rawRepresentation: alicesPublicKeyData)
    
// Bob can now encrypt a message for Alice using her public key
let message = "Hi Alice! This is Bob!"
let privateMessage = try bobsImportOfAlicesPublicKey.encrypt(message.bytes)
    
// This results in some encrypted output like this
// URcRwG6LfH63zOQf2w+HIllPri9Rb6hFlXbi/bh03zPl2MIIiSTjbAPqbVFmoF3RmDzFjIarIS7ZpT57a1F+OFOJjx50WYlng7dioKFS/rsuGHYnMn4csjCRF6TAqvRQcRnBueeINRRA8SLaLHX6sZuQkjIE5AoHJwgavmiv8PY=
      
// Bob can now send this encrypted message to Alice without worrying about people being able to read the original contents
    
// Alice receives the encrypted message and uses her private key to decrypt the data and recover the original message
let originalDecryptedMessage = try alicesPrivateKey.decrypt(privateMessage)
    
print(String(data: Data(originalDecryptedMessage), encoding: .utf8))
// "Hi Alice! This is Bob!"

RSA Signature & Verification Example

// Alice Generates a Private Key
let alicesPrivateKey = try RSA(keySize: 2048)
    
// Alice wants to sign a message that she agrees with
let messageAliceSupports = "Hi my name is Alice!"
let alicesSignature = try alicesPrivateKey.sign(messageAliceSupports.bytes)
    
// Alice shares her Public key and the signature with Bob
let alicesPublicKeyData = try alicesPrivateKey.publicKeyExternalRepresentation()
    
// Bob receives the raw external representation of Alice's public key and imports it!
let bobsImportOfAlicesPublicKey = try RSA(rawRepresentation: alicesPublicKeyData)
        
// Bob can now verify that Alice signed the message using the Private key associated with her shared Public key.
let verifiedSignature = try bobsImportOfAlicesPublicKey.verify(signature: alicesSignature, for: "Hi my name is Alice!".bytes)
    
if verifiedSignature == true {
  // Bob knows that the signature Alice provided is valid for the message and was signed using the Private key associated with Alice's shared Public key.
} else {
  // The signature was invalid, so either
  // - the message Alice signed was different than what we expected.
  // - or Alice used a Private key that isn't associated with the shared Public key that Bob has.
}

These SecKey interoperability examples are available on Apple platforms only.

CryptoSwift RSA Key -> Apple's Security Framework SecKey Example

/// Starting with a CryptoSwift RSA Key
let rsaKey = try RSA(keySize: 2048)

/// Define your Keys attributes
let attributes: [String:Any] = [
  kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
  kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, // or kSecAttrKeyClassPublic
  kSecAttrKeySizeInBits as String: 2048, // The appropriate bits
  kSecAttrIsPermanent as String: false
]
var error:Unmanaged<CFError>? = nil
guard let rsaSecKey = try SecKeyCreateWithData(rsaKey.externalRepresentation() as CFData, attributes as CFDictionary, &error) else {
  /// Error constructing SecKey from raw key data
  return
}

/// You now have an RSA SecKey for use with Apple's Security framework

Apple's Security Framework SecKey -> CryptoSwift RSA Key Example

/// Starting with a SecKey RSA Key
let rsaSecKey:SecKey

/// Copy External Representation
var externalRepError:Unmanaged<CFError>?
guard let cfdata = SecKeyCopyExternalRepresentation(rsaSecKey, &externalRepError) else {
  /// Failed to copy external representation for RSA SecKey
  return
}

/// Instantiate the RSA Key from the raw external representation
let rsaKey = try RSA(rawRepresentation: cfdata as Data)

/// You now have a CryptoSwift RSA Key

Author

CryptoSwift is owned and maintained by Marcin Krzyżanowski

You can follow me on Twitter at @krzyzanowskim for project updates and releases.

Cryptography Notice

This distribution includes cryptographic software. The country in which you currently reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted. See https://www.wassenaar.org/ for more information.

License

Copyright (C) 2014-2025 Marcin Krzyżanowski [email protected] This software is provided 'as-is', without any express or implied warranty.

In no event will the authors be held liable for any damages arising from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:

Changelog

See CHANGELOG file.

CryptoSwift (krzyzanowskim/CryptoSwift)

Searching Database…

这是什么东西?一套用纯 Swift 实现的标准且安全的加密算法集合,规模在持续增长:包括哈希、密码算法、RSA、消息认证码、密钥派生函数,以及针对 String 和 Data 的辅助工具。
这是一个要引入我 Swift 项目的库,还是一个独立的工具?它是一个纯 Swift 源码库,需要添加到你的项目里使用,不能单独运行——主要通过 Swift Package Manager 以源码形式分发。
怎么把它加到项目里?通过 Swift Package Manager 添加包依赖,并把 CryptoSwift 产品添加到你的 target。其他方式:在本地构建 CryptoSwift.xcframework 手动集成到 Xcode,或者直接拖入 xcodeproj 并嵌入框架(最低要求 iOS 11+/macOS 10.13+)。CocoaPods 仍然可用,但对新项目来说已被弃用。
编译它需要哪个版本的 Swift 工具链?当前发布版本需要 Swift 5.6 或更新。如果用的是更老的编译器,就得切换到对应的旧版分支,而这些分支已不再活跃维护。
写新代码时应该避开哪些算法?README 推荐安全的默认选择:新协议优先使用 AEAD 模式(AES-GCM、AES-CCM、ChaCha20-Poly1305),哈希优先用 SHA-256/SHA-512/SHA-3 而不是 MD5 和 SHA-1。MD5、SHA-1、ECB、CBC-MAC 和 PKCS#1 v1.5 被明确标记为遗留互操作性功能;另外每次运算都要用新的 IV 或 nonce,RSA 密钥至少 2048 位。
它能在 Linux 和 Android 上用吗,还是只支持苹果平台?不只支持苹果平台:部署目标包括 iOS 11、macOS 10.13、Mac Catalyst 13、tvOS 11、watchOS 4 和 visionOS 1,而且 Linux 和 Android 都在 CI 中经过测试。
可以在商业应用里使用吗?可以——任何用途包括商业应用都免费,但许可证要求在产品文档中加入致谢声明,修改过的源码也要有清晰的标记。README 里还有一条加密声明:使用前请了解你所在国家关于加密软件的法律规定。
它具体包含哪些算法?哈希摘要(MD5、SHA1、SHA2-224/256/384/512、SHA3)、CRC32/CRC32C/CRC16、密码算法(AES-128/192/256、ChaCha20、XChaCha20、Rabbit、Blowfish)、RSA 加密和签名、消息认证码(Poly1305、HMAC、CMAC、CBC-MAC)、分组密码模式(包括 GCM、CCM 和 OCB)、KDF(PBKDF1/2、HKDF、Scrypt)、填充方案,以及 AEAD ChaCha20-Poly1305。
我需要自己把数据转换成字节数组吗?不需要。字节数组(Array<UInt8>)是内部的基础类型,但 CryptoSwift 提供了便捷扩展,可以直接接受 String 或 Data 并自动转换,还有十六进制编码和 Base64 的辅助工具。
它能处理大文件而不用把所有内容都加载进内存吗?可以——增量更新使用 Cryptor 实例,一次只加密或解密一部分,为大文件节省内存,而且该库提供流式 API。
它支持非对称加密吗?密钥能和苹果的 Security 框架互相转换吗?它支持 RSA 加密、解密和签名,包括密钥生成。SecKey 互操作的示例(在 CryptoSwift RSA 密钥和苹果 SecKey 之间互相转换)只在苹果平台上可用。
Size
16.2 MB
Stars
10.6K
Age
12y
Commits · 90 Days