🔐 secp256k1.swift
Swift library and bindings for ECDSA signatures and secret/public key operations using libsecp256k1.
Objective
This library aims to be a lightweight wrapper for clients to include ECDSA functionality in Swift. The package aims to stay up-to-date and uses a submodule set to the default git branch of secp256k1.
Getting Started
In your Package.swift
:
dependencies: [
.package(
name: "secp256k1",
url: "https://github.com/GigaBitcoin/secp256k1.swift.git",
from: "0.2.0"
),
]
Basic Usage
import secp256k1
let privateKeyBytes = try! "14E4A74438858920D8A35FB2D88677580B6A2EE9BE4E711AE34EC6B396D87B5C".byteArray()
let privatekey = try! secp256k1.Signing.PrivateKey(rawRepresentation: privateKeyBytes)
print(String(byteArray: privatekey.publicKey.rawRepresentation)) // 02734b3511150a60fc8cac329cd5ff804555728740f2f2e98bc4242135ef5d5e4e
Advance Usage
import secp256k1
// Initialize context
let context = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY))!
// Setup private and public key variables
var pubkeyLen = 33
var cPubkey = secp256k1_pubkey()
var pubkey = [UInt8](repeating: 0, count: pubkeyLen)
let privkey = try! "14E4A74438858920D8A35FB2D88677580B6A2EE9BE4E711AE34EC6B396D87B5C".byteArray()
// Verify the context and keys are setup correctly
guard secp256k1_context_randomize(context, privkey) == 1,
secp256k1_ec_pubkey_create(context, &cPubkey, privkey) == 1,
secp256k1_ec_pubkey_serialize(context, &pubkey, &pubkeyLen, &cPubkey, UInt32(SECP256K1_EC_COMPRESSED)) == 1 else {
// Destory context after creation
secp256k1_context_destroy(context)
return
}
print(String(byteArray: pubKey)) // 02734b3511150a60fc8cac329cd5ff804555728740f2f2e98bc4242135ef5d5e4e
// Destory context after creation
secp256k1_context_destroy(context)
Danger
These APIs should not be considered stable and may change at any time. libsecp256k1 is still experimental and has not been formally released.