{"id":15032108,"url":"https://github.com/krzyzanowskim/cryptoswift","last_synced_at":"2026-04-09T18:39:21.808Z","repository":{"id":18355612,"uuid":"21535619","full_name":"krzyzanowskim/CryptoSwift","owner":"krzyzanowskim","description":"CryptoSwift is a growing collection of standard and secure cryptographic algorithms implemented in Swift","archived":false,"fork":false,"pushed_at":"2025-02-25T12:43:56.000Z","size":17136,"stargazers_count":10330,"open_issues_count":6,"forks_count":1710,"subscribers_count":184,"default_branch":"main","last_synced_at":"2025-05-11T03:08:14.654Z","etag":null,"topics":["aes","aes-gcm","cipher","commoncrypto","cryptography","cryptoswift","digest","hmac","hmac-authentication","md5","sha1","sha3","swift"],"latest_commit_sha":null,"homepage":"http://cryptoswift.io","language":"Swift","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/krzyzanowskim.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["krzyzanowskim","NathanFallet"]}},"created_at":"2014-07-06T07:31:39.000Z","updated_at":"2025-05-10T12:31:54.000Z","dependencies_parsed_at":"2023-12-14T11:01:43.084Z","dependency_job_id":"31ae2b9c-7331-4e8f-b6cb-d357e3f3f329","html_url":"https://github.com/krzyzanowskim/CryptoSwift","commit_stats":{"total_commits":1389,"total_committers":125,"mean_commits":11.112,"dds":"0.24190064794816413","last_synced_commit":"47ed1f38ab97b3b183bdfb8ce1132aeabd2e10b0"},"previous_names":[],"tags_count":87,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krzyzanowskim%2FCryptoSwift","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krzyzanowskim%2FCryptoSwift/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krzyzanowskim%2FCryptoSwift/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/krzyzanowskim%2FCryptoSwift/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/krzyzanowskim","download_url":"https://codeload.github.com/krzyzanowskim/CryptoSwift/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253509781,"owners_count":21919589,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aes","aes-gcm","cipher","commoncrypto","cryptography","cryptoswift","digest","hmac","hmac-authentication","md5","sha1","sha3","swift"],"created_at":"2024-09-24T20:17:21.354Z","updated_at":"2026-04-09T18:39:21.797Z","avatar_url":"https://github.com/krzyzanowskim.png","language":"Swift","funding_links":["https://github.com/sponsors/krzyzanowskim","https://github.com/sponsors/NathanFallet"],"categories":[],"sub_categories":[],"readme":"[![Platform](https://img.shields.io/badge/Platforms-iOS%20%7C%20Android%20%7C%20macOS%20%7C%20watchOS%20%7C%20tvOS%20%7C%20Linux-4E4E4E.svg?colorA=28a745)](#installation)\n\n[![Swift support](https://img.shields.io/badge/Swift-3.1%20%7C%203.2%20%7C%204.0%20%7C%204.1%20%7C%204.2%20%7C%205.0%20%7C%206.2-lightgrey.svg?colorA=28a745\u0026colorB=4E4E4E)](#swift-versions-support)\n[![Swift Package Manager compatible](https://img.shields.io/badge/SPM-compatible-brightgreen.svg?style=flat\u0026colorA=28a745\u0026\u0026colorB=4E4E4E)](https://github.com/swiftlang/swift-package-manager)\n[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-brightgreen.svg?style=flat\u0026colorA=28a745\u0026\u0026colorB=4E4E4E)](https://github.com/Carthage/Carthage)\n[![CocoaPods Deprecated](https://img.shields.io/cocoapods/v/CryptoSwift.svg?style=flat\u0026label=CocoaPods\u0026colorA=red\u0026\u0026colorB=4E4E4E)](https://cocoapods.org/pods/CryptoSwift)\n\n# CryptoSwift\n\nCrypto related functions and helpers for [Swift](https://swift.org) implemented in Swift. ([#PureSwift](https://twitter.com/hashtag/pureswift))\n\n**Note**: The `main` branch follows the latest currently released **version of Swift**. If you need an earlier version for an older version of Swift, specify its version in your `Podfile` or use the code on the branch for that version. Older branches are unsupported. Check [versions](#swift-versions-support) for details.\n\n---\n\n[Requirements](#requirements) | [Features](#features) | [Contribution](#contribution) | [Installation](#installation) | [Swift versions](#swift-versions-support) | [How-to](#how-to) | [Author](#author) | [License](#license) | [Changelog](#changelog)\n\n### Support \u0026 Sponsors\n\nThe financial sustainability of the project is possible thanks to the ongoing contributions from our [GitHub Sponsors](https://github.com/sponsors/krzyzanowskim)\n\n### Premium Sponsors\n\n  [Emerge Tools](https://www.emergetools.com/) is a suite of revolutionary products designed to supercharge mobile apps and the teams that build them.\n\n  [\u003cimg alt=\"www.emergetools.com/\" width=\"200\" src=\"https://github-production-user-asset-6210df.s3.amazonaws.com/758033/256565082-a21f5ac1-ef39-4b56-a8d2-575adeb7fe55.png\" /\u003e](https://www.emergetools.com)\n\n## Requirements\nGood mood\n\n## Features\n\n- Easy to use\n- Convenient extensions for String and Data\n- Support for incremental updates (stream, ...)\n- iOS, Android, macOS, AppleTV, watchOS, Linux support\n\n#### Hash (Digest)\n  [MD5](https://tools.ietf.org/html/rfc1321)\n| [SHA1](https://tools.ietf.org/html/rfc3174)\n| [SHA2-224](https://tools.ietf.org/html/rfc6234)\n| [SHA2-256](https://tools.ietf.org/html/rfc6234)\n| [SHA2-384](https://tools.ietf.org/html/rfc6234)\n| [SHA2-512](https://tools.ietf.org/html/rfc6234)\n| [SHA3](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf)\n\n#### Cyclic Redundancy Check (CRC)\n  [CRC32](https://en.wikipedia.org/wiki/Cyclic_redundancy_check)\n| [CRC32C](https://en.wikipedia.org/wiki/Cyclic_redundancy_check)\n| [CRC16](https://en.wikipedia.org/wiki/Cyclic_redundancy_check)\n\n#### Cipher\n  [AES-128, AES-192, AES-256](http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf)\n| [ChaCha20](http://cr.yp.to/chacha/chacha-20080128.pdf)\n| [XChaCha20](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha)\n| [Rabbit](https://tools.ietf.org/html/rfc4503)\n| [Blowfish](https://www.schneier.com/academic/blowfish/)\n\n#### RSA (public-key encryption algorithm)\n  [Encryption, Signature](https://github.com/krzyzanowskim/CryptoSwift#rsa)\n\n#### Message authenticators\n  [Poly1305](https://cr.yp.to/mac/poly1305-20050329.pdf)\n| [HMAC (MD5, SHA1, SHA256)](https://www.ietf.org/rfc/rfc2104.txt)\n| [CMAC](https://tools.ietf.org/html/rfc4493)\n| [CBC-MAC](https://en.wikipedia.org/wiki/CBC-MAC)\n\n#### Cipher mode of operation\n- Electronic codebook ([ECB](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_codebook_.28ECB.29))\n- Cipher-block chaining ([CBC](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher-block_chaining_.28CBC.29))\n- Propagating Cipher Block Chaining ([PCBC](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Propagating_Cipher_Block_Chaining_.28PCBC.29))\n- Cipher feedback ([CFB](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_feedback_.28CFB.29))\n- Output Feedback ([OFB](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Output_Feedback_.28OFB.29))\n- Counter Mode ([CTR](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29))\n- Galois/Counter Mode ([GCM](https://csrc.nist.gov/publications/detail/sp/800-38d/final))\n- Counter with Cipher Block Chaining-Message Authentication Code ([CCM](https://csrc.nist.gov/publications/detail/sp/800-38c/final))\n- OCB Authenticated-Encryption Algorithm ([OCB](https://tools.ietf.org/html/rfc7253))\n\n#### Password-Based Key Derivation Function\n- [PBKDF1](https://tools.ietf.org/html/rfc2898#section-5.1) (Password-Based Key Derivation Function 1)\n- [PBKDF2](https://tools.ietf.org/html/rfc2898#section-5.2) (Password-Based Key Derivation Function 2)\n- [HKDF](https://tools.ietf.org/html/rfc5869) (HMAC-based Extract-and-Expand Key Derivation Function)\n- [Scrypt](https://tools.ietf.org/html/rfc7914) (The scrypt Password-Based Key Derivation Function)\n\n#### Data padding\n- [PKCS#5](https://www.rfc-editor.org/rfc/rfc2898.html)\n- [EMSA-PKCS1-v1_5 (Encoding Method for Signature)](https://www.rfc-editor.org/rfc/rfc3447#section-9.2)\n- [EME-PCKS1-v1_5 (Encoding Method for Encryption)](https://www.rfc-editor.org/rfc/rfc3447)\n- [PKCS#7](https://tools.ietf.org/html/rfc5652#section-6.3)\n- [Zero padding](https://en.wikipedia.org/wiki/Padding_(cryptography)#Zero_padding)\n- [ISO78164](https://www.embedx.com/pdfs/ISO_STD_7816/info_isoiec7816-4%7Bed21.0%7Den.pdf)\n- [ISO10126](https://en.wikipedia.org/wiki/Padding_(cryptography)#ISO_10126)\n- No padding\n\n#### Authenticated Encryption with Associated Data (AEAD)\n- [AEAD\\_CHACHA20\\_POLY1305](https://tools.ietf.org/html/rfc7539#section-2.8)\n- [AEAD\\_XCHACHA20\\_POLY1305](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#section-2)\n\n## Why\n[Why?](https://github.com/krzyzanowskim/CryptoSwift/discussions/982) [Because I can](https://github.com/krzyzanowskim/CryptoSwift/discussions/982#discussioncomment-3669415).\n\n## How do I get involved?\n\nYou want to help, great! Go ahead and fork our repo, make your changes and send us a pull request.\n\n## Contribution\n\nCheck out [CONTRIBUTING.md](CONTRIBUTING.md) for more information on how to help with CryptoSwift.\n\n- If you found a bug, [open a discussion](https://github.com/krzyzanowskim/CryptoSwift/discussions).\n- If you have a feature request, [open a discussion](https://github.com/krzyzanowskim/CryptoSwift/discussions).\n\n## Installation\n\n### Hardened Runtime (macOS) and Xcode\n\nBinary CryptoSwift.xcframework (Used by Swift Package Manager package integration) won't load properly in your app if the app uses **Sign to Run Locally**  Signing Certificate with Hardened Runtime enabled. It is possible to setup Xcode like this. To solve the problem you have two options:\n- Use proper Signing Certificate, eg. *Development* \u003c- this is the proper action\n- Use `Disable Library Validation` aka `com.apple.security.cs.disable-library-validation` entitlement\n\n#### Xcode Project\n\nTo install CryptoSwift, add it as a submodule to your project (on the top level project directory):\n\n    git submodule add https://github.com/krzyzanowskim/CryptoSwift.git\n\nIt is recommended to enable [Whole-Module Optimization](https://swift.org/blog/whole-module-optimizations/) to gain better performance. Non-optimized build results in significantly worse performance.\n\n#### Swift Package Manager\n\nYou can use [Swift Package Manager](https://swift.org/package-manager/) and specify dependency in `Package.swift` by adding this:\n\n```swift\n.package(url: \"https://github.com/krzyzanowskim/CryptoSwift.git\", from: \"1.9.0\")\n```\n\nSee: [Package.swift - manual](https://blog.krzyzanowskim.com/2016/08/09/package-swift-manual/)\n\nNotice: Swift Package Manager uses debug configuration for debug Xcode build, that may result in significant (up to x10000) worse performance. Performance characteristic is different in Release build. To overcome this problem, consider embed `CryptoSwift.xcframework` described below.\n\n#### Carthage\n\nYou can use [Carthage](https://github.com/Carthage/Carthage).\nSpecify in Cartfile:\n\n```ruby\ngithub \"krzyzanowskim/CryptoSwift\"\n```\n\nRun `carthage` to build the framework and drag the built CryptoSwift.framework into your Xcode project. Follow [build instructions](https://github.com/Carthage/Carthage#getting-started). [Common issues](https://github.com/krzyzanowskim/CryptoSwift/discussions/983#discussioncomment-3669433).\n\n#### CocoaPods\n\n\u003e **Note**: CocoaPods is deprecated and no longer recommended for new projects. Use Swift Package Manager or Carthage instead.\n\nYou can use [CocoaPods](https://cocoapods.org/pods/CryptoSwift).\n\n```ruby\npod 'CryptoSwift', '~\u003e 1.8.4'\n```\n\nBear in mind that CocoaPods will build CryptoSwift without [Whole-Module Optimization](https://swift.org/blog/whole-module-optimizations/) that may impact performance. You can change it manually after installation, or use [cocoapods-wholemodule](https://github.com/jedlewison/cocoapods-wholemodule) plugin.\n\n#### XCFramework\n\nXCFrameworks require Xcode 11 or later and they can be integrated similarly to how we’re used to integrating the `.framework` format.\nPlease use script [scripts/build-framework.sh](scripts/build-framework.sh) to generate binary `CryptoSwift.xcframework` archive that you can use as a dependency in Xcode.\n\nCryptoSwift.xcframework is a Release (Optimized) binary that offer best available Swift code performance.\n\n\u003cimg width=\"320\" alt=\"Screen Shot 2020-10-27 at 00 06 32\" src=\"https://user-images.githubusercontent.com/758033/97240586-f0878280-17ee-11eb-9119-e5a960417d04.png\"\u003e\n\n#### Embedded Framework\n\nEmbedded frameworks require a minimum deployment target of iOS 11.0 or macOS Sierra (10.13). Drag the `CryptoSwift.xcodeproj` file into your Xcode project, and add appropriate framework as a dependency to your target. Now select your App and choose the General tab for the app target. Find *Embedded Binaries* and press \"+\", then select `CryptoSwift.framework` (iOS, macOS, watchOS or tvOS)\n\n![](https://cloud.githubusercontent.com/assets/758033/10834511/25a26852-7e9a-11e5-8c01-6cc8f1838459.png)\n\nSometimes \"embedded framework\" option is not available. In that case, you have to add new build phase for the target.\n\n![](https://cloud.githubusercontent.com/assets/758033/18415615/d5edabb0-77f8-11e6-8c94-f41d9fc2b8cb.png)\n\n##### iOS, macOS, watchOS, tvOS\n\nIn the project, you'll find [single scheme](https://mxcl.dev/PromiseKit/news/2016/08/Multiplatform-Single-Scheme-Xcode-Projects/) for all platforms:\n- CryptoSwift\n\n#### Swift versions support\n\n- Swift 1.2: branch [swift12](https://github.com/krzyzanowskim/CryptoSwift/tree/swift12) version \u003c= 0.0.13\n- Swift 2.1: branch [swift21](https://github.com/krzyzanowskim/CryptoSwift/tree/swift21) version \u003c= 0.2.3\n- Swift 2.2, 2.3: branch [swift2](https://github.com/krzyzanowskim/CryptoSwift/tree/swift2) version \u003c= 0.5.2\n- Swift 3.1, branch [swift3](https://github.com/krzyzanowskim/CryptoSwift/tree/swift3) version \u003c= 0.6.9\n- Swift 3.2, branch [swift32](https://github.com/krzyzanowskim/CryptoSwift/tree/swift32) version = 0.7.0\n- Swift 4.0, branch [swift4](https://github.com/krzyzanowskim/CryptoSwift/tree/swift4) version \u003c= 0.12.0\n- Swift 4.2, branch [swift42](https://github.com/krzyzanowskim/CryptoSwift/tree/swift42) version \u003c= 0.15.0\n- Swift 5.0, branch [swift5](https://github.com/krzyzanowskim/CryptoSwift/tree/swift5) version \u003c= 1.2.0\n- Swift 5.1, branch [swift51](https://github.com/krzyzanowskim/CryptoSwift/tree/swift51) version \u003c= 1.3.3\n- Swift 5.3, branch [swift53](https://github.com/krzyzanowskim/CryptoSwift/tree/swift53) version \u003c= 1.8.5\n- Swift 6.2 and newer, branch [main](https://github.com/krzyzanowskim/CryptoSwift/tree/main)\n\n## How-to\n\n* [Basics (data types, conversion, ...)](#basics)\n* [Digest (MD5, SHA...)](#calculate-digest)\n* [Message authenticators (HMAC, CMAC...)](#message-authenticators-1)\n* [Password-Based Key Derivation Function (PBKDF2, ...)](#password-based-key-derivation-functions)\n* [HMAC-based Key Derivation Function (HKDF)](#hmac-based-key-derivation-function)\n* [Data Padding](#data-padding)\n* [ChaCha20](#chacha20)\n* [Rabbit](#rabbit)\n* [Blowfish](#blowfish)\n* [AES - Advanced Encryption Standard](#aes)\n* [AES-GCM](#aes-gcm)\n* [Authenticated Encryption with Associated Data (AEAD)](#aead)\n\n##### Basics\n\n```swift\nimport CryptoSwift\n```\n\nCryptoSwift uses array of bytes aka `Array\u003cUInt8\u003e` 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.\n\n##### Data types conversion\n\nFor your convenience, **CryptoSwift** provides two functions to easily convert an array of bytes to `Data` or `Data` to an array of bytes:\n\nData from bytes:\n\n```swift\nlet data = Data([0x01, 0x02, 0x03])\n```\n\n`Data` to `Array\u003cUInt8\u003e`\n\n```swift\nlet bytes = data.byteArray                // [1,2,3]\n```\n\n[Hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) encoding:\n\n```swift\nlet bytes = Array\u003cUInt8\u003e(hex: \"0x010203\")  // [1,2,3]\nlet hex   = bytes.toHexString()            // \"010203\"\n```\n\nBuild bytes out of `String`\n```swift\nlet bytes: Array\u003cUInt8\u003e = \"cipherkey\".bytes  // Array(\"cipherkey\".utf8)\n```\n\nAlso... check out helpers that work with **Base64** encoded data:\n```swift\n\"aPf/i9th9iX+vf49eR7PYk2q7S5xmm3jkRLejgzHNJs=\".decryptBase64ToString(cipher)\n\"aPf/i9th9iX+vf49eR7PYk2q7S5xmm3jkRLejgzHNJs=\".decryptBase64(cipher)\nbytes.toBase64()\n```\n\n##### Calculate Digest\n\nHashing a data or array of bytes (aka `Array\u003cUInt8\u003e`)\n```swift\n/* Hash struct usage */\nlet bytes: Array\u003cUInt8\u003e = [0x01, 0x02, 0x03]\nlet digest = input.md5()\nlet digest = Digest.md5(bytes)\n```\n\n```swift\nlet data = Data([0x01, 0x02, 0x03])\n\nlet hash = data.md5()\nlet hash = data.sha1()\nlet hash = data.sha224()\nlet hash = data.sha256()\nlet hash = data.sha384()\nlet hash = data.sha512()\n```\n```swift\ndo {\n    var digest = MD5()\n    let partial1 = try digest.update(withBytes: [0x31, 0x32])\n    let partial2 = try digest.update(withBytes: [0x33])\n    let result = try digest.finish()\n} catch { }\n```\n\nHashing a String and printing result\n\n```swift\nlet hash = \"123\".md5() // \"123\".bytes.md5()\n```\n\n##### Calculate CRC\n\n```swift\nbytes.crc16()\ndata.crc16()\n\nbytes.crc32()\ndata.crc32()\n```\n\n##### Message authenticators\n\n```swift\n// Calculate Message Authentication Code (MAC) for message\nlet key: Array\u003cUInt8\u003e = [1,2,3,4,5,6,7,8,9,10,...]\n\ntry Poly1305(key: key).authenticate(bytes)\ntry HMAC(key: key, variant: .sha256).authenticate(bytes)\ntry CMAC(key: key).authenticate(bytes)\n```\n\n##### Password-Based Key Derivation Functions\n\n```swift\nlet password: Array\u003cUInt8\u003e = Array(\"s33krit\".utf8)\nlet salt: Array\u003cUInt8\u003e = Array(\"nacllcan\".utf8)\n\nlet key = try PKCS5.PBKDF2(password: password, salt: salt, iterations: 4096, keyLength: 32, variant: .sha2(.sha256)).calculate()\n```\n\n```swift\nlet password: Array\u003cUInt8\u003e = Array(\"s33krit\".utf8)\nlet salt: Array\u003cUInt8\u003e = Array(\"nacllcan\".utf8)\n// Scrypt implementation does not implement work parallelization, so `p` parameter will\n// increase the work time even in multicore systems\nlet key = try Scrypt(password: password, salt: salt, dkLen: 64, N: 16384, r: 8, p: 1).calculate()\n```\n\n##### HMAC-based Key Derivation Function\n\n```swift\nlet password: Array\u003cUInt8\u003e = Array(\"s33krit\".utf8)\nlet salt: Array\u003cUInt8\u003e = Array(\"nacllcan\".utf8)\n\nlet key = try HKDF(password: password, salt: salt, variant: .sha256).calculate()\n```\n\n\n##### Data Padding\n\nSome 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.\n\n```swift\nPadding.pkcs7.add(to: bytes, blockSize: AES.blockSize)\n```\n\n#### Working with Ciphers\n##### ChaCha20\n\n```swift\nlet encrypted = try ChaCha20(key: key, iv: iv).encrypt(message)\nlet decrypted = try ChaCha20(key: key, iv: iv).decrypt(encrypted)\n```\n\n##### Rabbit\n\n```swift\nlet encrypted = try Rabbit(key: key, iv: iv).encrypt(message)\nlet decrypted = try Rabbit(key: key, iv: iv).decrypt(encrypted)\n```\n##### Blowfish\n\n```swift\nlet encrypted = try Blowfish(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).encrypt(message)\nlet decrypted = try Blowfish(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).decrypt(encrypted)\n```\n\n##### AES\n\nNotice regarding padding: *Manual padding of data is optional, and CryptoSwift is using PKCS7 padding by default. If you need to manually disable/enable padding, you can do this by setting parameter for __AES__ class*\n\nVariant of AES encryption (AES-128, AES-192, AES-256) depends on given key length:\n\n- AES-128 = 16 bytes\n- AES-192 = 24 bytes\n- AES-256 = 32 bytes\n\nAES-256 example\n\n```swift\nlet encryptedBytes = try AES(key: [1,2,3,...,32], blockMode: CBC(iv: [1,2,3,...,16]), padding: .pkcs7)\n```\n\nFull example:\n\n```swift\nlet password: [UInt8] = Array(\"s33krit\".utf8)\nlet salt: [UInt8] = Array(\"nacllcan\".utf8)\n\n/* Generate a key from a `password`. Optional if you already have a key */\nlet key = try PKCS5.PBKDF2(\n    password: password,\n    salt: salt,\n    iterations: 4096,\n    keyLength: 32, /* AES-256 */\n    variant: .sha256\n).calculate()\n\n/* Generate random IV value. IV is public value. Either need to generate, or get it from elsewhere */\nlet iv = AES.randomIV(AES.blockSize)\n\n/* AES cryptor instance */\nlet aes = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7)\n\n/* Encrypt Data */\nlet inputData = Data()\nlet encryptedBytes = try aes.encrypt(inputData.byteArray)\nlet encryptedData = Data(encryptedBytes)\n\n/* Decrypt Data */\nlet decryptedBytes = try aes.decrypt(encryptedData.byteArray)\nlet decryptedData = Data(decryptedBytes)\n```\n\n###### All at once\n```swift\ndo {\n    let aes = try AES(key: \"keykeykeykeykeyk\", iv: \"drowssapdrowssap\") // aes128\n    let ciphertext = try aes.encrypt(Array(\"Nullam quis risus eget urna mollis ornare vel eu leo.\".utf8))\n} catch { }\n```\n\n###### Incremental updates\n\nIncremental operations use instance of Cryptor and encrypt/decrypt one part at a time, this way you can save on memory for large files.\n\n```swift\ndo {\n    var encryptor = try AES(key: \"keykeykeykeykeyk\", iv: \"drowssapdrowssap\").makeEncryptor()\n\n    var ciphertext = Array\u003cUInt8\u003e()\n    // aggregate partial results\n    ciphertext += try encryptor.update(withBytes: Array(\"Nullam quis risus \".utf8))\n    ciphertext += try encryptor.update(withBytes: Array(\"eget urna mollis \".utf8))\n    ciphertext += try encryptor.update(withBytes: Array(\"ornare vel eu leo.\".utf8))\n    // finish at the end\n    ciphertext += try encryptor.finish()\n\n    print(ciphertext.toHexString())\n} catch {\n    print(error)\n}\n```\n\n###### AES Advanced usage\n```swift\nlet input: Array\u003cUInt8\u003e = [0,1,2,3,4,5,6,7,8,9]\n\nlet key: Array\u003cUInt8\u003e = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]\nlet iv: Array\u003cUInt8\u003e = // Random bytes of `AES.blockSize` length\n\ndo {\n    let encrypted = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).encrypt(input)\n    let decrypted = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).decrypt(encrypted)\n} catch {\n    print(error)\n}\n```\n\nAES without data padding\n\n```swift\nlet input: Array\u003cUInt8\u003e = [0,1,2,3,4,5,6,7,8,9]\nlet encrypted: Array\u003cUInt8\u003e = try! AES(key: Array(\"secret0key000000\".utf8), blockMode: CBC(iv: Array(\"0123456789012345\".utf8)), padding: .noPadding).encrypt(input)\n```\n\nUsing convenience extensions\n\n```swift\nlet plain = Data([0x01, 0x02, 0x03])\nlet encrypted = try! plain.encrypt(ChaCha20(key: key, iv: iv))\nlet decrypted = try! encrypted.decrypt(ChaCha20(key: key, iv: iv))\n```\n\n##### AES-GCM\n\nThe result of Galois/Counter Mode (GCM) encryption is ciphertext and **authentication tag**, that is later used to decryption.\n\nencryption\n\n```swift\ndo {\n    // In combined mode, the authentication tag is directly appended to the encrypted message. This is usually what you want.\n    let gcm = GCM(iv: iv, mode: .combined)\n    let aes = try AES(key: key, blockMode: gcm, padding: .noPadding)\n    let encrypted = try aes.encrypt(plaintext)\n    let tag = gcm.authenticationTag\n} catch {\n    // failed\n}\n```\n\ndecryption\n\n```swift\ndo {\n    // In combined mode, the authentication tag is appended to the encrypted message. This is usually what you want.\n    let gcm = GCM(iv: iv, mode: .combined)\n    let aes = try AES(key: key, blockMode: gcm, padding: .noPadding)\n    return try aes.decrypt(encrypted)\n} catch {\n    // failed\n}\n```\n\n**Note**: GCM instance is not intended to be reused. So you can't use the same `GCM` instance from encoding to also perform decoding.\n\n##### AES-CCM\n\nThe result of Counter with Cipher Block Chaining-Message Authentication Code encryption is ciphertext and **authentication tag**, that is later used to decryption.\n\n```swift\ndo {\n    // The authentication tag is appended to the encrypted message.\n\tlet tagLength = 8\n\tlet ccm = CCM(iv: iv, tagLength: tagLength, messageLength: ciphertext.count - tagLength, additionalAuthenticatedData: data)\n    let aes = try AES(key: key, blockMode: ccm, padding: .noPadding)\n    return try aes.decrypt(encrypted)\n} catch {\n    // failed\n}\n```\n\nCheck documentation or CCM specification for valid parameters for CCM.\n\n##### AEAD\n\n```swift\nlet encrypt = try AEADChaCha20Poly1305.encrypt(plaintext, key: key, iv: nonce, authenticationHeader: header)\nlet decrypt = try AEADChaCha20Poly1305.decrypt(ciphertext, key: key, iv: nonce, authenticationHeader: header, authenticationTag: tagArr: tag)\n```\n\n##### RSA\n\nRSA initialization from parameters\n\n```swift\nlet input: Array\u003cUInt8\u003e = [0,1,2,3,4,5,6,7,8,9]\n\nlet n: Array\u003cUInt8\u003e = // RSA modulus\nlet e: Array\u003cUInt8\u003e = // RSA public exponent\nlet d: Array\u003cUInt8\u003e = // RSA private exponent\n\nlet rsa = RSA(n: n, e: e, d: d)\n\ndo {\n    let encrypted = try rsa.encrypt(input)\n    let decrypted = try rsa.decrypt(encrypted)\n} catch {\n    print(error)\n}\n```\n\nRSA key generation\n\n```swift\nlet rsa = try RSA(keySize: 2048) // This generates a modulus, public exponent and private exponent with the given size\n```\n\nRSA Encryption \u0026 Decryption Example\n``` swift\n// Alice Generates a Private Key\nlet alicesPrivateKey = try RSA(keySize: 1024)\n    \n// Alice shares her **public** key with Bob\nlet alicesPublicKeyData = try alicesPrivateKey.publicKeyExternalRepresentation()\n    \n// Bob receives the raw external representation of Alices public key and imports it\nlet bobsImportOfAlicesPublicKey = try RSA(rawRepresentation: alicesPublicKeyData)\n    \n// Bob can now encrypt a message for Alice using her public key\nlet message = \"Hi Alice! This is Bob!\"\nlet privateMessage = try bobsImportOfAlicesPublicKey.encrypt(message.bytes)\n    \n// This results in some encrypted output like this\n// URcRwG6LfH63zOQf2w+HIllPri9Rb6hFlXbi/bh03zPl2MIIiSTjbAPqbVFmoF3RmDzFjIarIS7ZpT57a1F+OFOJjx50WYlng7dioKFS/rsuGHYnMn4csjCRF6TAqvRQcRnBueeINRRA8SLaLHX6sZuQkjIE5AoHJwgavmiv8PY=\n      \n// Bob can now send this encrypted message to Alice without worrying about people being able to read the original contents\n    \n// Alice receives the encrypted message and uses her private key to decrypt the data and recover the original message\nlet originalDecryptedMessage = try alicesPrivateKey.decrypt(privateMessage)\n    \nprint(String(data: Data(originalDecryptedMessage), encoding: .utf8))\n// \"Hi Alice! This is Bob!\"\n```\n\nRSA Signature \u0026 Verification Example\n``` swift\n// Alice Generates a Private Key\nlet alicesPrivateKey = try RSA(keySize: 1024)\n    \n// Alice wants to sign a message that she agrees with\nlet messageAliceSupports = \"Hi my name is Alice!\"\nlet alicesSignature = try alicesPrivateKey.sign(messageAliceSupports.bytes)\n    \n// Alice shares her Public key and the signature with Bob\nlet alicesPublicKeyData = try alicesPrivateKey.publicKeyExternalRepresentation()\n    \n// Bob receives the raw external representation of Alices Public key and imports it!\nlet bobsImportOfAlicesPublicKey = try RSA(rawRepresentation: alicesPublicKeyData)\n        \n// Bob can now verify that Alice signed the message using the Private key associated with her shared Public key.\nlet verifiedSignature = try bobsImportOfAlicesPublicKey.verify(signature: alicesSignature, for: \"Hi my name is Alice!\".bytes)\n    \nif verifiedSignature == true {\n  // Bob knows that the signature Alice provided is valid for the message and was signed using the Private key associated with Alices shared Public key.\n} else {\n  // The signature was invalid, so either\n  // - the message Alice signed was different then what we expected.\n  // - or Alice used a Private key that isn't associated with the shared Public key that Bob has.\n}\n```\n\nCryptoSwift RSA Key -\u003e Apple's Security Framework SecKey Example\n``` swift\n/// Starting with a CryptoSwift RSA Key\nlet rsaKey = try RSA(keySize: 1024)\n\n/// Define your Keys attributes\nlet attributes: [String:Any] = [\n  kSecAttrKeyType as String: kSecAttrKeyTypeRSA,\n  kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, // or kSecAttrKeyClassPublic\n  kSecAttrKeySizeInBits as String: 1024, // The appropriate bits\n  kSecAttrIsPermanent as String: false\n]\nvar error:Unmanaged\u003cCFError\u003e? = nil\nguard let rsaSecKey = try SecKeyCreateWithData(rsaKey.externalRepresentation() as CFData, attributes as CFDictionary, \u0026error) else {\n  /// Error constructing SecKey from raw key data\n  return\n}\n\n/// You now have an RSA SecKey for use with Apple's Security framework\n```\n\nApple's Security Framework SecKey -\u003e CryptoSwift RSA Key Example\n``` swift\n/// Starting with a SecKey RSA Key\nlet rsaSecKey:SecKey\n\n/// Copy External Representation\nvar externalRepError:Unmanaged\u003cCFError\u003e?\nguard let cfdata = SecKeyCopyExternalRepresentation(rsaSecKey, \u0026externalRepError) else {\n  /// Failed to copy external representation for RSA SecKey\n  return\n}\n\n/// Instantiate the RSA Key from the raw external representation\nlet rsaKey = try RSA(rawRepresentation: cfdata as Data)\n\n/// You now have a CryptoSwift RSA Key\n```\n\n\n## Author\n\nCryptoSwift is owned and maintained by [Marcin Krzyżanowski](https://www.krzyzanowskim.com)\n\nYou can follow me on Twitter at [@krzyzanowskim](https://x.com/krzyzanowskim) for project updates and releases.\n\n# Cryptography Notice\n\nThis 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.\n\n## License\n\nCopyright (C) 2014-2025 Marcin Krzyżanowski \u003cmarcin@krzyzanowskim.com\u003e\nThis software is provided 'as-is', without any express or implied warranty.\n\nIn no event will the authors be held liable for any damages arising from the use of this software.\n\nPermission 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:\n\n- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, **an acknowledgment in the product documentation is required**.\n- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.\n- This notice may not be removed or altered from any source or binary distribution.\n- Redistributions of any form whatsoever must retain the following acknowledgment: 'This product includes software developed by the \"Marcin Krzyzanowski\" (https://krzyzanowskim.com/).'\n\n## Changelog\n\nSee [CHANGELOG](./CHANGELOG) file.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkrzyzanowskim%2Fcryptoswift","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkrzyzanowskim%2Fcryptoswift","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkrzyzanowskim%2Fcryptoswift/lists"}