Skip to content

Instantly share code, notes, and snippets.

@thomsmed
Created January 19, 2024 22:10
Show Gist options
  • Save thomsmed/571d6d593ed7d739d4fac8f527bf9ca3 to your computer and use it in GitHub Desktop.
Save thomsmed/571d6d593ed7d739d4fac8f527bf9ca3 to your computer and use it in GitHub Desktop.
Quick and dirty generate, export and import EC256 Key Pair (SecKey -> base64 -> SecKey).
//
// Quickly and dirty generatte EC256 Key Pair, export as base64 Data/String, and then import from base64 Data/String.
// Perfect when you need an in-memory key pair for mocks/unit testing.
//
import CryptoKit
// Generate EC256 Key Pair and export as base64 String/Data
let attributes = [
kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
kSecAttrKeySizeInBits as String: 256,
kSecAttrCanSign as String: true
] as [String: Any]
let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, nil)!
let publicKey = SecKeyCopyPublicKey(privateKey)!
let privateKeyData = SecKeyCopyExternalRepresentation(privateKey, nil)! as Data
print("Private Key Data (base64):", privateKeyData.base64EncodedString())
let publicKeyData = SecKeyCopyExternalRepresentation(publicKey, nil)! as Data
print("Public Key Data (base64):", publicKeyData.base64EncodedString())
// Import Private Key
let importedPrivateKeyData = Data(base64Encoded: privateKeyData.base64EncodedString())! as CFData
let importedPrivateKeyAttributes = [
kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
kSecAttrKeyClass as String: kSecAttrKeyClassPublic
] as CFDictionary
let importedPrivateKey = SecKeyCreateWithData(importedPrivateKeyData, importedPrivateKeyAttributes, nil)!
// Import Public Key
let importedPublicKeyData = Data(base64Encoded: publicKeyData.base64EncodedString())! as CFData
let importedPublicKeyAttributes = [
kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
kSecAttrKeyClass as String: kSecAttrKeyClassPublic
] as CFDictionary
let importedPublicKey = SecKeyCreateWithData(importedPublicKeyData, importedPublicKeyAttributes, nil)!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment