English | 简体中文
Swift implementation of Bitcoin BIP39 mnemonic generation, validation, entropy conversion, and seed derivation.
- Swift 5.1+
- macOS 10.15+ or iOS 13+
- Swift Package Manager
Add the package to Package.swift:
.package(url: "https://github.com/pengpengliu/BIP39.git", branch: "master")Then add BIP39 to your target dependencies:
.target(
name: "YourTarget",
dependencies: ["BIP39"]
)Generate a mnemonic with secure system randomness:
import BIP39
let mnemonic = try Mnemonic()
print(mnemonic.phrase.joined(separator: " "))Use a specific entropy strength:
let mnemonic = try Mnemonic(strength: 256)Supported strengths are 128, 160, 192, 224, and 256 bits, which produce 12, 15, 18, 21, and 24 words.
Create a mnemonic from an existing phrase and derive the BIP39 seed:
let words = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
.split(separator: " ")
.map(String.init)
let mnemonic = try Mnemonic(phrase: words, passphrase: "TREZOR")
let seed = try mnemonic.seed()Convert between entropy and mnemonic words:
let entropy = [UInt8](repeating: 0, count: 16)
let phrase = try Mnemonic.toMnemonic(entropy)
let restoredEntropy = try Mnemonic.toEntropy(phrase)Validate a phrase:
if Mnemonic.isValid(phrase: words) {
// phrase has a valid word count, words, and checksum
}The package includes English and Chinese wordlists:
let entropy = [UInt8](repeating: 0, count: 16)
let phrase = try Mnemonic.toMnemonic(entropy, wordlist: Wordlists.chinese)
let mnemonic = try Mnemonic(phrase: phrase, passphrase: "", wordlist: Wordlists.chinese)When using a non-English or custom wordlist, pass the same wordlist to every conversion, validation, and initialization API. Custom wordlists must contain exactly 2048 unique words.
Mnemonic uses strict BIP39 validation:
- entropy must be
16,20,24,28, or32bytes - phrase length must be
12,15,18,21, or24words - wordlists must contain exactly 2048 unique words
- seed derivation applies BIP39 NFKD normalization before PBKDF2-HMAC-SHA512
- random mnemonic generation fails if secure system randomness fails
These APIs throw on invalid input or derivation failure:
try Mnemonic(strength:wordlist:)try Mnemonic(phrase:passphrase:wordlist:)try Mnemonic(entropy:wordlist:)try Mnemonic.toMnemonic(_:wordlist:)try Mnemonic.toEntropy(_:wordlist:)try mnemonic.seed()
Run the test suite:
swift testTests cover official BIP39 vectors, entropy boundaries, checksum validation, Unicode normalization, Chinese wordlist round-trips, invalid wordlists, and PBKDF2 input validation.
Code is under the BSD 2-clause "Simplified" License. Documentation is under the Creative Commons Attribution license.