Contents.swift 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. /*:
  8. # Data types conversinn
  9. */
  10. let data = Data(bytes: [0x01, 0x02, 0x03])
  11. let bytes = data.bytes
  12. let bytesHex = Array<UInt8>(hex: "0x010203")
  13. let hexString = bytesHex.toHexString()
  14. /*:
  15. # Digest
  16. */
  17. data.md5()
  18. data.sha1()
  19. data.sha224()
  20. data.sha256()
  21. data.sha384()
  22. data.sha512()
  23. bytes.sha1()
  24. "123".sha1()
  25. Digest.sha1(bytes)
  26. //: Digest calculated incrementally
  27. do {
  28. var digest = MD5()
  29. let partial1 = try digest.update(withBytes: [0x31, 0x32])
  30. let partial2 = try digest.update(withBytes: [0x33])
  31. let result = try digest.finish()
  32. } catch { }
  33. /*:
  34. # CRC
  35. */
  36. bytes.crc16()
  37. bytes.crc32()
  38. /*:
  39. # HMAC
  40. */
  41. do {
  42. let key:Array<UInt8> = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,23,25,26,27,28,29,30,31,32]
  43. try Poly1305(key: key).authenticate(bytes)
  44. try HMAC(key: key, variant: .sha256).authenticate(bytes)
  45. } catch {}
  46. /*:
  47. # PBKDF1, PBKDF2
  48. */
  49. do {
  50. let password: Array<UInt8> = "s33krit".utf8.map {$0}
  51. let salt: Array<UInt8> = "nacllcan".utf8.map {$0}
  52. try PKCS5.PBKDF1(password: password, salt: salt, variant: .sha1, iterations: 4096).calculate()
  53. let value = try PKCS5.PBKDF2(password: password, salt: salt, iterations: 4096, variant: .sha256).calculate()
  54. } catch {}
  55. /*:
  56. # Padding
  57. */
  58. PKCS7().add(to: bytes, blockSize: AES.blockSize)
  59. /*:
  60. # ChaCha20
  61. */
  62. do {
  63. let key:Array<UInt8> = [0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c];
  64. let iv:Array<UInt8> = [0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F]
  65. let message = Array<UInt8>(repeating: 7, count: 10)
  66. let encrypted = try ChaCha20(key: key, iv: iv).encrypt(message)
  67. let decrypted = try ChaCha20(key: key, iv: iv).decrypt(encrypted)
  68. } catch {}
  69. /*:
  70. # AES
  71. ### One-time shot.
  72. Encrypt all data at once.
  73. */
  74. do {
  75. let aes = try AES(key: "passwordpassword", iv: "drowssapdrowssap") // aes128
  76. let ciphertext = try aes.encrypt("Nullam quis risus eget urna mollis ornare vel eu leo.".utf8.map({$0}))
  77. print(ciphertext.toHexString())
  78. } catch {
  79. print(error)
  80. }
  81. /*:
  82. ### Incremental encryption
  83. Instantiate Encryptor for AES encryption (or decryptor for decryption) and process input data partially.
  84. */
  85. do {
  86. var encryptor = try AES(key: "passwordpassword", iv: "drowssapdrowssap").makeEncryptor()
  87. var ciphertext = Array<UInt8>()
  88. // aggregate partial results
  89. ciphertext += try encryptor.update(withBytes: "Nullam quis risus ".utf8.map({$0}))
  90. ciphertext += try encryptor.update(withBytes: "eget urna mollis ".utf8.map({$0}))
  91. ciphertext += try encryptor.update(withBytes: "ornare vel eu leo.".utf8.map({$0}))
  92. // finish at the end
  93. ciphertext += try encryptor.finish()
  94. print(ciphertext.toHexString())
  95. } catch {
  96. print(error)
  97. }
  98. /*:
  99. ### Encrypt stream
  100. */
  101. do {
  102. // write until all is written
  103. func writeTo(stream: OutputStream, bytes: Array<UInt8>) {
  104. var writtenCount = 0
  105. while stream.hasSpaceAvailable && writtenCount < bytes.count {
  106. let c = stream.write(bytes, maxLength: bytes.count)
  107. if c <= 0 {
  108. break;
  109. }
  110. writtenCount += stream.write(bytes, maxLength: bytes.count)
  111. }
  112. }
  113. let aes = try AES(key: "passwordpassword", iv: "drowssapdrowssap")
  114. var encryptor = aes.makeEncryptor()
  115. // prepare streams
  116. let data = Data(bytes: (0..<100).map { $0 })
  117. let inputStream = InputStream(data: data)
  118. let outputStream = OutputStream(toMemory: ())
  119. inputStream.open()
  120. outputStream.open()
  121. var buffer = Array<UInt8>(repeating: 0, count: 2)
  122. // encrypt input stream data and write encrypted result to output stream
  123. while (inputStream.hasBytesAvailable) {
  124. let readCount = inputStream.read(&buffer, maxLength: buffer.count)
  125. if (readCount > 0) {
  126. try encryptor.update(withBytes: buffer[0..<readCount]) { (bytes) in
  127. writeTo(stream: outputStream, bytes: bytes)
  128. }
  129. }
  130. }
  131. // finalize encryption
  132. try encryptor.finish { (bytes) in
  133. writeTo(stream: outputStream, bytes: bytes)
  134. }
  135. // print result
  136. if let ciphertext = outputStream.property(forKey: Stream.PropertyKey(rawValue: Stream.PropertyKey.dataWrittenToMemoryStreamKey.rawValue)) as? Data {
  137. print("Encrypted stream data: \(ciphertext.toHexString())")
  138. }
  139. } catch {
  140. print(error)
  141. }