Skip to content
This repository has been archived by the owner on Apr 16, 2020. It is now read-only.

Commit

Permalink
Optimize encryption algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
zhuhaow committed Aug 21, 2016
1 parent ad7b5e5 commit 233a469
Showing 1 changed file with 6 additions and 9 deletions.
15 changes: 6 additions & 9 deletions src/Crypto/SodiumStreamCrypto.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<UInt8>(outputData.mutableBytes), UnsafePointer<UInt8>(inputData.bytes), UInt64(outputData.length), UnsafePointer<UInt8>(iv.bytes), UInt64(counter/blockSize), UnsafePointer<UInt8>(key.bytes))
crypto_stream_chacha20_xor_ic(UnsafeMutablePointer<UInt8>(outputData.mutableBytes), UnsafePointer<UInt8>(outputData.bytes), UInt64(outputData.length), UnsafePointer<UInt8>(iv.bytes), UInt64(counter/blockSize), UnsafePointer<UInt8>(key.bytes))
case .Salsa20:
crypto_stream_salsa20_xor_ic(UnsafeMutablePointer<UInt8>(outputData.mutableBytes), UnsafePointer<UInt8>(inputData.bytes), UInt64(outputData.length), UnsafePointer<UInt8>(iv.bytes), UInt64(counter/blockSize), UnsafePointer<UInt8>(key.bytes))
crypto_stream_salsa20_xor_ic(UnsafeMutablePointer<UInt8>(outputData.mutableBytes), UnsafePointer<UInt8>(outputData.bytes), UInt64(outputData.length), UnsafePointer<UInt8>(iv.bytes), UInt64(counter/blockSize), UnsafePointer<UInt8>(key.bytes))
}

counter += data.length
Expand Down

0 comments on commit 233a469

Please sign in to comment.