Skip to content

lemo-nade-room/swift-crypto-codable

Repository files navigation

CryptoCodable

CryptoCodableは、Appleのswift-cryptoを使用してJSONエンコード時にAES-GCMでプロパティを暗号化するためのSwiftライブラリです。このライブラリは、Sendable対応であると同時に、CodableHashableにも準拠したプロパティを保護し、復号もシンプルに行えるように設計されています。

Documentation MIT License Testing Status Swift 6.0+

サポート

  • macOS >= 13
  • Swift >= 6.0

特徴

  • AES-GCMでJSONプロパティを暗号化・復号
  • 暗号化対象のプロパティはSendableCryptoFieldableに準拠している必要がある

インストール

このライブラリはSwift Package Managerを使用してインストールできます。

let package = Package(
    ...
    dependencies: [
        ...
        .package(url: "https://github.com/lemo-nade-room/swift-crypto-codable.git", branch: "main"),
    ],
    targets: [
        .target(
            name: "YourApp",
            dependencies: [
                .product(name: "CryptoCodable", package: "swift-crypto-codable"),
            ]
        ),
        ...
    ]
    ...
)

ドキュメンテーション

DocCによるAPIドキュメントがあります

使用方法

1. CryptoFieldプロパティラッパーを使った型を定義

まず、暗号化対象のプロパティを持つCodableな型を定義します。

import CryptoCodable
import Foundation

struct Event: Hashable, Codable, Sendable {
    var id: UUID
    var 職業: String
    @CryptoField var 氏名: String
    @CryptoField var LINEやってる: Bool
    @CryptoField var 誕生日: Date
    @CryptoField var 年齢: Int
    @CryptoField var 身長: Double
    @CryptoField var 体重: Double?
}

2. 暗号化

次に、暗号鍵を設定して暗号化を行います。暗号鍵が設定されていない場合、fatalErrorが発生します。

import CryptoCodable
import Foundation

let jsonData: Data = try CryptoConfigContainer.$key.withValue(.init(size: .bits256)) {
    try JSONEncoder().encode(event)
}

3. 復号

暗号化されたデータを復号します。復号時にも暗号鍵を設定します。

import CryptoCodable
import Foundation

let event: Event = try CryptoConfigContainer.$key.withValue(key) {
    try JSONDecoder().decode(Event.self, from: encrypted)
}

暗号化可能なプロパティの条件

  • プロパティの型はSendableCryptoFieldableに準拠している必要があります。
  • Int, String, Double, Bool, Date, Optional型はデフォルトで準拠している

暗号鍵が設定されていない場合

暗号鍵が設定されていない場合、プロパティにはnilが設定されますが、デコード自体は成功します。

  • 暗号鍵が異なる場合には、DecryptFailureエラーが発生します。

ライセンス

このライブラリはMITライセンスで提供されています。詳細はLICENSEファイルをご覧ください。

なお、このプロジェクトはapple/swift-cryptoに依存しています。apple/swift-cryptoはApache 2.0ライセンスに基づいて提供されています。詳しくはこちらをご確認ください。