Image Encryption in Swift

后端 未结 1 1114
醉酒成梦
醉酒成梦 2021-01-14 08:56

I am using IDZSwiftCommonCrypto for image encryption using StreamCryptor described as an example at its GitHub page: https://github.com/iosdevzone/IDZSwiftCommo

相关标签:
1条回答
  • 2021-01-14 09:36
    xx.append(outputBuffer, count: cryptedBytes)
    

    should help.

    below is sample code for picking up an encrypted image file and returning the data.

    func decryptImage(from path:URL)-> Data? {
        var decryptData = Data()
    
        let sc = StreamCryptor(operation:.decrypt, algorithm:.aes, options:.PKCS7Padding, key:key, iv:iv)
    
        guard let encryptedInputStream = InputStream(fileAtPath: path.relativePath) else {
            return nil
        }
    
        var inputBuffer = [UInt8](repeating: 0, count: Int(1024))
        var outputBuffer = [UInt8](repeating: 0, count: Int(1024))
    
        encryptedInputStream.open()
    
        var cryptedBytes : Int = 0
        while encryptedInputStream.hasBytesAvailable
        {
            let bytesRead = encryptedInputStream.read(&inputBuffer, maxLength: inputBuffer.count)
    
            let status = sc.update(bufferIn: inputBuffer, byteCountIn: bytesRead, bufferOut: &outputBuffer, byteCapacityOut: outputBuffer.count, byteCountOut: &cryptedBytes)
    
            if (status != Status.success) {
            encryptedInputStream.close()
                return nil
            }
    
            if(cryptedBytes > 0)
            {
                decryptData.append(outputBuffer, count: cryptedBytes)
            }
        }
    
        let status = sc.final(bufferOut: &outputBuffer, byteCapacityOut: outputBuffer.count, byteCountOut: &cryptedBytes)
        if (status != Status.success) {
            encryptedInputStream.close()
            return nil
        }
    
        if(cryptedBytes > 0)
        {
            decryptData.append(outputBuffer, count: cryptedBytes)
        }
        encryptedInputStream.close()
        return decryptData
    }
    

    Happy coding :)

    0 讨论(0)
提交回复
热议问题