瀏覽代碼

Update Playground with Stream example.

Marcin Krzyżanowski 9 年之前
父節點
當前提交
491cd21199
共有 2 個文件被更改,包括 54 次插入1 次删除
  1. 53 0
      CryptoSwift.playground/Contents.swift
  2. 1 1
      CryptoSwift.playground/contents.xcplayground

+ 53 - 0
CryptoSwift.playground/Contents.swift

@@ -4,6 +4,8 @@
  Contact: [marcin@krzyzanowskim.com](http://krzyzanowskim.com)
 */
 import CryptoSwift
+import Foundation
+import XCPlayground
 
 //: # AES
 //: One-time shot
@@ -30,3 +32,54 @@ do {
 } catch {
     print(error)
 }
+
+//: Encrypt stream incrementally
+do {
+    // write until all is written
+    func writeToStream(stream: NSOutputStream, bytes: [UInt8]) {
+        var writtenCount = 0
+        while stream.hasSpaceAvailable && writtenCount < bytes.count {
+            let c = stream.write(bytes, maxLength: bytes.count)
+            if c <= 0 {
+                break;
+            }
+
+            writtenCount += stream.write(bytes, maxLength: bytes.count)
+        }
+    }
+
+    let aes = try AES(key: "passwordpassword", iv: "drowssapdrowssap")
+    var encryptor = aes.makeEncryptor()
+
+    // prepare streams
+    let data = NSData(bytes: (0..<100).map { $0 })
+    let inputStream = NSInputStream(data: data)
+    let outputStream = NSOutputStream(toMemory: ())
+    inputStream.open()
+    outputStream.open()
+
+    var buffer = [UInt8](count: 2, repeatedValue: 0)
+
+    // encrypt input stream data and write encrypted result to output stream
+    while (inputStream.hasBytesAvailable) {
+        let readCount = inputStream.read(&buffer, maxLength: buffer.count)
+        if (readCount > 0) {
+            try encryptor.update(withBytes: Array(buffer[0..<readCount])) { (bytes) in
+                writeToStream(outputStream, bytes: bytes)
+            }
+        }
+    }
+
+    // finalize encryption
+    try encryptor.finish { (bytes) in
+        writeToStream(outputStream, bytes: bytes)
+    }
+
+    // print result
+    if let ciphertext = outputStream.propertyForKey(NSStreamDataWrittenToMemoryStreamKey) as? NSData {
+        print("Encrypted stream data: \(ciphertext.toHexString())")
+    }
+
+} catch {
+    print(error)
+}

+ 1 - 1
CryptoSwift.playground/contents.xcplayground

@@ -1,4 +1,4 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<playground version='5.0' target-platform='ios' display-mode='raw'>
+<playground version='5.0' target-platform='ios' display-mode='rendered'>
     <timeline fileName='timeline.xctimeline'/>
 </playground>