CryptoKit框架详细解析(三) —— CryptoKit使用入门简单示例(二)

版本记录

版本号 时间
V1.0 2020.08.01 星期六

前言

CryptoKitiOS13的新的SDK,接下来几篇我们就一起看一下这个专题。感兴趣的可以看下面几篇文章。
1. CryptoKit框架详细解析(一) —— 基本概览(一)
2. CryptoKit框架详细解析(二) —— CryptoKit使用入门简单示例(一)

源码

1. Swift

首先看下工程组织结构

下面就是源码了

1. SceneDelegate.swift
import SwiftUI

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
  var window: UIWindow?

  func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Create the SwiftUI view that provides the window contents.
    let contentView = ContentView()

    // Use a UIHostingController as window root view controller.
    if let windowScene = scene as? UIWindowScene {
      let window = UIWindow(windowScene: windowScene)
      window.rootViewController = UIHostingController(rootView: contentView)
      self.window = window
      window.makeKeyAndVisible()
    }
  }
}
2. ContentView.swift
import SwiftUI

struct ContentView: View {
  @State var horcruxes: [Horcrux] = []
  let secretsURL = FileManager.documentsDirectoryURL
    .appendingPathComponent("Secrets.enc")

  // Call initHorcruxes to create 1.3MB Secrets.enc
  let names = ["Cup", "Diadem", "Journal", "Locket", "Ring", "Snake"]
  let labels = [
    "Hufflepuff's Cup",
    "Ravenclaw's Diadem",
    "Riddle's Diary",
    "Slytherin's Locket",
    "Gaunt's Ring",
    "Nagini"
  ]
  func initHorcruxes() {
    for i in 0..<names.count {
      // swiftlint:disable:next force_unwrapping
      let horcrux = Horcrux(name: names[i], imageData: (UIImage(named: names[i])?.pngData())!, label: labels[i])
      horcruxes.append(horcrux)
    }
  }

  // Once Secrets.enc exists, call readFile instead of initHorcruxes
  func readFile() {
    let decoder = PropertyListDecoder()
    do {
      let data = try Data.init(contentsOf: secretsURL)
      horcruxes = try decoder.decode([Horcrux].self, from: data)
      print("Secrets read from file \(secretsURL.absoluteString)")
    } catch {
      print(error)
    }
  }

  func writeFile(items: [Horcrux]) {
    // Don't overwrite Secrets.enc with empty array
    guard !items.isEmpty else { return }
    let encoder = PropertyListEncoder()
    encoder.outputFormat = .xml
    do {
      let data = try encoder.encode(items)
      //      try data.write(to: secretsURL)
      try data.write(to: secretsURL, options: .completeFileProtection)
      print("Secrets written to file \(secretsURL.absoluteString)")
    } catch {
      print(error)
    }
  }

  var body: some View {
    List(horcruxes, id: \.name) { horcrux in
      HStack {
        // swiftlint:disable:next force_unwrapping
        Image(uiImage: UIImage(data: horcrux.imageData)!)
          .resizable()
          .frame(maxHeight: 100)
          .aspectRatio(1 / 1, contentMode: .fit)
        Text(horcrux.label)
      }
    }
    .onAppear {
      //      self.initHorcruxes()
      self.readFile()
      self.writeFile(items: self.horcruxes)
    }
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView(horcruxes: [])
  }
}

public extension FileManager {
  static var documentsDirectoryURL: URL {
    `default`.urls(for: .documentDirectory, in: .userDomainMask)[0]
  }
}
3. Horcrux.swift
import Foundation

struct Horcrux: Codable {
  let name: String
  let imageData: Data
  let label: String
}
4. CryptoKitTutorial.playground
// Copyright (c) 2020 Razeware LLC
// For full license & permission details, see LICENSE.markdown.

import UIKit
import CryptoKit

func getData(for item: String, of type: String) -> Data {
  let filePath = Bundle.main.path(forResource: item, ofType: type)!
  return FileManager.default.contents(atPath: filePath)!
}
//: ## Hashing data
//: ### Hashable Protocol
func hashItem(item: String) -> Int {
  var hasher = Hasher()
  item.hash(into: &hasher)
  return hasher.finalize()
}
let hashValue = hashItem(item: "the quick brown fox")
//: ### Cryptographic Hashing
let data = getData(for: "Baby", of: "png")
UIImage(data: data)

// Create a digest of `data`:
let digest = SHA256.hash(data: data)

// Dumbledore sends`data` and `digest` to Harry,
// who hashes `data` and checks that digests match.
let receivedDataDigest = SHA256.hash(data: data)
if digest == receivedDataDigest {
  print("Data received == data sent.")
}

// Get String representation of `digest`:
String(describing: digest)

