0

我正在尝试使用 Cryptoswift 框架加密 Swift 中的文件。我做到了,但是对于像mp4,mp3这样的文件有点重,它很慢。我真的不知道它发生了什么,如果我以错误的方式实现或者算法是这样的。

这是我的代码。

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)
}
4

1 回答 1

0

我想说,尝试使用 Release 版本重新测试。假设您正在查看 Debug 构建,预计 Swift 代码会明显变慢

于 2018-02-07T02:49:34.093 回答