Contents.swift 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*:
  2. To whom may be concerned: I offer professional support to all my open source projects.
  3. Contact: [marcin@krzyzanowskim.com](http://krzyzanowskim.com)
  4. */
  5. import CryptoSwift
  6. import Foundation
  7. import XCPlayground
  8. //: # AES
  9. //: One-time shot
  10. do {
  11. let aes = try AES(key: "passwordpassword", iv: "drowssapdrowssap")
  12. let ciphertext = try aes.encrypt("Nullam quis risus eget urna mollis ornare vel eu leo.".utf8.map({$0}))
  13. print(ciphertext.toHexString())
  14. } catch {
  15. print(error)
  16. }
  17. //: Incremental encryption
  18. do {
  19. let aes = try AES(key: "passwordpassword", iv: "drowssapdrowssap")
  20. var encryptor = aes.makeEncryptor()
  21. var ciphertext = Array<UInt8>()
  22. ciphertext += try encryptor.update(withBytes: "Nullam quis risus ".utf8.map({$0}))
  23. ciphertext += try encryptor.update(withBytes: "eget urna mollis ".utf8.map({$0}))
  24. ciphertext += try encryptor.update(withBytes: "ornare vel eu leo.".utf8.map({$0}))
  25. ciphertext += try encryptor.finish()
  26. print(ciphertext.toHexString())
  27. } catch {
  28. print(error)
  29. }
  30. //: Encrypt stream incrementally
  31. do {
  32. // write until all is written
  33. func writeToStream(stream: NSOutputStream, bytes: Array<UInt8>) {
  34. var writtenCount = 0
  35. while stream.hasSpaceAvailable && writtenCount < bytes.count {
  36. let c = stream.write(bytes, maxLength: bytes.count)
  37. if c <= 0 {
  38. break;
  39. }
  40. writtenCount += stream.write(bytes, maxLength: bytes.count)
  41. }
  42. }
  43. let aes = try AES(key: "passwordpassword", iv: "drowssapdrowssap")
  44. var encryptor = aes.makeEncryptor()
  45. // prepare streams
  46. let data = NSData(bytes: (0..<100).map { $0 })
  47. let inputStream = NSInputStream(data: data)
  48. let outputStream = NSOutputStream(toMemory: ())
  49. inputStream.open()
  50. outputStream.open()
  51. var buffer = Array<UInt8>(repeating: 0, count: 2)
  52. // encrypt input stream data and write encrypted result to output stream
  53. while (inputStream.hasBytesAvailable) {
  54. let readCount = inputStream.read(&buffer, maxLength: buffer.count)
  55. if (readCount > 0) {
  56. try encryptor.update(withBytes: Array(buffer[0..<readCount])) { (bytes) in
  57. writeToStream(outputStream, bytes: bytes)
  58. }
  59. }
  60. }
  61. // finalize encryption
  62. try encryptor.finish { (bytes) in
  63. writeToStream(outputStream, bytes: bytes)
  64. }
  65. // print result
  66. if let ciphertext = outputStream.propertyForKey(NSStreamDataWrittenToMemoryStreamKey) as? NSData {
  67. print("Encrypted stream data: \(ciphertext.toHexString())")
  68. }
  69. } catch {
  70. print(error)
  71. }