0

I'm trying to encrypt a file in Swift with the framework Cryptoswift. I made it, but with files a little bit heavy like mp4, mp3, it is very slow. I don't really know what it is happening, if I'm implementing in the wrong way or the algorithm is like that.

Here is my code.

do {
    // write until all is written
    let ex = "a"
    func writeTo(stream: OutputStream, bytes: Array<UInt8>) {
        var writtenCount = 0
        while stream.hasSpaceAvailable && writtenCount < bytes.count {
            writtenCount += stream.write(bytes, maxLength: bytes.count)
        }
    }
    let path = "somewhere"
    let aes = try AES(key: key, iv: iv)
    var encryptor = aes.makeEncryptor()

    // prepare streams
    //let data = Data(bytes: (0..<100).map { $0 })
    let inputStream = InputStream(fileAtPath: path)
    let outputStream = OutputStream(toFileAtPath: "somewhere", append: false)
    inputStream?.open()
    outputStream?.open()

    var buffer = Array<UInt8>(repeating: 0, count: 2)

    // 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: buffer[0..<readCount!]) { (bytes) in
                writeTo(stream: outputStream!, bytes: bytes)
            }
        }
    }

    // finalize encryption
    try encryptor.finish { (bytes) in
        writeTo(stream: outputStream!, bytes: bytes)
    }

    if let ciphertext = outputStream?.property(forKey: Stream.PropertyKey(rawValue: Stream.PropertyKey.dataWrittenToMemoryStreamKey.rawValue)) as? Data {
        print("Encrypted stream data: \(ciphertext.toHexString())")
    }

} catch {
    print(error)
}
Marcin
  • 3,694
  • 5
  • 32
  • 52
Efrain Perez
  • 63
  • 2
  • 5

1 Answers1

0

I'd say, try to re-test with the Release build. Assuming you're looking at Debug build, it is expected that Swift code will be significantly slower

Marcin
  • 3,694
  • 5
  • 32
  • 52