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