Skip to content

Commit 491cd21

Browse files
committed
Update Playground with Stream example.
1 parent 5663670 commit 491cd21

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

CryptoSwift.playground/Contents.swift

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
Contact: [[email protected]](http://krzyzanowskim.com)
55
*/
66
import CryptoSwift
7+
import Foundation
8+
import XCPlayground
79

810
//: # AES
911
//: One-time shot
@@ -30,3 +32,54 @@ do {
3032
} catch {
3133
print(error)
3234
}
35+
36+
//: Encrypt stream incrementally
37+
do {
38+
// write until all is written
39+
func writeToStream(stream: NSOutputStream, bytes: [UInt8]) {
40+
var writtenCount = 0
41+
while stream.hasSpaceAvailable && writtenCount < bytes.count {
42+
let c = stream.write(bytes, maxLength: bytes.count)
43+
if c <= 0 {
44+
break;
45+
}
46+
47+
writtenCount += stream.write(bytes, maxLength: bytes.count)
48+
}
49+
}
50+
51+
let aes = try AES(key: "passwordpassword", iv: "drowssapdrowssap")
52+
var encryptor = aes.makeEncryptor()
53+
54+
// prepare streams
55+
let data = NSData(bytes: (0..<100).map { $0 })
56+
let inputStream = NSInputStream(data: data)
57+
let outputStream = NSOutputStream(toMemory: ())
58+
inputStream.open()
59+
outputStream.open()
60+
61+
var buffer = [UInt8](count: 2, repeatedValue: 0)
62+
63+
// encrypt input stream data and write encrypted result to output stream
64+
while (inputStream.hasBytesAvailable) {
65+
let readCount = inputStream.read(&buffer, maxLength: buffer.count)
66+
if (readCount > 0) {
67+
try encryptor.update(withBytes: Array(buffer[0..<readCount])) { (bytes) in
68+
writeToStream(outputStream, bytes: bytes)
69+
}
70+
}
71+
}
72+
73+
// finalize encryption
74+
try encryptor.finish { (bytes) in
75+
writeToStream(outputStream, bytes: bytes)
76+
}
77+
78+
// print result
79+
if let ciphertext = outputStream.propertyForKey(NSStreamDataWrittenToMemoryStreamKey) as? NSData {
80+
print("Encrypted stream data: \(ciphertext.toHexString())")
81+
}
82+
83+
} catch {
84+
print(error)
85+
}
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2-
<playground version='5.0' target-platform='ios' display-mode='raw'>
2+
<playground version='5.0' target-platform='ios' display-mode='rendered'>
33
<timeline fileName='timeline.xctimeline'/>
44
</playground>

0 commit comments

Comments
 (0)