Selaa lähdekoodia

Update to latest changes in Swift.
Error -> ErrorProblem (I hope it's temporary https://twitter.com/krzyzanowskim/status/757707046267518978).
AESVariant -> AES.Variant
Language syntax updates.

Marcin Krzyżanowski 9 vuotta sitten
vanhempi
commit
1f7fb235bf

+ 0 - 2
CryptoSwift.playground/Contents.swift

@@ -5,8 +5,6 @@
 */
 import CryptoSwift
 import Foundation
-import XCPlayground
-
 /*: 
  # AES
  ### One-time shot.

+ 4 - 4
CryptoSwiftTests/HashTests.swift

@@ -51,16 +51,16 @@ final class CryptoSwiftTests: XCTestCase {
     
     func testMD5PerformanceCommonCrypto() {
         self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: false, for: { () -> Void in
-            let buf = UnsafeMutablePointer<UInt8>(calloc(1024 * 1024, sizeof(UInt8)))
+            let buf = UnsafeMutablePointer<UInt8>(calloc(1024 * 1024, sizeof(UInt8.self)))
             let data = NSData(bytes: buf, length: 1024 * 1024)
-            let outbuf = UnsafeMutablePointer<UInt8>(allocatingCapacity: Int(CC_MD5_DIGEST_LENGTH))
+            let outbuf = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(CC_MD5_DIGEST_LENGTH))
             self.startMeasuring()
                 CC_MD5(data.bytes, CC_LONG(data.length), outbuf)
             //let output = NSData(bytes: outbuf, length: Int(CC_MD5_DIGEST_LENGTH));
             self.stopMeasuring()
-            outbuf.deallocateCapacity(Int(CC_MD5_DIGEST_LENGTH))
+            outbuf.deallocate(capacity: Int(CC_MD5_DIGEST_LENGTH))
             outbuf.deinitialize()
-            buf?.deallocateCapacity(1024 * 1024)
+            buf?.deallocate(capacity:1024 * 1024)
             buf?.deinitialize()
         })
     }

+ 1 - 1
CryptoSwiftTests/PBKDF.swift

@@ -22,7 +22,7 @@ class PBKDF: XCTestCase {
     func test_pbkdf1() {
         let password: Array<UInt8> = [0x70,0x61,0x73,0x73,0x77,0x6F,0x72,0x64]
         let salt: Array<UInt8> = [0x78,0x57,0x8E,0x5A,0x5D,0x63,0xCB,0x06]
-        let value = try! PKCS5.PBKDF1(password: password, salt: salt, iterations: 1000, keyLength: 16, variant: .sha1).calculate()
+        let value = try! PKCS5.PBKDF1(password: password, salt: salt, iterations: 1000, keyLength: 16).calculate()
         XCTAssertEqual(value.toHexString(), "dc19847e05c64d2faf10ebfb4a3d2a20")
     }
 

+ 8 - 8
Sources/CryptoSwift/AES.swift

@@ -11,13 +11,13 @@
 private typealias Key = SecureBytes
 
 final public class AES: BlockCipher {
-    public enum Error: ErrorProtocol {
+    public enum ErrorProblem: Error {
         case dataPaddingRequired
         case invalidKeyOrInitializationVector
         case invalidInitializationVector
     }
     
-    public enum AESVariant: Int {
+    public enum Variant: Int {
         case aes128 = 1, aes192, aes256
         
         var Nk:Int { // Nk words
@@ -36,7 +36,7 @@ final public class AES: BlockCipher {
     private let blockMode:BlockMode
     public static let blockSize:Int = 16 // 128 /8
     
-    public var variant:AESVariant {
+    public var variant:Variant {
         switch (self.key.count * 8) {
         case 128:
             return .aes128
@@ -104,7 +104,7 @@ final public class AES: BlockCipher {
 
         if (blockMode.options.contains(.InitializationVectorRequired) && self.iv.count != AES.blockSize) {
             assert(false, "Block size and Initialization Vector must be the same length!")
-            throw Error.invalidInitializationVector
+            throw ErrorProblem.invalidInitializationVector
         }
     }
 }
@@ -257,7 +257,7 @@ extension AES {
         return out
     }
 
-    private func expandKeyInv(_ key: Key, variant: AESVariant) -> Array<Array<UInt32>> {
+    private func expandKeyInv(_ key: Key, variant: Variant) -> Array<Array<UInt32>> {
         let rounds = variant.Nr
         var rk2:Array<Array<UInt32>> = expandKey(key, variant: variant)
 
@@ -280,7 +280,7 @@ extension AES {
         return rk2
     }
 
-    private func expandKey(_ key:Key, variant:AESVariant) -> Array<Array<UInt32>> {
+    private func expandKey(_ key:Key, variant:Variant) -> Array<Array<UInt32>> {
 
         func convertExpandedKey(_ expanded:Array<UInt8>) -> Array<Array<UInt32>> {
             var arr = Array<UInt32>()
@@ -492,7 +492,7 @@ extension AES: Cipher {
         }
 
         if blockMode.options.contains(.PaddingRequired) && (out.count % AES.blockSize != 0) {
-            throw Error.dataPaddingRequired
+            throw ErrorProblem.dataPaddingRequired
         }
 
         return out
@@ -500,7 +500,7 @@ extension AES: Cipher {
 
     public func decrypt(_ bytes:Array<UInt8>) throws -> Array<UInt8> {
         if blockMode.options.contains(.PaddingRequired) && (bytes.count % AES.blockSize != 0) {
-            throw Error.dataPaddingRequired
+            throw ErrorProblem.dataPaddingRequired
         }
 
         var oneTimeCryptor = self.makeDecryptor()

+ 3 - 3
Sources/CryptoSwift/Authenticator.swift

@@ -11,7 +11,7 @@
 */
 public enum Authenticator {
     
-    public enum Error: ErrorProtocol {
+    public enum ErrorProblem: Error {
         case authenticateError
     }
     
@@ -32,12 +32,12 @@ public enum Authenticator {
         switch (self) {
         case .Poly1305(let key):
             guard let auth = CryptoSwift.Poly1305(key: key)?.authenticate(bytes) else {
-                throw Error.authenticateError
+                throw ErrorProblem.authenticateError
             }
             return auth
         case .HMAC(let key, let variant):
             guard let auth = CryptoSwift.HMAC(key: key, variant: variant)?.authenticate(bytes) else {
-                throw Error.authenticateError
+                throw ErrorProblem.authenticateError
             }
             return auth
         }

+ 1 - 1
Sources/CryptoSwift/BlockMode/CBC.swift

@@ -25,7 +25,7 @@ struct CBCModeWorker: BlockModeWorker {
             return plaintext
         }
         prev = ciphertext
-        return ciphertext ?? []
+        return ciphertext 
     }
 
     mutating func decrypt(_ ciphertext: Array<UInt8>) -> Array<UInt8> {

+ 1 - 1
Sources/CryptoSwift/BlockMode/PCBC.swift

@@ -25,7 +25,7 @@ struct PCBCModeWorker: BlockModeWorker {
             return plaintext
         }
         prev = xor(plaintext, ciphertext)
-        return ciphertext ?? []
+        return ciphertext
     }
 
     mutating func decrypt(_ ciphertext: Array<UInt8>) -> Array<UInt8> {

+ 3 - 3
Sources/CryptoSwift/ChaCha20.swift

@@ -8,7 +8,7 @@
 
 final public class ChaCha20: BlockCipher {
     
-    public enum Error: ErrorProtocol {
+    public enum ErrorProblem: Error {
         case missingContext
     }
     
@@ -115,7 +115,7 @@ final public class ChaCha20: BlockCipher {
     private final func encryptBytes(_ message:Array<UInt8>) throws -> Array<UInt8> {
         
         guard let ctx = context else {
-            throw Error.missingContext
+            throw ErrorProblem.missingContext
         }
         
         var c:Array<UInt8> = Array<UInt8>(repeating: 0, count: message.count)
@@ -166,7 +166,7 @@ final public class ChaCha20: BlockCipher {
 extension ChaCha20: Cipher {
     public func encrypt(_ bytes:Array<UInt8>) throws -> Array<UInt8> {
         guard context != nil else {
-            throw Error.missingContext
+            throw ErrorProblem.missingContext
         }
 
         return try encryptBytes(bytes)

+ 1 - 1
Sources/CryptoSwift/Cipher.swift

@@ -6,7 +6,7 @@
 //  Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
 //
 
-public enum CipherError: ErrorProtocol {
+public enum CipherError: Error {
     case encrypt
     case decrypt
 }

+ 1 - 1
Sources/CryptoSwift/Foundation/AES+Foundation.swift

@@ -11,7 +11,7 @@ import Foundation
 extension AES {
     convenience public init(key:String, iv:String, blockMode:BlockMode = .CBC, padding: Padding = PKCS7()) throws {
         guard let kkey = key.bridge().data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)?.bytes, let iiv = iv.bridge().data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)?.bytes else {
-            throw Error.invalidKeyOrInitializationVector
+            throw ErrorProblem.invalidKeyOrInitializationVector
         }
         
         try self.init(key: kkey, iv: iiv, blockMode: blockMode, padding: padding)

+ 2 - 2
Sources/CryptoSwift/Generics.swift

@@ -59,7 +59,7 @@ func integerWith<T:Integer where T:ByteConvertible, T: BitshiftOperationsType>(_
 func arrayOfBytes<T>(value:T, length:Int? = nil) -> Array<UInt8> {
     let totalBytes = length ?? sizeof(T.self)
 
-    let valuePointer = UnsafeMutablePointer<T>(allocatingCapacity: 1)
+    let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
     valuePointer.pointee = value
     
     let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer)
@@ -69,7 +69,7 @@ func arrayOfBytes<T>(value:T, length:Int? = nil) -> Array<UInt8> {
     }
     
     valuePointer.deinitialize()
-    valuePointer.deallocateCapacity(1)
+    valuePointer.deallocate(capacity: 1)
     
     return bytes
 }

+ 8 - 8
Sources/CryptoSwift/Hash.swift

@@ -15,21 +15,21 @@ public enum Hash {
     
     public func calculate() -> Array<UInt8> {
         switch self {
-        case md5(let bytes):
+        case .md5(let bytes):
             return MD5(bytes).calculate()
-        case sha1(let bytes):
+        case .sha1(let bytes):
             return SHA1(bytes).calculate()
-        case sha224(let bytes):
+        case .sha224(let bytes):
             return SHA2(bytes, variant: .sha224).calculate32()
-        case sha256(let bytes):
+        case .sha256(let bytes):
             return SHA2(bytes, variant: .sha256).calculate32()
-        case sha384(let bytes):
+        case .sha384(let bytes):
             return SHA2(bytes, variant: .sha384).calculate64()
-        case sha512(let bytes):
+        case .sha512(let bytes):
             return SHA2(bytes, variant: .sha512).calculate64()
-        case crc32(let bytes, let seed, let reflect):
+        case .crc32(let bytes, let seed, let reflect):
             return CRC().crc32(bytes, seed: seed, reflect: reflect).bytes()
-        case crc16(let bytes, let seed):
+        case .crc16(let bytes, let seed):
             return UInt32(CRC().crc16(bytes, seed: seed)).bytes(totalBytes: 2)
         }
     }

+ 5 - 5
Sources/CryptoSwift/IntegerConvertible.swift

@@ -7,10 +7,10 @@
 //
 
 protocol BitshiftOperationsType {
-    func <<(lhs: Self, rhs: Self) -> Self
-    func >>(lhs: Self, rhs: Self) -> Self
-    func <<=(lhs: inout Self, rhs: Self)
-    func >>=(lhs: inout Self, rhs: Self)
+    static func <<(lhs: Self, rhs: Self) -> Self
+    static func >>(lhs: Self, rhs: Self) -> Self
+    static func <<=(lhs: inout Self, rhs: Self)
+    static func >>=(lhs: inout Self, rhs: Self)
 }
 
 protocol ByteConvertible {
@@ -35,4 +35,4 @@ extension UInt64 : BitshiftOperationsType, ByteConvertible {
     init(truncatingBitPattern value: UInt64) {
         self = value
     }
-}
+}

+ 6 - 4
Sources/CryptoSwift/PKCS5/PBKDF1.swift

@@ -15,7 +15,7 @@ public extension PKCS5 {
     /// some applications.
     public struct PBKDF1 {
 
-        public enum Error: ErrorProtocol {
+        public enum ErrorProblem: Error {
             case invalidInput
             case derivedKeyTooLong
         }
@@ -55,18 +55,20 @@ public extension PKCS5 {
         public init(password: Array<UInt8>, salt: Array<UInt8>, variant: Variant = .sha1, iterations: Int = 4096 /* c */, keyLength: Int? = nil /* dkLen */) throws {
             precondition(iterations > 0)
             precondition(salt.count == 8)
+            
+            let keyLength = keyLength ?? variant.size
 
             if (keyLength > variant.size) {
-                throw Error.derivedKeyTooLong
+                throw ErrorProblem.derivedKeyTooLong
             }
 
             guard let t1 = variant.calculateHash(password + salt) else {
-                throw Error.invalidInput
+                throw ErrorProblem.invalidInput
             }
 
             self.iterations = iterations
             self.variant = variant
-            self.keyLength = keyLength ?? variant.size
+            self.keyLength = keyLength
             self.t1 = t1
         }
 

+ 3 - 3
Sources/CryptoSwift/PKCS5/PBKDF2.swift

@@ -19,7 +19,7 @@ public extension PKCS5 {
     ///          DK = PBKDF2(PRF, Password, Salt, c, dkLen)
     public struct PBKDF2 {
 
-        public enum Error: ErrorProtocol {
+        public enum ErrorProblem: Error {
             case invalidInput
             case derivedKeyTooLong
         }
@@ -39,14 +39,14 @@ public extension PKCS5 {
             precondition(iterations > 0)
             
             guard let prf = HMAC(key: password, variant: variant), iterations > 0 && !password.isEmpty && !salt.isEmpty else {
-                throw Error.invalidInput
+                throw ErrorProblem.invalidInput
             }
 
             self.dkLen = keyLength ?? variant.size
             let keyLengthFinal = Double(self.dkLen)
             let hLen = Double(prf.variant.size)
             if keyLengthFinal > (pow(2,32) - 1) * hLen {
-                throw Error.derivedKeyTooLong
+                throw ErrorProblem.derivedKeyTooLong
             }
 
             self.salt = salt

+ 1 - 1
Sources/CryptoSwift/PKCS7.swift

@@ -11,7 +11,7 @@
 
 public struct PKCS7: Padding {
 
-    public enum Error: ErrorProtocol {
+    public enum ErrorProblem: Error {
         case invalidPaddingValue
     }