// Small change in `data` produces completely different digest:
String(describing: SHA256.hash(data: "Harry is a horcrux".data(using: .utf8)!))
String(describing: SHA256.hash(data: "Harry's a horcrux".data(using: .utf8)!))
//: ## HMAC: Hash-based Message Authentication Code
//: Use a symmetric cryptographic key when creating the digest
//: so the receiver knows it’s from you, or a server can check
//: that you’re authorized to upload files.
// Create a 256-bit symmetric key
let key256 = SymmetricKey(size: .bits256)
// Create a keyed digest of data
let sha512MAC = HMAC<SHA512>.authenticationCode(
  for: data, using: key256)
String(describing: sha512MAC)
// Convert signature to Data
let authenticationCodeData = Data(sha512MAC)
// Dumbledore sends data and signature to Harry, who checks the signature:
if HMAC<SHA512>.isValidAuthenticationCode(authenticationCodeData,
   authenticating: data, using: key256) {
    print("The message authentication code is validating the data: \(data))")
  UIImage(data: data)
}
else { print("not valid") }
//: ## Authenticated Encryption
// Create a sealed box with the encrypted data
let sealedBoxData = try! ChaChaPoly.seal(data, using: key256).combined
// Harry receives sealed box data, then extracts the sealed box
let sealedBox = try! ChaChaPoly.SealedBox(combined: sealedBoxData)
// Harry decrypts data with the same key
let decryptedData = try! ChaChaPoly.open(sealedBox, using: key256)

// What else is in the box?
sealedBox.nonce  // 12 bytes
sealedBox.tag  // 16 bytes
// encryptedData isn't an image
let encryptedData = sealedBox.ciphertext
UIImage(data: encryptedData)
UIImage(data: decryptedData)
//: ## Public-Key Cryptography
// Dumbledore wants to send the horcrux image to Harry.
// He signs it so Harry can verify it's from him.
let albusSigningPrivateKey = Curve25519.Signing.PrivateKey()
let albusSigningPublicKeyData =
  albusSigningPrivateKey.publicKey.rawRepresentation
// Dumbledore publishes `albusSigningPublicKeyData`.
// Dumbledore signs `data` (or `digest`) with his private key.
let signatureForData = try! albusSigningPrivateKey.signature(
  for: data)
// Signing a digest of the data is faster:
let digest512 = SHA512.hash(data: data)
let signatureForDigest = try! albusSigningPrivateKey.signature(
  for: Data(digest512))
// Harry verifies signatures with key created from
// albusSigningPublicKeyData.
let publicKey = try! Curve25519.Signing.PublicKey(
  rawRepresentation: albusSigningPublicKeyData)
if publicKey.isValidSignature(signatureForData, for: data) {
  print("Dumbledore sent this data.")
}
if publicKey.isValidSignature(signatureForDigest,
  for: Data(digest512)) {
  print("Data received == data sent.")
  UIImage(data: data)
}
//: ## Shared secret / Key agreement
// Dumbledore and Harry create private and public keys for
// key agreement, and publish the public keys.
let albusPrivateKey = Curve25519.KeyAgreement.PrivateKey()
let albusPublicKeyData = albusPrivateKey.publicKey.rawRepresentation
let harryPrivateKey = Curve25519.KeyAgreement.PrivateKey()
let harryPublicKeyData = harryPrivateKey.publicKey.rawRepresentation
// Dumbledore and Harry must agree on the salt value
// for creating the symmetric key:
let protocolSalt = "Voldemort's Horcruxes".data(using: .utf8)!
// Dumbledore uses his private key and Harry's public key
// to calculate `sharedSecret` and `symmetricKey`.
let harryPublicKey = try! Curve25519.KeyAgreement.PublicKey(
  rawRepresentation: harryPublicKeyData)
let ADsharedSecret = try! albusPrivateKey.sharedSecretFromKeyAgreement(
  with: harryPublicKey)
let ADsymmetricKey = ADsharedSecret.hkdfDerivedSymmetricKey(
  using: SHA256.self, salt: protocolSalt,
  sharedInfo: Data(), outputByteCount: 32)
// Harry uses his private key and Dumbledore's public key
// to calculate `sharedSecret` and `symmetricKey`.
let albusPublicKey = try! Curve25519.KeyAgreement.PublicKey(
rawRepresentation: albusPublicKeyData)
let HPsharedSecret = try! harryPrivateKey.sharedSecretFromKeyAgreement(
  with: albusPublicKey)
let HPsymmetricKey = HPsharedSecret.hkdfDerivedSymmetricKey(
  using: SHA256.self, salt: protocolSalt,
  sharedInfo: Data(), outputByteCount: 32)
// As if by magic, they produce the same symmetric key!
if ADsymmetricKey == HPsymmetricKey {
  print("Dumbledore and Harry have the same symmetric key.")
}
//: Now Dumbledore and Harry can use symmetric key cryptography to authenticate or encrypt data.

后记

本篇主要讲述了CryptoKit使用入门简单示例,感兴趣的给个赞或者关注~~~

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270