Communityコーディング&開発github.com

dpearson2699/cryptokit

Apple CryptoKit を使用して Swift 暗号プリミティブを利用します。SHA-2 や SHA-3 によるハッシュ化、HMAC の生成、AES-GCM や ChaChaPoly による暗号化、P256/P384/P521/Curve25519 や ML-DSA 鍵による署名、ECDH、HPKE、ML-KEM、X-Wing 鍵交換、Secure Enclave CryptoKit 鍵の利用、または CommonCrypto コードの CryptoKit への移行時に使用します。

cryptokit とは?

このスキルは、Apple プラットフォーム向けに Swift で暗号操作を行うための CryptoKit フレームワークの公式ガイドです。開発者は SHA-2 や SHA-3 によるハッシュ、HMAC 認証、AES-GCM や ChaChaPoly による対称暗号化、P-256/P-384/P-521 および Curve25519 (EdDSA) を用いた非対称署名、そして ECDH や HPKE、ML-KEM、X-Wing などの高度な鍵交換プロトコルを実装できます。また、ML-DSA ポスト量子署名や Secure Enclave のハードウェア鍵の管理にも対応しており、CommonCrypto からの移行も容易です。macOS (Mac Catalyst 含む)、iOS、iPadOS、watchOS、tvOS、visionOS をサポートし、各 OS バージョンに応じた CryptoKit の機能差にも言及しています。実装例やベストプラクティスが豊富に含まれており、安全かつ効率的な暗号コードの作成を支援します。

対応~Claude Code~Codex CLI~Cursor
Part ofMobile
npx skills add https://github.com/dpearson2699/swift-ios-skills/tree/main/skills/cryptokit

Installed? Explore more コーディング&開発 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

cryptokit は何をしますか?

Apple CryptoKit を使用して Swift 暗号プリミティブを利用します。SHA-2 や SHA-3 によるハッシュ化、HMAC の生成、AES-GCM や ChaChaPoly による暗号化、P256/P384/P521/Curve25519 や ML-DSA 鍵による署名、ECDH、HPKE、ML-KEM、X-Wing 鍵交換、Secure Enclave CryptoKit 鍵の利用、または CommonCrypto コードの CryptoKit への移行時に使用します。


サポートプラットフォーム

  • macOS 10.15+ (Catalyst および arm64 を含む)
  • iOS 13.0+
  • iPadOS 13.0+
  • watchOS 6.0+
  • tvOS 13.0+
  • visionOS 1.0+

暗号ハッシュ

SHA256, SHA384, SHA512 (SHA-2) および SHA3_256, SHA3_384, SHA3_512 (SHA-3) をサポート。

import CryptoKit

let data = Data("hello".utf8)

// SHA-2
let sha2Digest = SHA256.hash(data: data)
print(sha2Digest.hexString) // hexString は `CryptoKit` 拡張プロパティ

// SHA-3 (macOS 10.15+, iOS 13.0+)
let sha3Digest = SHA3_512.hash(data: data)

CryptoKit 拡張機能として hexString プロパティを追加:

extension Digest {
    var hexString: String {
        self.map { String(format: "%02x", $0) }.joined()
    }
}

メッセージ認証コード (HMAC)

let key = SymmetricKey(size: .bits256)
let authenticationCode = HMAC<SHA256>.authenticationCode(for: data, using: key)
let isValid = HMAC<SHA256>.isValidAuthenticationCode(authenticationCode, authenticating: data, using: key)

対称暗号化

AES-GCM (認証付き暗号化)

let key = SymmetricKey(size: .bits256)
let sealedBox = try! AES.GCM.seal(data, using: key)
let decryptedData = try! AES.GCM.open(sealedBox)

暗号文 (sealedBox.ciphertext) と認証タグ (sealedBox.tag) に加え、nonce も利用可能:

let nonce = try! AES.GCM.Nonce(data: nonceData) // 12 バイト
let sealedBox = try! AES.GCM.seal(data, using: key, nonce: nonce, authenticating: additionalData)

ChaChaPoly (認証付き暗号化)

let key = SymmetricKey(size: .bits256)
let sealedBox = try! ChaChaPoly.seal(data, using: key)
let decryptedData = try! ChaChaPoly.open(sealedBox)

ChaChaPoly は nonce と追加データもオプションでサポート:

let nonce = ChaChaPoly.Nonce()
let sealedBox = try! ChaChaPoly.seal(data, using: key, nonce: nonce, authenticating: additionalData)

HKDF による鍵導出

let derivedKey = HKDF<SHA256>.deriveKey(inputKeyMaterial: symmetricKey, salt: saltData, info: infoData, outputByteCount: 32)

公開鍵暗号

鍵の生成

