|
4 | 4 | Contact: [ [email protected]](http://krzyzanowskim.com) |
5 | 5 | */ |
6 | 6 | import CryptoSwift |
| 7 | +import Foundation |
| 8 | +import XCPlayground |
7 | 9 |
|
8 | 10 | //: # AES |
9 | 11 | //: One-time shot |
|
30 | 32 | } catch { |
31 | 33 | print(error) |
32 | 34 | } |
| 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 | +} |
0 commit comments