Skip to content

Commit

Permalink
Update to 1.0 CryptoSwift
Browse files Browse the repository at this point in the history
  • Loading branch information
cstephens-phunware committed May 15, 2019
1 parent f9da1dc commit 2744356
Show file tree
Hide file tree
Showing 69 changed files with 2,693 additions and 1,045 deletions.
736 changes: 330 additions & 406 deletions stellarsdk/stellarsdk.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

40 changes: 40 additions & 0 deletions stellarsdk/stellarsdk/libs/CryptoSwift/AEAD/AEAD.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//
// AEAD.swift
// CryptoSwift
//
// Copyright (C) 2014-2017 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.
//
//

// https://www.iana.org/assignments/aead-parameters/aead-parameters.xhtml

/// Authenticated Encryption with Associated Data (AEAD)
public protocol AEAD {
static var kLen: Int { get } // key length
static var ivRange: Range<Int> { get } // nonce length
}

extension AEAD {
static func calculateAuthenticationTag(authenticator: Authenticator, cipherText: Array<UInt8>, authenticationHeader: Array<UInt8>) throws -> Array<UInt8> {
let headerPadding = ((16 - (authenticationHeader.count & 0xf)) & 0xf)
let cipherPadding = ((16 - (cipherText.count & 0xf)) & 0xf)

var mac = authenticationHeader
mac += Array<UInt8>(repeating: 0, count: headerPadding)
mac += cipherText
mac += Array<UInt8>(repeating: 0, count: cipherPadding)
mac += UInt64(bigEndian: UInt64(authenticationHeader.count)).bytes()
mac += UInt64(bigEndian: UInt64(cipherText.count)).bytes()

return try authenticator.authenticate(mac)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//
// ChaCha20Poly1305.swift
// CryptoSwift
//
// Copyright (C) 2014-2017 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.
//
//
// https://tools.ietf.org/html/rfc7539#section-2.8.1

/// AEAD_CHACHA20_POLY1305
public final class AEADChaCha20Poly1305: AEAD {
public static let kLen = 32 // key length
public static var ivRange = Range<Int>(12...12)

/// Authenticated encryption
public static func encrypt(_ plainText: Array<UInt8>, key: Array<UInt8>, iv: Array<UInt8>, authenticationHeader: Array<UInt8>) throws -> (cipherText: Array<UInt8>, authenticationTag: Array<UInt8>) {
let cipher = try ChaCha20(key: key, iv: iv)

var polykey = Array<UInt8>(repeating: 0, count: kLen)
var toEncrypt = polykey
polykey = try cipher.encrypt(polykey)
toEncrypt += polykey
toEncrypt += plainText

let fullCipherText = try cipher.encrypt(toEncrypt)
let cipherText = Array(fullCipherText.dropFirst(64))

let tag = try calculateAuthenticationTag(authenticator: Poly1305(key: polykey), cipherText: cipherText, authenticationHeader: authenticationHeader)
return (cipherText, tag)
}

/// Authenticated decryption
public static func decrypt(_ cipherText: Array<UInt8>, key: Array<UInt8>, iv: Array<UInt8>, authenticationHeader: Array<UInt8>, authenticationTag: Array<UInt8>) throws -> (plainText: Array<UInt8>, success: Bool) {
let chacha = try ChaCha20(key: key, iv: iv)

let polykey = try chacha.encrypt(Array<UInt8>(repeating: 0, count: kLen))
let mac = try calculateAuthenticationTag(authenticator: Poly1305(key: polykey), cipherText: cipherText, authenticationHeader: authenticationHeader)
guard mac == authenticationTag else {
return (cipherText, false)
}

var toDecrypt = Array<UInt8>(reserveCapacity: cipherText.count + 64)
toDecrypt += polykey
toDecrypt += polykey
toDecrypt += cipherText
let fullPlainText = try chacha.decrypt(toDecrypt)
let plainText = Array(fullPlainText.dropFirst(64))
return (plainText, true)
}
}
130 changes: 12 additions & 118 deletions stellarsdk/stellarsdk/libs/CryptoSwift/AES.Cryptors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,128 +14,22 @@
//

// 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: Updatable {
private var worker: BlockModeWorker
private let padding: Padding
private var accumulated = Array<UInt8>()
private var processedBytesTotalCount: Int = 0
private let paddingRequired: Bool

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

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(chunk)
processedBytes += chunk.count
}
}
accumulated.removeFirst(processedBytes)
processedBytesTotalCount += processedBytes
return encrypted
extension AES: Cryptors {
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 {
private var worker: BlockModeWorker
private let padding: Padding
private var accumulated = Array<UInt8>()
private var processedBytesTotalCount: Int = 0
private let paddingRequired: Bool

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

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

switch aes.blockMode {
case .CFB, .OFB, .CTR:
// CFB, OFB, CTR uses encryptBlock to decrypt
worker = try aes.blockMode.worker(blockSize: AES.blockSize, cipherOperation: aes.encrypt)
default:
worker = try aes.blockMode.worker(blockSize: AES.blockSize, cipherOperation: aes.decrypt)
}

paddingRequired = aes.blockMode.options.contains(.paddingRequired)
}

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
}