// NIST P-256 / P-384 / P-521
let p256PrivateKey = P256.KeyAgreement.PrivateKey()
let p256PublicKey = p256PrivateKey.publicKey

// Curve25519 (X25519 鍵共有, Ed25519 署名)
let curve25519PrivateKey = Curve25519.KeyAgreement.PrivateKey()
let curve25519PublicKey = curve25519PrivateKey.publicKey

// ポスト量子 ML-DSA (macOS 15+, iOS 18+)
let mlDsaPrivateKey = MLDSA.PrivateKey()
let mlDsaPublicKey = mlDsaPrivateKey.publicKey

// Secure Enclave 鍵 (Secure Enclave 搭載デバイスのみ)
let accessControl = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .privateKeyUsage, nil)!
let sePrivateKey = try! SecureEnclave.P256.KeyAgreement.PrivateKey(accessControl: accessControl)
let sePublicKey = sePrivateKey.publicKey

デジタル署名

// ECDSA (P-256)
let signingKey = P256.Signing.PrivateKey()
let signature = try! signingKey.signature(for: data)
let isValid = signingKey.publicKey.isValidSignature(signature, for: data)

// EdDSA (Curve25519)
let edPrivateKey = Curve25519.Signing.PrivateKey()
let edSignature = try! edPrivateKey.signature(for: data)
let edIsValid = edPrivateKey.publicKey.isValidSignature(edSignature, for: data)

// ML-DSA (ポスト量子)
let mlDsaSigningKey = MLDSA.PrivateKey()
let mlDsaSignature = try! mlDsaSigningKey.signature(for: data)
let mlDsaValid = mlDsaSigningKey.publicKey.isValidSignature(mlDsaSignature, for: data)

鍵共有

// ECDH (P-256)
let alicePrivate = P256.KeyAgreement.PrivateKey()
let bobPrivate = P256.KeyAgreement.PrivateKey()
let sharedSecret = try! alicePrivate.sharedSecretFromKeyAgreement(with: bobPrivate.publicKey)

// X25519 (Curve25519)
let aliceXPrivate = Curve25519.KeyAgreement.PrivateKey()
let bobXPrivate = Curve25519.KeyAgreement.PrivateKey()
let xSharedSecret = try! aliceXPrivate.sharedSecretFromKeyAgreement(with: bobXPrivate.publicKey)

// HPKE (Hybrid Public Key Encryption)
let hpkeSender = try! HPKE.Sender(recipient: bobPublicKey, ciphersuite: .P256_HKDF_SHA256_AES_GCM)
let hpkeCiphertext = try! hpkeSender.seal(data, using: symmetricKey)
let hpkeReceiver = try! HPKE.Recipient(privateKey: bobPrivate, ciphersuite: .P256_HKDF_SHA256_AES_GCM, enc: hpkeSender.enc)
let hpkeDecrypted = try! hpkeReceiver.open(hpkeCiphertext, using: symmetricKey)

// ML-KEM (ポスト量子鍵カプセル化, macOS 15+, iOS 18+)
let mlKemPrivateKey = MLKEM512.PrivateKey()
let mlKemPublicKey = mlKemPrivateKey.publicKey
let (mlKemCiphertext, mlKemSharedSecret) = try! MLKEM512.encapsulate(publicKey: mlKemPublicKey)
let mlKemDecapsulated = try! mlKemPrivateKey.decapsulate(ciphertext: mlKemCiphertext)

// X-Wing (ハイブリッド鍵カプセル化: ML-KEM768 + X25519)
let xwingPrivateKey = XWing.PrivateKey()
let xwingPublicKey = xwingPrivateKey.publicKey
let (xwingCiphertext, xwingSharedSecret) = try! XWing.encapsulate(publicKey: xwingPublicKey)
let xwingDecapsulated = try! xwingPrivateKey.decapsulate(ciphertext: xwingCiphertext)

SafeMath (サイドチャネル攻撃対策)

import CryptoKitSafeMath // CryptoKit 内部の一部

let equal = safeCompare(data1, data2) // タイミング攻撃に耐性のある比較

CommonCrypto からの移行

// 以前 (CommonCrypto):
// CC_MD5(data, length, digest) // 非推奨

// 現在 (CryptoKit):
import CryptoKit
let digest = Insecure.MD5.hash(data: data) // レガシーコード移行のみ

// 以前: CCCrypt(kCCEncrypt, kCCAlgorithmAES, ...)
// 現在:
let key = SymmetricKey(size: .bits256)
let sealedBox = try! AES.GCM.seal(data, using: key)

