From 233a469e9e86264ecf93c3913e505ee0ce2207c8 Mon Sep 17 00:00:00 2001 From: Zhuhao Wang Date: Sun, 21 Aug 2016 22:59:13 +0800 Subject: [PATCH] Optimize encryption algorithm --- src/Crypto/SodiumStreamCrypto.swift | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/Crypto/SodiumStreamCrypto.swift b/src/Crypto/SodiumStreamCrypto.swift index 87a109614..85716e264 100644 --- a/src/Crypto/SodiumStreamCrypto.swift +++ b/src/Crypto/SodiumStreamCrypto.swift @@ -24,22 +24,19 @@ class SodiumStreamCrypto: StreamCryptoProtocol { func update(data: NSData) -> NSData { let padding = counter % blockSize - var inputData: NSData + var outputData: NSMutableData if padding == 0 { - inputData = data + outputData = NSMutableData(data: data) } else { - let _data = NSMutableData(length: data.length + padding)! - _data.replaceBytesInRange(NSRange(location: padding, length: data.length), withBytes: data.bytes) - inputData = _data + outputData = NSMutableData(length: data.length + padding)! + outputData.replaceBytesInRange(NSRange(location: padding, length: data.length), withBytes: data.bytes) } - let outputData = NSMutableData(length: padding + data.length)! - switch algorithm { case .Chacha20: - crypto_stream_chacha20_xor_ic(UnsafeMutablePointer(outputData.mutableBytes), UnsafePointer(inputData.bytes), UInt64(outputData.length), UnsafePointer(iv.bytes), UInt64(counter/blockSize), UnsafePointer(key.bytes)) + crypto_stream_chacha20_xor_ic(UnsafeMutablePointer(outputData.mutableBytes), UnsafePointer(outputData.bytes), UInt64(outputData.length), UnsafePointer(iv.bytes), UInt64(counter/blockSize), UnsafePointer(key.bytes)) case .Salsa20: - crypto_stream_salsa20_xor_ic(UnsafeMutablePointer(outputData.mutableBytes), UnsafePointer(inputData.bytes), UInt64(outputData.length), UnsafePointer(iv.bytes), UInt64(counter/blockSize), UnsafePointer(key.bytes)) + crypto_stream_salsa20_xor_ic(UnsafeMutablePointer(outputData.mutableBytes), UnsafePointer(outputData.bytes), UInt64(outputData.length), UnsafePointer(iv.bytes), UInt64(counter/blockSize), UnsafePointer(key.bytes)) } counter += data.length