var processedBytes = 0
var plaintext = Array<UInt8>(reserveCapacity: accumulated.count)
for chunk in accumulated.batched(by: AES.blockSize) {
if isLast || (accumulated.count - processedBytes) >= AES.blockSize {
plaintext += worker.decrypt(chunk)

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

processedBytes += chunk.count
}
}
accumulated.removeFirst(processedBytes)
processedBytesTotalCount += processedBytes

if isLast {
plaintext = padding.remove(from: plaintext, blockSize: AES.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)
self.worker = worker

offset = position % AES.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)
if worker is StreamModeWorker {
return try StreamDecryptor(blockSize: AES.blockSize, padding: padding, worker)
}
return try BlockDecryptor(blockSize: AES.blockSize, padding: padding, worker)
}
}
46 changes: 27 additions & 19 deletions stellarsdk/stellarsdk/libs/CryptoSwift/AES.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@

/// The Advanced Encryption Standard (AES)
public final class AES: BlockCipher {

public enum Error: Swift.Error {
/// Invalid key
case invalidKeySize
/// Data padding is required
case dataPaddingRequired
/// Invalid Data
Expand All @@ -42,24 +43,15 @@ public final class AES: BlockCipher {
}
}

private lazy var variantNr: Int = self.variant.Nr
private lazy var variantNb: Int = self.variant.Nb
private lazy var variantNk: Int = self.variant.Nk
private let variantNr: Int
private let variantNb: Int
private let variantNk: Int

public static let blockSize: Int = 16 // 128 /8
public let keySize: Int

public var variant: Variant {
switch key.count * 8 {
case 128:
return .aes128
case 192:
return .aes192
case 256:
return .aes256
default:
preconditionFailure("Unknown AES variant for given key.")
}
}
/// AES Variant
public let variant: Variant

// Parameters
let key: Key
Expand Down Expand Up @@ -124,6 +116,23 @@ public final class AES: BlockCipher {
self.key = Key(bytes: key)
self.blockMode = blockMode
self.padding = padding
self.keySize = self.key.count

// Validate key size
switch keySize * 8 {
case 128:
variant = .aes128
case 192:
variant = .aes192
case 256:
variant = .aes256
default:
throw Error.invalidKeySize
}

variantNb = variant.Nb
variantNk = variant.Nk
variantNr = variant.Nr
}

internal func encrypt(block: ArraySlice<UInt8>) -> Array<UInt8>? {
Expand Down Expand Up @@ -354,9 +363,8 @@ private extension AES {
}

private func expandKey(_ key: Key, variant _: Variant) -> Array<Array<UInt32>> {

func convertExpandedKey(_ expanded: Array<UInt8>) -> Array<Array<UInt32>> {
return expanded.batched(by: 4).map({ UInt32(bytes: $0.reversed()) }).batched(by: 4).map({ Array($0) })
return expanded.batched(by: 4).map({ UInt32(bytes: $0.reversed()) }).batched(by: 4).map { Array($0) }
}

/*
Expand Down Expand Up @@ -485,8 +493,8 @@ private extension AES {
}

// MARK: Cipher
extension AES: Cipher {

extension AES: Cipher {
public func encrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8> {
let chunks = bytes.batched(by: AES.blockSize)

Expand Down
Loading

0 comments on commit 2744356

Please sign in to comment.