如何将文件转换为数组<uint8>以加密cryptoSwift?

时间:2017-03-17 15:30:09

标签: swift encryption cryptoswift

我试图用框架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)
}

1 个答案:

答案 0 :(得分:0)

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