ベストプラクティス

  1. 鍵管理: 鍵は Keychain に保存するか、Secure Enclave を利用してください。平文の鍵をソースコードに埋め込まないでください。
  2. エラー処理: 暗号操作は失敗する可能性があります (CryptoKitError をキャッチしてください)。
  3. nonce の一意性: AES-GCM と ChaChaPoly では、同じ鍵で nonce を再利用しないでください(ランダム nonce 生成を使用するか、シーケンシャルな nonce を安全に管理してください)。
  4. ハッシュの使用方法: SHA-2 はほとんどの用途に推奨されます。SHA-3 は将来性を考慮した選択肢であり、SHA-1 や MD5 はレガシーコードの相互運用性にのみ使用してください。
  5. ポスト量子暗号: ML-DSA(署名)と ML-KEM または X-Wing(鍵共有)は、量子コンピュータに対する耐性が必要な新規プロジェクトに推奨されます。利用可能性は OS バージョンに依存します(macOS 15+、iOS 18+)。

エラー処理の例

do {
    let sealedBox = try AES.GCM.seal(plaintext, using: key)
} catch CryptoKitError.authenticationFailure {
    print("認証失敗")
} catch CryptoKitError.incorrectParameterSize {
    print("パラメータサイズが不正")
} catch {
    print("その他のエラー: \(error)")
}

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

dpearson2699/accessorysetupkit

Discover and configure Bluetooth and Wi-Fi accessories using AccessorySetupKit. Use when presenting a privacy-preserving accessory picker, defining discovery descriptors for BLE or Wi-Fi devices, handling accessory session events, migrating from CoreBluetooth permission-based scanning, or setting up accessories without requiring broad Bluetooth permissions.

dpearson2699/activitykit

Implement, review, or improve Live Activities and Dynamic Island experiences in iOS apps using ActivityKit. Use when building real-time updating widgets for the Lock Screen and Dynamic Island — delivery tracking, sports scores, ride-sharing status, workout timers, media playback, or any time-sensitive information that updates in real time. Also use when working with ActivityKit, ActivityAttributes, Activity lifecycle (request/update/end), Dynamic Island layouts (compact/minimal/expanded), push-to-update Live Activities, or Lock Screen live widgets.

dpearson2699/adattributionkit

Measure ad effectiveness with privacy-preserving attribution using AdAttributionKit. Use when registering ad impressions, handling attribution postbacks, updating conversion values, implementing re-engagement attribution, configuring publisher or advertiser apps, or replacing SKAdNetwork with AdAttributionKit for ad measurement.

dpearson2699/alarmkit

Implement AlarmKit alarms and countdown timers for iOS and iPadOS with Lock Screen, Dynamic Island, and Apple Watch system UI. Covers AlarmManager scheduling, AlarmAttributes and AlarmPresentation, AlarmButton stop and snooze actions, authorization, state observation, and Live Activity integration. Use when building wake-up alarms, countdown timers, or alarm-style alerts that need Apple's system alarm experience.

dpearson2699/app-clips

Build iOS App Clips with invocation URLs, App Clip Codes, NFC, QR codes, Safari banners, Maps, Messages, target setup, App Store Connect experiences, size/capability constraints, NSUserActivity routing, SKOverlay promotion, App Group/keychain handoff, ephemeral notifications, location confirmation, and full-app migration. Use when creating App Clips or wiring App Clip invocation, experience configuration, or full-app handoff.

dpearson2699/app-intents

Implement App Intents for Siri, Shortcuts, Spotlight, widgets, Control Center, and Apple Intelligence on iOS. Covers AppIntent actions, AppEntity and EntityQuery models, AppShortcutsProvider phrases, IndexedEntity Spotlight indexing, WidgetConfigurationIntent, SnippetIntent, and assistant schemas. Use when exposing app actions or entities to system surfaces.

dpearson2699/apple-on-device-ai

Integrate on-device AI using Foundation Models framework, Core ML, and open-source LLM runtimes on Apple Silicon. Covers Foundation Models (LanguageModelSession, @Generable, @Guide, SystemLanguageModel, structured output, tool calling), Core ML (coremltools, model conversion, quantization, palettization, pruning, Neural Engine, MLTensor), MLX Swift (transformer inference, unified memory), and llama.cpp (GGUF, cross-platform LLM). Use when building tool-calling AI features, working with guided generation schemas, converting models, or running on-device inference.

dpearson2699/appmigrationkit

Transfer app data to or from other platforms using AppMigrationKit. Use when implementing system-orchestrated one-time migration between iOS and Android or another platform, building an AppMigrationExtension, packaging transportable resources with ResourcesArchiver, importing resources on the destination device, reporting import progress, handling migration errors and app group cleanup, checking MigrationStatus, or testing migration code with AppMigrationTester.

dpearson2699/app-store-review

