Contents.swift 4.4 KB

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