Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
krzyzanowskim committed Jul 31, 2018
2 parents 4d446e7 + 4378728 commit 3f6869c
Show file tree
Hide file tree
Showing 25 changed files with 398 additions and 241 deletions.
8 changes: 7 additions & 1 deletion CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
0.11.0
- API: Cryptor.seek() is throwable
- Adds proper stream support for CTR encryption with Updaptable interface.
- Refactor internals for the stream cipher modes.
- Set minimum deployment target to 8.0 (again).

0.10.0
- API: BlockMode is no longer an enum. Please migrate to eg. CBC() etc...
- Adds AES-GCM support. #97 - Feature sponsored by GesundheitsCloud (http://www.gesundheitscloud.de/)
Expand Down Expand Up @@ -93,7 +99,7 @@
- Set deployment targets for all platform. Fixes Carthage builds.
- New: SHA-3 implementation (request #291)
- SHA-1 conforms to Updatable protocol and may be calculated incrementally.
- SHA-2 conforms to Updatable protocol and may be calculated incrementally.
- SHA-2 conforms to Updatable protocol and may be calculated incrementally.

0.6.0
- Remove bridge() workaround for Linux (not needed)
Expand Down
2 changes: 1 addition & 1 deletion CryptoSwift.podspec
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = "CryptoSwift"
s.version = "0.10.0"
s.version = "0.11.0"
s.source = { :git => "https://github.com/krzyzanowskim/CryptoSwift.git", :tag => "#{s.version}" }
s.summary = "Cryptography in Swift. SHA, MD5, CRC, PBKDF, Poly1305, HMAC, CMAC, HDKF, ChaCha20, Rabbit, Blowfish, AES."
s.description = "Cryptography functions and helpers for Swift implemented in Swift. SHA-1, SHA-2, SHA-3, MD5, PBKDF1, PBKDF2, CRC, Poly1305, HMAC, ChaCha20, Rabbit, Blowfish, AES"
Expand Down
32 changes: 20 additions & 12 deletions CryptoSwift.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

158 changes: 9 additions & 149 deletions Sources/CryptoSwift/AES.Cryptors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,157 +16,17 @@
// MARK: Cryptors

extension AES: Cryptors {
public func makeEncryptor() throws -> AES.Encryptor {
return try AES.Encryptor(aes: self)
}

public func makeDecryptor() throws -> AES.Decryptor {
return try AES.Decryptor(aes: self)
}
}

// MARK: Encryptor

extension AES {
public struct Encryptor: Cryptor, Updatable {
private var worker: BlockModeWorker
private let padding: Padding
// Accumulated bytes. Not all processed bytes.
private var accumulated = Array<UInt8>()
private var processedBytesTotalCount: Int = 0

init(aes: AES) throws {
padding = aes.padding
worker = try aes.blockMode.worker(blockSize: AES.blockSize, cipherOperation: aes.encrypt)
}

// MARK: Updatable
public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
accumulated += bytes

if isLast {
accumulated = padding.add(to: accumulated, blockSize: AES.blockSize)
}

var processedBytes = 0
var encrypted = Array<UInt8>(reserveCapacity: accumulated.count)
for chunk in accumulated.batched(by: AES.blockSize) {
if isLast || (accumulated.count - processedBytes) >= AES.blockSize {
encrypted += worker.encrypt(block: chunk)
processedBytes += chunk.count
}
}
accumulated.removeFirst(processedBytes)
processedBytesTotalCount += processedBytes

if var finalizingWorker = worker as? BlockModeWorkerFinalizing, isLast == true {
encrypted = try finalizingWorker.finalize(encrypt: encrypted.slice)
}

return encrypted
public func makeEncryptor() throws -> Cryptor & Updatable {
let worker = try blockMode.worker(blockSize: AES.blockSize, cipherOperation: encrypt)
if worker is StreamModeWorker {
return try StreamEncryptor(blockSize: AES.blockSize, padding: padding, worker)
}
return try BlockEncryptor(blockSize: AES.blockSize, padding: padding, worker)
}
}

// MARK: Decryptor

extension AES {
public struct Decryptor: RandomAccessCryptor, Updatable {
private var worker: BlockModeWorker
private let padding: Padding
private let additionalBufferSize: Int
private var accumulated = Array<UInt8>()
private var processedBytesTotalCount: Int = 0

private var offset: Int = 0
private var offsetToRemove: Int = 0

init(aes: AES) throws {
padding = aes.padding

if aes.blockMode.options.contains(.useEncryptToDecrypt) {
worker = try aes.blockMode.worker(blockSize: AES.blockSize, cipherOperation: aes.encrypt)
} else {
worker = try aes.blockMode.worker(blockSize: AES.blockSize, cipherOperation: aes.decrypt)
}

additionalBufferSize = worker.additionalBufferSize
}

public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
// prepend "offset" number of bytes at the beginning
if offset > 0 {
accumulated += Array<UInt8>(repeating: 0, count: offset) + bytes
offsetToRemove = offset
offset = 0
} else {
accumulated += bytes
}

// If a worker (eg GCM) can combine ciphertext + tag
// we need to remove tag from the ciphertext.
if !isLast && accumulated.count < worker.blockSize + additionalBufferSize {
return []
}

let accumulatedWithoutSuffix: Array<UInt8>
if additionalBufferSize > 0 {
// FIXME: how slow is that?
accumulatedWithoutSuffix = Array(accumulated.prefix(accumulated.count - additionalBufferSize))
} else {
accumulatedWithoutSuffix = accumulated
}

var processedBytesCount = 0
var plaintext = Array<UInt8>(reserveCapacity: accumulatedWithoutSuffix.count)
// Processing in a block-size manner. It's good for block modes, but bad for stream modes.
for var chunk in accumulatedWithoutSuffix.batched(by: worker.blockSize) {
if isLast || (accumulatedWithoutSuffix.count - processedBytesCount) >= worker.blockSize {

if isLast, var finalizingWorker = worker as? BlockModeWorkerFinalizing {
chunk = try finalizingWorker.willDecryptLast(block: chunk + accumulated.suffix(additionalBufferSize)) // tag size
}

if !chunk.isEmpty {
plaintext += worker.decrypt(block: chunk)
}

// remove "offset" from the beginning of first chunk
if offsetToRemove > 0 {
plaintext.removeFirst(offsetToRemove)
offsetToRemove = 0
}

if var finalizingWorker = worker as? BlockModeWorkerFinalizing, isLast == true {
plaintext = try finalizingWorker.didDecryptLast(block: plaintext.slice)
}

processedBytesCount += chunk.count
}
}
accumulated.removeFirst(processedBytesCount) // super-slow
processedBytesTotalCount += processedBytesCount

if isLast {
plaintext = padding.remove(from: plaintext, blockSize: worker.blockSize)
}

return plaintext
}

@discardableResult public mutating func seek(to position: Int) -> Bool {
guard var worker = self.worker as? RandomAccessBlockModeWorker else {
return false
}

worker.counter = UInt(position / AES.blockSize) // TODO: worker.blockSize
self.worker = worker

offset = position % worker.blockSize

accumulated = []

return true
}
public func makeDecryptor() throws -> Cryptor & Updatable {
let cipherOperation: CipherOperationOnBlock = blockMode.options.contains(.useEncryptToDecrypt) == true ? encrypt : decrypt
let worker = try blockMode.worker(blockSize: AES.blockSize, cipherOperation: cipherOperation)
return try BlockDecryptor(blockSize: AES.blockSize, padding: padding, worker)
}
}
84 changes: 84 additions & 0 deletions Sources/CryptoSwift/BlockDecryptor.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// CryptoSwift
//
// Copyright (C) 2014-__YEAR__ Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//

public class BlockDecryptor: Cryptor, Updatable {
private let blockSize: Int
private let padding: Padding
private var worker: CipherModeWorker
private var accumulated = Array<UInt8>()

init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws {
self.blockSize = blockSize
self.padding = padding
self.worker = worker
}

public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
accumulated += bytes

// If a worker (eg GCM) can combine ciphertext + tag
// we need to remove tag from the ciphertext.
if !isLast && accumulated.count < blockSize + worker.additionalBufferSize {
return []
}

let accumulatedWithoutSuffix: Array<UInt8>
if worker.additionalBufferSize > 0 {
// FIXME: how slow is that?
accumulatedWithoutSuffix = Array(accumulated.prefix(accumulated.count - worker.additionalBufferSize))
} else {
accumulatedWithoutSuffix = accumulated
}

var processedBytesCount = 0
var plaintext = Array<UInt8>(reserveCapacity: accumulatedWithoutSuffix.count)
// Processing in a block-size manner. It's good for block modes, but bad for stream modes.
for var chunk in accumulatedWithoutSuffix.batched(by: blockSize) {
if isLast || (accumulatedWithoutSuffix.count - processedBytesCount) >= blockSize {

if isLast, var finalizingWorker = worker as? BlockModeWorkerFinalizing {
chunk = try finalizingWorker.willDecryptLast(block: chunk + accumulated.suffix(worker.additionalBufferSize)) // tag size
}

if !chunk.isEmpty {
plaintext += worker.decrypt(block: chunk)
}

if var finalizingWorker = worker as? BlockModeWorkerFinalizing, isLast == true {
plaintext = try finalizingWorker.didDecryptLast(block: plaintext.slice)
}

processedBytesCount += chunk.count
}
}
accumulated.removeFirst(processedBytesCount) // super-slow

if isLast {
plaintext = padding.remove(from: plaintext, blockSize: blockSize)
}

return plaintext
}

public func seek(to position: Int) throws {
guard var worker = self.worker as? StreamModeWorker else {
fatalError("Not supported")
}

try worker.seek(to: position)
self.worker = worker

accumulated = []
}
}
57 changes: 57 additions & 0 deletions Sources/CryptoSwift/BlockEncryptor.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// CryptoSwift
//
// Copyright (C) 2014-__YEAR__ Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
final class BlockEncryptor: Cryptor, Updatable {
private let blockSize: Int
private var worker: CipherModeWorker
private let padding: Padding
// Accumulated bytes. Not all processed bytes.
private var accumulated = Array<UInt8>(reserveCapacity: 16)

private var lastBlockRemainder = 0

init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws {
self.blockSize = blockSize
self.padding = padding
self.worker = worker
}

// MARK: Updatable
public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool) throws -> Array<UInt8> {
accumulated += bytes

if isLast {
accumulated = padding.add(to: accumulated, blockSize: blockSize)
}

var encrypted = Array<UInt8>(reserveCapacity: accumulated.count)
for chunk in accumulated.batched(by: blockSize) {
if isLast || chunk.count == blockSize {
encrypted += worker.encrypt(block: chunk)
}
}

// Stream encrypts all, so it removes all elements
accumulated.removeFirst(encrypted.count)

if var finalizingWorker = worker as? BlockModeWorkerFinalizing, isLast == true {
encrypted = try finalizingWorker.finalize(encrypt: encrypted.slice)
}

return encrypted
}

func seek(to: Int) throws {
fatalError("Not supported")
}
}
4 changes: 3 additions & 1 deletion Sources/CryptoSwift/BlockMode/BlockMode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,7 @@ public typealias CipherOperationOnBlock = (_ block: ArraySlice<UInt8>) -> Array<
public protocol BlockMode {
var options: BlockModeOption { get }
//TODO: doesn't have to be public
func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> BlockModeWorker
func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker
}

typealias StreamMode = BlockMode
2 changes: 1 addition & 1 deletion Sources/CryptoSwift/BlockMode/CBC.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public struct CBC: BlockMode {
self.iv = iv
}

public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> BlockModeWorker {
public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker {
if iv.count != blockSize {
throw Error.invalidInitializationVector
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/CryptoSwift/BlockMode/CFB.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public struct CFB: BlockMode {
self.iv = iv
}

public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> BlockModeWorker {
public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker {
if iv.count != blockSize {
throw Error.invalidInitializationVector
}
Expand Down
Loading

0 comments on commit 3f6869c

Please sign in to comment.