Prepare for App Store review and prevent rejections. Covers App Store review guidelines, app rejection reasons, PrivacyInfo.xcprivacy privacy manifest requirements, required API reason codes, in-app purchase IAP and StoreKit rules, App Store Guidelines compliance, ATT App Tracking Transparency, EU DMA Digital Markets Act, HIG compliance checklist, app submission preparation, review preparation, metadata requirements, entitlements, widgets, and Live Activities review rules. Use when preparing for App Store submission, fixing rejection reasons, auditing privacy manifests, implementing ATT consent flow, configuring StoreKit IAP, or checking HIG compliance.

dpearson2699/audioaccessorykit

Support audio accessory features like automatic switching using AudioAccessoryKit. Use when implementing automatic audio routing for paired accessories, registering audio accessory configuration from the container app, updating placement or connected audio source identifiers from an app extension, or handling AccessoryControlDevice capabilities and errors.

dpearson2699/authentication

Implement iOS authentication flows with AuthenticationServices and LocalAuthentication. Use when building Sign in with Apple, passkey/WebAuthn registration or sign-in with ASAuthorizationPlatformPublicKeyCredentialProvider, ASAuthorizationController credential state and revocation handling, ASWebAuthenticationSession OAuth or third-party login, Password AutoFill, identity-token server validation, or local biometric re-authentication with LAContext.

dpearson2699/avkit

Create media playback experiences using AVKit. Use when adding video players with AVPlayerViewController, enabling Picture-in-Picture, routing media with AirPlay, using SwiftUI VideoPlayer views, configuring transport controls, displaying subtitles and closed captions, or integrating AVFoundation playback with system UI.

dpearson2699/background-processing

Schedule and execute background work on iOS using BGTaskScheduler. Use when registering BGAppRefreshTask for short background fetches, BGProcessingTask for long-running maintenance, BGContinuedProcessingTask (iOS 26+) for foreground-started work that continues in background, background URLSession downloads, or background push notifications. Covers Info.plist configuration, expiration handling, task completion, and debugging with simulated launches.

dpearson2699/browserenginekit

Build alternative browser engines using BrowserEngineKit. Use when developing a non-WebKit browser engine for iOS/iPadOS in supported regions, managing web content/rendering/networking extension processes, configuring GPU and networking process capabilities, checking alternative-engine device eligibility, or reviewing BrowserEngineKit entitlements and Info.plist setup.

dpearson2699/callkit

Implement VoIP calling with CallKit and PushKit. Use when building incoming/outgoing call flows, registering for VoIP push notifications, configuring CXProvider and CXCallController, handling call actions, coordinating audio sessions, or creating Call Directory extensions for caller ID and call blocking.

dpearson2699/carplay

Build CarPlay-enabled apps using the CarPlay framework. Use when creating navigation, audio, communication, EV charging, parking, or food ordering apps for the car display, working with CPTemplateApplicationScene, CPInterfaceController template hierarchies, CPListTemplate, CPMapTemplate, CPNowPlayingTemplate, configuring CarPlay entitlements, or integrating with CarPlay Simulator for testing.

dpearson2699/cloudkit

Implement, review, or improve CloudKit and iCloud sync in iOS/macOS apps. Use when working with CKContainer, CKRecord, CKQuery, CKSubscription, CKSyncEngine, CKShare, NSUbiquitousKeyValueStore, or iCloud Drive file coordination; when syncing SwiftData models via ModelConfiguration with cloudKitDatabase; when handling CKError codes for conflict resolution, network failures, or quota limits; or when checking iCloud account status before performing sync operations.

dpearson2699/contacts-framework

Read, create, update, and pick contacts using the Contacts and ContactsUI frameworks. Use when fetching contact data, saving new contacts, wrapping CNContactPickerViewController in SwiftUI, handling contact permissions, or working with CNContactStore fetch and save requests.

dpearson2699/core-bluetooth

Build direct Bluetooth Low Energy workflows with Core Bluetooth. Use when implementing BLE central or peripheral GATT communication, scanning or connecting with CBCentralManager, discovering services and characteristics, reading/writing/subscribing with CBPeripheral, publishing local services with CBPeripheralManager, handling Bluetooth authorization, background BLE modes, state restoration, write flow control, or CBUUID-based workflows. For privacy-preserving accessory setup/picker flows, use accessorysetupkit first and return here for post-setup GATT communication.

dpearson2699/coreml

Integrate Core ML models in iOS apps for on-device machine learning inference. Covers model loading (.mlmodel, .mlpackage, .mlmodelc), predictions with auto-generated classes and MLFeatureProvider, compute unit configuration (CPU, GPU, Neural Engine), MLTensor, VNCoreMLRequest, MLComputePlan, multi-model pipelines, and deployment strategies. Use when loading Core ML models, making predictions, configuring compute units, or profiling model performance.

関連スキル