forked from krzyzanowskim/CryptoSwift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Contents.swift
85 lines (71 loc) · 2.6 KB
/
Contents.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*:
To whom may be concerned: I offer professional support to all my open source projects.
Contact: [[email protected]](http://krzyzanowskim.com)
*/
import CryptoSwift
import Foundation
import XCPlayground
//: # AES
//: One-time shot
do {
let aes = try AES(key: "passwordpassword", iv: "drowssapdrowssap") // aes128
let ciphertext = try aes.encrypt("Nullam quis risus eget urna mollis ornare vel eu leo.".utf8.map({$0}))
print(ciphertext.toHexString())
} catch {
print(error)
}
//: Incremental encryption
do {
let aes = try AES(key: "passwordpassword", iv: "drowssapdrowssap") // aes128
var encryptor = aes.makeEncryptor()
var ciphertext = Array<UInt8>()
ciphertext += try encryptor.update(withBytes: "Nullam quis risus ".utf8.map({$0}))
ciphertext += try encryptor.update(withBytes: "eget urna mollis ".utf8.map({$0}))
ciphertext += try encryptor.update(withBytes: "ornare vel eu leo.".utf8.map({$0}))
ciphertext += try encryptor.finish()
print(ciphertext.toHexString())
} catch {
print(error)
}
//: Encrypt stream incrementally
do {
// write until all is written
func writeToStream(stream: NSOutputStream, bytes: Array<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 = Array<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)
}