Преглед на файлове

Upgrade to Xcode 8 with Swift 3 and new Foundation

Marcin Krzyżanowski преди 9 години
родител
ревизия
1f82bc6c33
променени са 59 файла, в които са добавени 471 реда и са изтрити 513 реда
  1. 25 16
      CryptoSwift.xcodeproj/project.pbxproj
  2. 1 1
      CryptoSwift.xcodeproj/xcshareddata/xcschemes/CryptoSwift OSX.xcscheme
  3. 1 1
      CryptoSwift.xcodeproj/xcshareddata/xcschemes/CryptoSwift iOS.xcscheme
  4. 1 1
      CryptoSwift.xcodeproj/xcshareddata/xcschemes/CryptoSwift tvOS.xcscheme
  5. 1 1
      CryptoSwift.xcodeproj/xcshareddata/xcschemes/CryptoSwift watchOS.xcscheme
  6. 47 86
      CryptoSwiftTests/AESTests.swift
  7. 8 8
      CryptoSwiftTests/ChaCha20Tests.swift
  8. 5 5
      CryptoSwiftTests/ExtensionsTest.swift
  9. 5 5
      CryptoSwiftTests/HMACTests.swift
  10. 12 16
      CryptoSwiftTests/HashTests.swift
  11. 2 2
      CryptoSwiftTests/Helpers.swift
  12. 1 1
      CryptoSwiftTests/PBKDF.swift
  13. 3 3
      CryptoSwiftTests/Poly1305Tests.swift
  14. 5 5
      CryptoSwiftTests/RabbitTests.swift
  15. 66 66
      Sources/CryptoSwift/AES.swift
  16. 1 1
      Sources/CryptoSwift/Array+Extension.swift
  17. 7 7
      Sources/CryptoSwift/Authenticator.swift
  18. 3 3
      Sources/CryptoSwift/Bit.swift
  19. 8 8
      Sources/CryptoSwift/BlockMode/BlockMode.swift
  20. 2 2
      Sources/CryptoSwift/BlockMode/BlockModeWorker.swift
  21. 4 4
      Sources/CryptoSwift/BlockMode/CBC.swift
  22. 5 5
      Sources/CryptoSwift/BlockMode/CFB.swift
  23. 7 7
      Sources/CryptoSwift/BlockMode/CTR.swift
  24. 3 3
      Sources/CryptoSwift/BlockMode/ECB.swift
  25. 5 5
      Sources/CryptoSwift/BlockMode/OFB.swift
  26. 7 7
      Sources/CryptoSwift/BlockMode/PCBC.swift
  27. 5 5
      Sources/CryptoSwift/CRC.swift
  28. 4 4
      Sources/CryptoSwift/CSArrayType+Extensions.swift
  29. 26 26
      Sources/CryptoSwift/ChaCha20.swift
  30. 5 5
      Sources/CryptoSwift/Cipher.swift
  31. 4 4
      Sources/CryptoSwift/Cryptors.swift
  32. 3 3
      Sources/CryptoSwift/Foundation/AES+Foundation.swift
  33. 4 4
      Sources/CryptoSwift/Foundation/ArrayUInt8+Foundation.swift
  34. 3 3
      Sources/CryptoSwift/Foundation/CSArrayType+Foundation.swift
  35. 2 2
      Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift
  36. 30 38
      Sources/CryptoSwift/Foundation/Data+Extension.swift
  37. 3 3
      Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift
  38. 7 7
      Sources/CryptoSwift/Foundation/String+FoundationExtension.swift
  39. 4 4
      Sources/CryptoSwift/Foundation/Utils+Foundation.swift
  40. 22 22
      Sources/CryptoSwift/Generics.swift
  41. 6 6
      Sources/CryptoSwift/HMAC.swift
  42. 5 5
      Sources/CryptoSwift/Hash.swift
  43. 3 3
      Sources/CryptoSwift/HashProtocol.swift
  44. 6 6
      Sources/CryptoSwift/IntExtension.swift
  45. 1 1
      Sources/CryptoSwift/MD5.swift
  46. 2 2
      Sources/CryptoSwift/Multiplatform.swift
  47. 8 8
      Sources/CryptoSwift/PKCS5/PBKDF1.swift
  48. 9 9
      Sources/CryptoSwift/PKCS5/PBKDF2.swift
  49. 2 2
      Sources/CryptoSwift/PKCS7.swift
  50. 1 1
      Sources/CryptoSwift/Padding.swift
  51. 23 23
      Sources/CryptoSwift/Poly1305.swift
  52. 18 18
      Sources/CryptoSwift/Rabbit.swift
  53. 2 2
      Sources/CryptoSwift/SHA1.swift
  54. 6 6
      Sources/CryptoSwift/SHA2.swift
  55. 1 1
      Sources/CryptoSwift/String+Extension.swift
  56. 3 3
      Sources/CryptoSwift/UInt32Extension.swift
  57. 3 3
      Sources/CryptoSwift/UInt64Extension.swift
  58. 11 11
      Sources/CryptoSwift/UInt8Extension.swift
  59. 4 4
      Sources/CryptoSwift/Utils.swift

+ 25 - 16
CryptoSwift.xcodeproj/project.pbxproj

@@ -56,10 +56,10 @@
 		757BC9071C1CA56A0093AAA9 /* ChaCha20+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757BC8F91C1CA56A0093AAA9 /* ChaCha20+Foundation.swift */; };
 		757BC9081C1CA56A0093AAA9 /* ChaCha20+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757BC8F91C1CA56A0093AAA9 /* ChaCha20+Foundation.swift */; };
 		757BC9091C1CA56A0093AAA9 /* ChaCha20+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757BC8F91C1CA56A0093AAA9 /* ChaCha20+Foundation.swift */; };
-		757BC90A1C1CA56A0093AAA9 /* NSData+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757BC8FA1C1CA56A0093AAA9 /* NSData+Extension.swift */; };
-		757BC90B1C1CA56A0093AAA9 /* NSData+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757BC8FA1C1CA56A0093AAA9 /* NSData+Extension.swift */; };
-		757BC90C1C1CA56A0093AAA9 /* NSData+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757BC8FA1C1CA56A0093AAA9 /* NSData+Extension.swift */; };
-		757BC90D1C1CA56A0093AAA9 /* NSData+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757BC8FA1C1CA56A0093AAA9 /* NSData+Extension.swift */; };
+		757BC90A1C1CA56A0093AAA9 /* Data+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757BC8FA1C1CA56A0093AAA9 /* Data+Extension.swift */; };
+		757BC90B1C1CA56A0093AAA9 /* Data+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757BC8FA1C1CA56A0093AAA9 /* Data+Extension.swift */; };
+		757BC90C1C1CA56A0093AAA9 /* Data+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757BC8FA1C1CA56A0093AAA9 /* Data+Extension.swift */; };
+		757BC90D1C1CA56A0093AAA9 /* Data+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757BC8FA1C1CA56A0093AAA9 /* Data+Extension.swift */; };
 		757BC90E1C1CA56A0093AAA9 /* Rabbit+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757BC8FB1C1CA56A0093AAA9 /* Rabbit+Foundation.swift */; };
 		757BC90F1C1CA56A0093AAA9 /* Rabbit+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757BC8FB1C1CA56A0093AAA9 /* Rabbit+Foundation.swift */; };
 		757BC9101C1CA56A0093AAA9 /* Rabbit+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757BC8FB1C1CA56A0093AAA9 /* Rabbit+Foundation.swift */; };
@@ -354,7 +354,7 @@
 		757BC8F71C1CA56A0093AAA9 /* AES+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "AES+Foundation.swift"; sourceTree = "<group>"; };
 		757BC8F81C1CA56A0093AAA9 /* ArrayUInt8+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ArrayUInt8+Foundation.swift"; sourceTree = "<group>"; };
 		757BC8F91C1CA56A0093AAA9 /* ChaCha20+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ChaCha20+Foundation.swift"; sourceTree = "<group>"; };
-		757BC8FA1C1CA56A0093AAA9 /* NSData+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "NSData+Extension.swift"; sourceTree = "<group>"; };
+		757BC8FA1C1CA56A0093AAA9 /* Data+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Data+Extension.swift"; sourceTree = "<group>"; };
 		757BC8FB1C1CA56A0093AAA9 /* Rabbit+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Rabbit+Foundation.swift"; sourceTree = "<group>"; };
 		757BC8FC1C1CA56A0093AAA9 /* String+FoundationExtension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "String+FoundationExtension.swift"; sourceTree = "<group>"; };
 		757BC8FD1C1CA56A0093AAA9 /* Utils+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Utils+Foundation.swift"; sourceTree = "<group>"; };
@@ -509,7 +509,6 @@
 				757BC9281C1CA5790093AAA9 /* HashProtocol.swift */,
 				757BC9291C1CA5790093AAA9 /* HMAC.swift */,
 				757BC92B1C1CA5790093AAA9 /* IntegerConvertible.swift */,
-				757BC92C1C1CA5790093AAA9 /* IntExtension.swift */,
 				757BC92D1C1CA5790093AAA9 /* MD5.swift */,
 				757BC92E1C1CA5790093AAA9 /* Multiplatform.swift */,
 				757BC92F1C1CA5790093AAA9 /* Operators.swift */,
@@ -522,6 +521,7 @@
 				757BC9351C1CA5790093AAA9 /* SHA1.swift */,
 				757BC9361C1CA5790093AAA9 /* SHA2.swift */,
 				757BC9371C1CA5790093AAA9 /* String+Extension.swift */,
+				757BC92C1C1CA5790093AAA9 /* IntExtension.swift */,
 				757BC9381C1CA5790093AAA9 /* UInt8Extension.swift */,
 				757BC9391C1CA5790093AAA9 /* UInt32Extension.swift */,
 				757BC93A1C1CA5790093AAA9 /* UInt64Extension.swift */,
@@ -574,7 +574,7 @@
 				757BC8F71C1CA56A0093AAA9 /* AES+Foundation.swift */,
 				757BC8F81C1CA56A0093AAA9 /* ArrayUInt8+Foundation.swift */,
 				757BC8F91C1CA56A0093AAA9 /* ChaCha20+Foundation.swift */,
-				757BC8FA1C1CA56A0093AAA9 /* NSData+Extension.swift */,
+				757BC8FA1C1CA56A0093AAA9 /* Data+Extension.swift */,
 				757BC8FB1C1CA56A0093AAA9 /* Rabbit+Foundation.swift */,
 				757BC8FC1C1CA56A0093AAA9 /* String+FoundationExtension.swift */,
 				757BC8FD1C1CA56A0093AAA9 /* Utils+Foundation.swift */,
@@ -757,7 +757,7 @@
 			isa = PBXProject;
 			attributes = {
 				LastSwiftUpdateCheck = 0700;
-				LastUpgradeCheck = 0710;
+				LastUpgradeCheck = 0800;
 				ORGANIZATIONNAME = "Marcin Krzyzanowski";
 				TargetAttributes = {
 					5596BDBA1BC8F220007E38D5 = {
@@ -765,9 +765,11 @@
 					};
 					754BE45419693E190098E6F3 = {
 						CreatedOnToolsVersion = 6.0;
+						LastSwiftMigration = 0800;
 					};
 					754BE45F19693E190098E6F3 = {
 						CreatedOnToolsVersion = 6.0;
+						LastSwiftMigration = 0800;
 						TestTargetID = 754BE45419693E190098E6F3;
 					};
 				};
@@ -889,7 +891,7 @@
 				757BC9951C1CA5790093AAA9 /* Padding.swift in Sources */,
 				80545D141CA9FECD00474A99 /* Bit.swift in Sources */,
 				757BC9A51C1CA5790093AAA9 /* Rabbit.swift in Sources */,
-				757BC90B1C1CA56A0093AAA9 /* NSData+Extension.swift in Sources */,
+				757BC90B1C1CA56A0093AAA9 /* Data+Extension.swift in Sources */,
 				757BC9791C1CA5790093AAA9 /* HMAC.swift in Sources */,
 				75482EAD1CB329DF001F66A5 /* PKCS5.swift in Sources */,
 				757BC9031C1CA56A0093AAA9 /* ArrayUInt8+Foundation.swift in Sources */,
@@ -955,7 +957,7 @@
 				757BC9021C1CA56A0093AAA9 /* ArrayUInt8+Foundation.swift in Sources */,
 				757BC9781C1CA5790093AAA9 /* HMAC.swift in Sources */,
 				75482EAC1CB329DF001F66A5 /* PKCS5.swift in Sources */,
-				757BC90A1C1CA56A0093AAA9 /* NSData+Extension.swift in Sources */,
+				757BC90A1C1CA56A0093AAA9 /* Data+Extension.swift in Sources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
@@ -1035,7 +1037,7 @@
 				757BC9041C1CA56A0093AAA9 /* ArrayUInt8+Foundation.swift in Sources */,
 				757BC97A1C1CA5790093AAA9 /* HMAC.swift in Sources */,
 				75482EAF1CB329DF001F66A5 /* PKCS5.swift in Sources */,
-				757BC90C1C1CA56A0093AAA9 /* NSData+Extension.swift in Sources */,
+				757BC90C1C1CA56A0093AAA9 /* Data+Extension.swift in Sources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
@@ -1095,7 +1097,7 @@
 				757BC9971C1CA5790093AAA9 /* Padding.swift in Sources */,
 				80545D151CA9FECD00474A99 /* Bit.swift in Sources */,
 				757BC9A71C1CA5790093AAA9 /* Rabbit.swift in Sources */,
-				757BC90D1C1CA56A0093AAA9 /* NSData+Extension.swift in Sources */,
+				757BC90D1C1CA56A0093AAA9 /* Data+Extension.swift in Sources */,
 				757BC97B1C1CA5790093AAA9 /* HMAC.swift in Sources */,
 				75482EAE1CB329DF001F66A5 /* PKCS5.swift in Sources */,
 				757BC9051C1CA56A0093AAA9 /* ArrayUInt8+Foundation.swift in Sources */,
@@ -1181,6 +1183,7 @@
 				PRODUCT_NAME = CryptoSwift;
 				SDKROOT = watchos;
 				SKIP_INSTALL = YES;
+				SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
 				TARGETED_DEVICE_FAMILY = 4;
 				WATCHOS_DEPLOYMENT_TARGET = 2.0;
 			};
@@ -1210,6 +1213,7 @@
 				ENABLE_TESTABILITY = YES;
 				GCC_C_LANGUAGE_STANDARD = gnu99;
 				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_NO_COMMON_BLOCKS = YES;
 				GCC_OPTIMIZATION_LEVEL = 0;
 				GCC_PREPROCESSOR_DEFINITIONS = (
 					"DEBUG=1",
@@ -1260,6 +1264,7 @@
 				ENABLE_NS_ASSERTIONS = NO;
 				ENABLE_STRICT_OBJC_MSGSEND = YES;
 				GCC_C_LANGUAGE_STANDARD = gnu99;
+				GCC_NO_COMMON_BLOCKS = YES;
 				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
 				GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
 				GCC_WARN_UNDECLARED_SELECTOR = YES;
@@ -1298,6 +1303,7 @@
 				PRODUCT_NAME = CryptoSwift;
 				SKIP_INSTALL = YES;
 				SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+				SWIFT_VERSION = 3.0;
 			};
 			name = Debug;
 		};
@@ -1322,7 +1328,8 @@
 				PRODUCT_NAME = CryptoSwift;
 				SKIP_INSTALL = YES;
 				SWIFT_DISABLE_SAFETY_CHECKS = YES;
-				SWIFT_OPTIMIZATION_LEVEL = "-O";
+				SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+				SWIFT_VERSION = 3.0;
 			};
 			name = Release;
 		};
@@ -1345,6 +1352,7 @@
 				PRODUCT_BUNDLE_IDENTIFIER = "com.hakore.${PRODUCT_NAME:rfc1034identifier}";
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				SWIFT_OBJC_BRIDGING_HEADER = CryptoSwiftTests/Bridging.h;
+				SWIFT_VERSION = 3.0;
 			};
 			name = Debug;
 		};
@@ -1366,7 +1374,8 @@
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				SWIFT_DISABLE_SAFETY_CHECKS = YES;
 				SWIFT_OBJC_BRIDGING_HEADER = CryptoSwiftTests/Bridging.h;
-				SWIFT_OPTIMIZATION_LEVEL = "-O";
+				SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
+				SWIFT_VERSION = 3.0;
 			};
 			name = Release;
 		};
@@ -1421,7 +1430,7 @@
 				SDKROOT = appletvos;
 				SKIP_INSTALL = YES;
 				SWIFT_DISABLE_SAFETY_CHECKS = YES;
-				SWIFT_OPTIMIZATION_LEVEL = "-O";
+				SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
 				TARGETED_DEVICE_FAMILY = 3;
 				TVOS_DEPLOYMENT_TARGET = 9.0;
 				WATCHOS_DEPLOYMENT_TARGET = 2.0;
@@ -1474,7 +1483,7 @@
 				SDKROOT = macosx;
 				SKIP_INSTALL = YES;
 				SWIFT_DISABLE_SAFETY_CHECKS = YES;
-				SWIFT_OPTIMIZATION_LEVEL = "-O";
+				SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
 			};
 			name = Release;
 		};

+ 1 - 1
CryptoSwift.xcodeproj/xcshareddata/xcschemes/CryptoSwift OSX.xcscheme

@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <Scheme
-   LastUpgradeVersion = "0710"
+   LastUpgradeVersion = "0800"
    version = "1.3">
    <BuildAction
       parallelizeBuildables = "YES"

+ 1 - 1
CryptoSwift.xcodeproj/xcshareddata/xcschemes/CryptoSwift iOS.xcscheme

@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <Scheme
-   LastUpgradeVersion = "0710"
+   LastUpgradeVersion = "0800"
    version = "1.3">
    <BuildAction
       parallelizeBuildables = "YES"

+ 1 - 1
CryptoSwift.xcodeproj/xcshareddata/xcschemes/CryptoSwift tvOS.xcscheme

@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <Scheme
-   LastUpgradeVersion = "0710"
+   LastUpgradeVersion = "0800"
    version = "1.3">
    <BuildAction
       parallelizeBuildables = "YES"

+ 1 - 1
CryptoSwift.xcodeproj/xcshareddata/xcschemes/CryptoSwift watchOS.xcscheme

@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <Scheme
-   LastUpgradeVersion = "0710"
+   LastUpgradeVersion = "0800"
    version = "1.3">
    <BuildAction
       parallelizeBuildables = "YES"

+ 47 - 86
CryptoSwiftTests/AESTests.swift

@@ -20,9 +20,9 @@ final class AESTests: XCTestCase {
         let expected:Array<UInt8> = [0xae,0x8c,0x59,0x95,0xb2,0x6f,0x8e,0x3d,0xb0,0x6f,0x0a,0xa5,0xfe,0xc4,0xf0,0xc2];
         
         let aes = try! AES(key: key, iv: iv, blockMode: .CBC, padding: NoPadding())
-        let encrypted = try! aes.encrypt(bytes: input)
+        let encrypted = try! aes.encrypt(input)
         XCTAssertEqual(encrypted, expected, "encryption failed")
-        let decrypted = try! aes.decrypt(bytes: encrypted)
+        let decrypted = try! aes.decrypt(encrypted)
         XCTAssertEqual(decrypted, input, "decryption failed")
     }
 
@@ -33,9 +33,9 @@ final class AESTests: XCTestCase {
         let expected:Array<UInt8> = [0xae,0x8c,0x59,0x95,0xb2,0x6f,0x8e,0x3d,0xb0,0x6f,0x0a,0xa5,0xfe,0xc4,0xf0,0xc2];
         
         let aes = try! AES(key: key, iv: iv, blockMode: .CBC, padding: NoPadding())
-        let encrypted = try! aes.encrypt(bytes: input)
+        let encrypted = try! aes.encrypt(input)
         XCTAssertEqual(encrypted, expected, "encryption failed")
-        let decrypted = try! aes.decrypt(bytes: encrypted)
+        let decrypted = try! aes.decrypt(encrypted)
         XCTAssertEqual(decrypted, input, "decryption failed")
     }
     
@@ -44,9 +44,9 @@ final class AESTests: XCTestCase {
         let expected:Array<UInt8> = [0x69, 0xc4, 0xe0, 0xd8, 0x6a, 0x7b, 0x4, 0x30, 0xd8, 0xcd, 0xb7, 0x80, 0x70, 0xb4, 0xc5, 0x5a];
         
         let aes = try! AES(key: aesKey, blockMode: .ECB, padding: NoPadding())
-        let encrypted = try! aes.encrypt(bytes: input)
+        let encrypted = try! aes.encrypt(input)
         XCTAssertEqual(encrypted, expected, "encryption failed")
-        let decrypted = try! aes.decrypt(bytes: encrypted)
+        let decrypted = try! aes.decrypt(encrypted)
         XCTAssertEqual(decrypted, input, "decryption failed")
     }
 
@@ -57,9 +57,9 @@ final class AESTests: XCTestCase {
         let expected:Array<UInt8> = [0x76,0x49,0xab,0xac,0x81,0x19,0xb2,0x46,0xce,0xe9,0x8e,0x9b,0x12,0xe9,0x19,0x7d];
 
         let aes = try! AES(key: key, iv:iv, blockMode: .CBC, padding: NoPadding())
-        let encrypted = try! aes.encrypt(bytes: plaintext)
+        let encrypted = try! aes.encrypt(plaintext)
         XCTAssertEqual(encrypted, expected, "encryption failed")
-        let decrypted = try! aes.decrypt(bytes: encrypted)
+        let decrypted = try! aes.decrypt(encrypted)
         XCTAssertEqual(decrypted, plaintext, "decryption failed")
     }
 
@@ -70,9 +70,9 @@ final class AESTests: XCTestCase {
         let expected:Array<UInt8> = [0x76,0x49,0xab,0xac,0x81,0x19,0xb2,0x46,0xce,0xe9,0x8e,0x9b,0x12,0xe9,0x19,0x7d,0x89,0x64,0xe0,0xb1,0x49,0xc1,0x0b,0x7b,0x68,0x2e,0x6e,0x39,0xaa,0xeb,0x73,0x1c]
         
         let aes = try! AES(key: key, iv:iv, blockMode: .CBC, padding: PKCS7())
-        let encrypted = try! aes.encrypt(bytes: plaintext)
+        let encrypted = try! aes.encrypt(plaintext)
         XCTAssertEqual(encrypted, expected, "encryption failed")
-        let decrypted = try! aes.decrypt(bytes: encrypted)
+        let decrypted = try! aes.decrypt(encrypted)
         XCTAssertEqual(decrypted, plaintext, "decryption failed")
     }
 
@@ -89,7 +89,7 @@ final class AESTests: XCTestCase {
         ciphertext += try! encryptor.update(withBytes: Array(plaintext[8..<16]))
         ciphertext += try! encryptor.update(withBytes: Array(plaintext[16..<32]))
         ciphertext += try! encryptor.finish()
-        XCTAssertEqual(try! aes.encrypt(bytes: plaintext), ciphertext, "encryption failed")
+        XCTAssertEqual(try! aes.encrypt(plaintext), ciphertext, "encryption failed")
     }
 
     func testAES_encrypt_incremental() {
@@ -118,7 +118,7 @@ final class AESTests: XCTestCase {
         plaintext += try! decryptor.update(withBytes: Array(ciphertext[8..<16]))
         plaintext += try! decryptor.update(withBytes: Array(ciphertext[16..<32]))
         plaintext += try! decryptor.finish()
-        XCTAssertEqual(try! aes.decrypt(bytes: ciphertext), plaintext, "encryption failed")
+        XCTAssertEqual(try! aes.decrypt(ciphertext), plaintext, "encryption failed")
     }
 
     func testAES_encrypt_cfb() {
@@ -128,9 +128,9 @@ final class AESTests: XCTestCase {
         let expected:Array<UInt8> = [0x3b,0x3f,0xd9,0x2e,0xb7,0x2d,0xad,0x20,0x33,0x34,0x49,0xf8,0xe8,0x3c,0xfb,0x4a];
         
         let aes = try! AES(key: key, iv:iv, blockMode: .CFB, padding: NoPadding())
-        let encrypted = try! aes.encrypt(bytes: plaintext)
+        let encrypted = try! aes.encrypt(plaintext)
         XCTAssertEqual(encrypted, expected, "encryption failed")
-        let decrypted = try! aes.decrypt(bytes: encrypted)
+        let decrypted = try! aes.decrypt(encrypted)
         XCTAssertEqual(decrypted, plaintext, "decryption failed")
     }
 
@@ -139,8 +139,8 @@ final class AESTests: XCTestCase {
         let key: Array<UInt8> = [56, 118, 37, 51, 125, 78, 103, 107, 119, 40, 74, 88, 117, 112, 123, 75, 122, 89, 72, 36, 46, 91, 106, 60, 54, 110, 34, 126, 69, 126, 61, 87]
         let iv: Array<UInt8> = [69, 122, 99, 87, 83, 112, 110, 65, 54, 109, 107, 89, 73, 122, 74, 49]
         let plaintext: Array<UInt8> = [123, 10, 32, 32, 34, 67, 111, 110, 102, 105, 114, 109, 34, 32, 58, 32, 34, 116, 101, 115, 116, 105, 110, 103, 34, 44, 10, 32, 32, 34, 70, 105, 114, 115, 116, 78, 97, 109, 101, 34, 32, 58, 32, 34, 84, 101, 115, 116, 34, 44, 10, 32, 32, 34, 69, 109, 97, 105, 108, 34, 32, 58, 32, 34, 116, 101, 115, 116, 64, 116, 101, 115, 116, 46, 99, 111, 109, 34, 44, 10, 32, 32, 34, 76, 97, 115, 116, 78, 97, 109, 101, 34, 32, 58, 32, 34, 84, 101, 115, 116, 101, 114, 34, 44, 10, 32, 32, 34, 80, 97, 115, 115, 119, 111, 114, 100, 34, 32, 58, 32, 34, 116, 101, 115, 116, 105, 110, 103, 34, 44, 10, 32, 32, 34, 85, 115, 101, 114, 110, 97, 109, 101, 34, 32, 58, 32, 34, 84, 101, 115, 116, 34, 10, 125]
-        let encrypted: Array<UInt8> = try! AES(key: key, iv: iv, blockMode: .CFB).encrypt(bytes: plaintext)
-        let decrypted: Array<UInt8> = try! AES(key: key, iv: iv, blockMode: .CFB).decrypt(bytes: encrypted)
+        let encrypted: Array<UInt8> = try! AES(key: key, iv: iv, blockMode: .CFB).encrypt(plaintext)
+        let decrypted: Array<UInt8> = try! AES(key: key, iv: iv, blockMode: .CFB).decrypt(encrypted)
         XCTAssert(decrypted == plaintext, "decryption failed")
     }
 
@@ -151,9 +151,9 @@ final class AESTests: XCTestCase {
         let expected:Array<UInt8> = [0x3b,0x3f,0xd9,0x2e,0xb7,0x2d,0xad,0x20,0x33,0x34,0x49,0xf8,0xe8,0x3c,0xfb,0x4a];
 
         let aes = try! AES(key: key, iv:iv, blockMode: .OFB, padding: NoPadding())
-        let encrypted = try! aes.encrypt(bytes: plaintext)
+        let encrypted = try! aes.encrypt(plaintext)
         XCTAssertEqual(encrypted, expected, "encryption failed")
-        let decrypted = try! aes.decrypt(bytes: encrypted)
+        let decrypted = try! aes.decrypt(encrypted)
         XCTAssertEqual(decrypted, plaintext, "decryption failed")
     }
 
@@ -164,9 +164,9 @@ final class AESTests: XCTestCase {
         let expected:Array<UInt8> = [0xdc,0x7e,0x84,0xbf,0xda,0x79,0x16,0x4b,0x7e,0xcd,0x84,0x86,0x98,0x5d,0x38,0x60];
 
         let aes = try! AES(key: key, iv:iv, blockMode: .OFB, padding: NoPadding())
-        let encrypted = try! aes.encrypt(bytes: plaintext)
+        let encrypted = try! aes.encrypt(plaintext)
         XCTAssertEqual(encrypted, expected, "encryption failed")
-        let decrypted = try! aes.decrypt(bytes: encrypted)
+        let decrypted = try! aes.decrypt(encrypted)
         XCTAssertEqual(decrypted, plaintext, "decryption failed")
     }
 
@@ -177,10 +177,10 @@ final class AESTests: XCTestCase {
         let expected:Array<UInt8> = [0xf5,0x8c,0x4c,0x04,0xd6,0xe5,0xf1,0xba,0x77,0x9e,0xab,0xfb,0x5f,0x7b,0xfb,0xd6];
 
         let aes = try! AES(key: key, iv:iv, blockMode: .PCBC, padding: NoPadding())
-        let encrypted = try! aes.encrypt(bytes: plaintext)
+        let encrypted = try! aes.encrypt(plaintext)
         print(encrypted.toHexString())
         XCTAssertEqual(encrypted, expected, "encryption failed")
-        let decrypted = try! aes.decrypt(bytes: encrypted)
+        let decrypted = try! aes.decrypt(encrypted)
         XCTAssertEqual(decrypted, plaintext, "decryption failed")
     }
 
@@ -191,9 +191,9 @@ final class AESTests: XCTestCase {
         let expected:Array<UInt8> = [0x87,0x4d,0x61,0x91,0xb6,0x20,0xe3,0x26,0x1b,0xef,0x68,0x64,0x99,0x0d,0xb6,0xce]
         
         let aes = try! AES(key: key, iv:iv, blockMode: .CTR, padding: NoPadding())
-        let encrypted = try! aes.encrypt(bytes: plaintext)
+        let encrypted = try! aes.encrypt(plaintext)
         XCTAssertEqual(encrypted, expected, "encryption failed")
-        let decrypted = try! aes.decrypt(bytes: encrypted)
+        let decrypted = try! aes.decrypt(encrypted)
         XCTAssertEqual(decrypted, plaintext, "decryption failed")
     }
 
@@ -204,70 +204,31 @@ final class AESTests: XCTestCase {
         let expected:Array<UInt8> = [0x87,0x4d,0x61,0x91,0xb6,0x20,0xe3,0x26,0x1b,0xef,0x68,0x64,0x99,0x0d,0xb6,0xce,0x37]
 
         let aes = try! AES(key: key, iv:iv, blockMode: .CTR, padding: NoPadding())
-        let encrypted = try! aes.encrypt(bytes: plaintext)
+        let encrypted = try! aes.encrypt(plaintext)
         XCTAssertEqual(encrypted, expected, "encryption failed")
-        let decrypted = try! aes.decrypt(bytes: encrypted)
+        let decrypted = try! aes.decrypt(encrypted)
         XCTAssertEqual(decrypted, plaintext, "decryption failed")
     }
 
-    func testAES_encrypt_performance() {
-        let key:Array<UInt8> = [0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c];
-        let iv:Array<UInt8> = [0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F]
-        let message = Array<UInt8>(repeating: 7, count: 1024 * 1024)
-        let aes = try! AES(key: key, iv: iv, blockMode: .CBC, padding: PKCS7())
-        measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true, for: { () -> Void in
-            _ = try! aes.encrypt(bytes: message)
-        })
-    }
-
-    func testAES_decrypt_performance() {
-        let key:Array<UInt8> = [0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c];
-        let iv:Array<UInt8> = [0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F]
-        let message = Array<UInt8>(repeating: 7, count: 1024 * 1024)
-        let aes = try! AES(key: key, iv: iv, blockMode: .CBC, padding: PKCS7())
-        measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true, for: { () -> Void in
-            _ = try! aes.decrypt(bytes: message)
-        })
-    }
-
-    func testAESPerformanceCommonCrypto() {
-        let key:Array<UInt8> = [0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c];
-        let iv:Array<UInt8> = [0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F]
-        let message = Array<UInt8>(repeating: 7, count: 1024 * 1024)
-        
-        measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: false, for: { () -> Void in
-            let keyData     = NSData.with(bytes: key)
-            let keyBytes    = UnsafePointer<Void>(keyData.bytes)
-            let ivData      = NSData.with(bytes: iv)
-            let ivBytes     = UnsafePointer<Void>(ivData.bytes)
-            
-            let data = NSData.with(bytes: message)
-            let dataLength    = data.length
-            let dataBytes     = UnsafePointer<Void>(data.bytes)
-            
-            let cryptData    = NSMutableData(length: Int(dataLength) + kCCBlockSizeAES128)
-            let cryptPointer = UnsafeMutablePointer<Void>(cryptData!.mutableBytes)
-            let cryptLength  = cryptData!.length
-            
-            var numBytesEncrypted:Int = 0
-            
-            self.startMeasuring()
-            
-            CCCrypt(
-                UInt32(kCCEncrypt),
-                UInt32(kCCAlgorithmAES128),
-                UInt32(kCCOptionPKCS7Padding),
-                keyBytes,
-                key.count,
-                ivBytes,
-                dataBytes,
-                dataLength,
-                cryptPointer, cryptLength,
-                &numBytesEncrypted)
-
-            self.stopMeasuring()
-        })
-    }
+//    func testAES_encrypt_performance() {
+//        let key:Array<UInt8> = [0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c];
+//        let iv:Array<UInt8> = [0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F]
+//        let message = Array<UInt8>(repeating: 7, count: 1024 * 1024)
+//        let aes = try! AES(key: key, iv: iv, blockMode: .CBC, padding: PKCS7())
+//        measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true, for: { () -> Void in
+//            _ = try! aes.encrypt(message)
+//        })
+//    }
+//
+//    func testAES_decrypt_performance() {
+//        let key:Array<UInt8> = [0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c];
+//        let iv:Array<UInt8> = [0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F]
+//        let message = Array<UInt8>(repeating: 7, count: 1024 * 1024)
+//        let aes = try! AES(key: key, iv: iv, blockMode: .CBC, padding: PKCS7())
+//        measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true, for: { () -> Void in
+//            _ = try! aes.decrypt(message)
+//        })
+//    }
 
     func testAESWithWrongKey() {
         let key:Array<UInt8> = [0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c];
@@ -277,8 +238,8 @@ final class AESTests: XCTestCase {
 
         let aes = try! AES(key: key, iv:iv, blockMode: .CBC, padding: PKCS7())
         let aes2 = try! AES(key: key2, iv:iv, blockMode: .CBC, padding: PKCS7())
-        let encrypted = try! aes.encrypt(bytes: plaintext)
-        let decrypted = try? aes2.decrypt(bytes: encrypted)
+        let encrypted = try! aes.encrypt(plaintext)
+        let decrypted = try? aes2.decrypt(encrypted)
         XCTAssertTrue(decrypted! != plaintext, "failed")
     }
 

+ 8 - 8
CryptoSwiftTests/ChaCha20Tests.swift

@@ -48,18 +48,18 @@ final class ChaCha20Tests: XCTestCase {
             let message = Array<UInt8>(repeating: 0, count: (expectedHex.characters.count / 2))
             
             do {
-                let encrypted = try ChaCha20(key: keys[idx], iv: ivs[idx])!.encrypt(bytes: message)
-                let decrypted = try ChaCha20(key: keys[idx], iv: ivs[idx])!.decrypt(bytes: encrypted)
+                let encrypted = try ChaCha20(key: keys[idx], iv: ivs[idx])!.encrypt(message)
+                let decrypted = try ChaCha20(key: keys[idx], iv: ivs[idx])!.decrypt(encrypted)
                 XCTAssertEqual(message, decrypted, "ChaCha20 decryption failed");
                 
                 // check extension
-                let messageData = NSData(bytes: message, length: message.count);
+                let messageData = Data(bytes: message);
                 let encrypted2 = try! messageData.encrypt(cipher: ChaCha20(key: keys[idx], iv: ivs[idx])!)
                 XCTAssertNotNil(encrypted2, "")
-                XCTAssertEqual(NSData.with(bytes: encrypted), encrypted2, "ChaCha20 extension failed")
-            } catch CipherError.Encrypt {
+                XCTAssertEqual(Data(bytes: encrypted), encrypted2, "ChaCha20 extension failed")
+            } catch CipherError.encrypt {
                 XCTAssert(false, "Encryption failed")
-            } catch CipherError.Decrypt {
+            } catch CipherError.decrypt {
                 XCTAssert(false, "Decryption failed")
             } catch {
                 XCTAssert(false, "Failed")
@@ -75,7 +75,7 @@ final class ChaCha20Tests: XCTestCase {
 
         print(message.count)
 
-        let encrypted = try! ChaCha20(key: key, iv: iv)!.encrypt(bytes: message)
+        let encrypted = try! ChaCha20(key: key, iv: iv)!.encrypt(message)
         XCTAssertEqual(encrypted, expected, "Ciphertext failed")
     }
 
@@ -84,7 +84,7 @@ final class ChaCha20Tests: XCTestCase {
         let iv:Array<UInt8> = [0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F]
         let message = Array<UInt8>(repeating: 7, count: (1024 * 1024) * 1)
         measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true, for: { () -> Void in
-            let encrypted = try! ChaCha20(key: key, iv: iv)?.encrypt(bytes: message)
+            let encrypted = try! ChaCha20(key: key, iv: iv)?.encrypt(message)
             self.stopMeasuring()
             XCTAssert(encrypted != nil, "not encrypted")
         })

+ 5 - 5
CryptoSwiftTests/ExtensionsTest.swift

@@ -22,7 +22,7 @@ final class ExtensionsTest: XCTestCase {
         measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: false, for: { () -> Void in
             let message = Array<UInt8>(repeating: 7, count: 1024 * 1024)
             self.startMeasuring()
-            _ = message.chunks(chunksize: AES.blockSize)
+            _ = message.chunks(size: AES.blockSize)
             self.stopMeasuring()
         })
     }
@@ -31,13 +31,13 @@ final class ExtensionsTest: XCTestCase {
     func testIntExtension() {
         let i1:Int = 1024
         let i1Array = i1.bytes(totalBytes: 32 / 8) // 32 bit
-        let i1recovered = Int.with(bytes: i1Array)
+        let i1recovered = Int.with(i1Array)
         
         XCTAssertEqual(i1, i1recovered, "Bytes conversion failed")
         
         let i2:Int = 1024
         let i2Array = i2.bytes(totalBytes: 160 / 8) // 160 bit
-        let i2recovered = Int.with(bytes: i2Array)
+        let i2recovered = Int.with(i2Array)
         
         XCTAssertEqual(i2, i2recovered, "Bytes conversion failed")
     }
@@ -86,8 +86,8 @@ final class ExtensionsTest: XCTestCase {
     }
 
     func test_NSData_init() {
-        let data = NSData(bytes: [0x01, 0x02, 0x03])
-        XCTAssert(data.length == 3, "Invalid data")
+        let data = Data(bytes: [0x01, 0x02, 0x03])
+        XCTAssert(data.count == 3, "Invalid data")
     }
 
     func test_String_encrypt_base64() {

+ 5 - 5
CryptoSwiftTests/HMACTests.swift

@@ -24,7 +24,7 @@ final class HMACTests: XCTestCase {
         let msg:Array<UInt8> = []
         let expectedMac:Array<UInt8> = [0x74,0xe6,0xf7,0x29,0x8a,0x9c,0x2d,0x16,0x89,0x35,0xf5,0x8c,0x00,0x1b,0xad,0x88]
         
-        let hmac = try! Authenticator.HMAC(key: key, variant: .md5).authenticate(bytes: msg)
+        let hmac = try! Authenticator.HMAC(key: key, variant: .md5).authenticate(msg)
         XCTAssertEqual(hmac, expectedMac, "Invalid authentication result")
     }
     
@@ -33,7 +33,7 @@ final class HMACTests: XCTestCase {
         let msg:Array<UInt8> = []
         let expectedMac:Array<UInt8> = [0xfb,0xdb,0x1d,0x1b,0x18,0xaa,0x6c,0x08,0x32,0x4b,0x7d,0x64,0xb7,0x1f,0xb7,0x63,0x70,0x69,0x0e,0x1d]
         
-        let hmac = try! Authenticator.HMAC(key: key, variant: .sha1).authenticate(bytes: msg)
+        let hmac = try! Authenticator.HMAC(key: key, variant: .sha1).authenticate(msg)
         XCTAssertEqual(hmac, expectedMac, "Invalid authentication result")
     }
 
@@ -42,7 +42,7 @@ final class HMACTests: XCTestCase {
         let msg:Array<UInt8> = []
         let expectedMac:Array<UInt8> = [0xb6,0x13,0x67,0x9a,0x08,0x14,0xd9,0xec,0x77,0x2f,0x95,0xd7,0x78,0xc3,0x5f,0xc5,0xff,0x16,0x97,0xc4,0x93,0x71,0x56,0x53,0xc6,0xc7,0x12,0x14,0x42,0x92,0xc5,0xad]
         
-        let hmac = try! Authenticator.HMAC(key: key, variant: .sha256).authenticate(bytes: msg)
+        let hmac = try! Authenticator.HMAC(key: key, variant: .sha256).authenticate(msg)
         XCTAssertEqual(hmac, expectedMac, "Invalid authentication result")
     }
 
@@ -51,7 +51,7 @@ final class HMACTests: XCTestCase {
         let msg:Array<UInt8> = []
         let expectedMac:Array<UInt8> = [0x6c, 0x1f, 0x2e, 0xe9, 0x38, 0xfa, 0xd2, 0xe2, 0x4b, 0xd9, 0x12, 0x98, 0x47, 0x43, 0x82, 0xca, 0x21, 0x8c, 0x75, 0xdb, 0x3d, 0x83, 0xe1, 0x14, 0xb3, 0xd4, 0x36, 0x77, 0x76, 0xd1, 0x4d, 0x35, 0x51, 0x28, 0x9e, 0x75, 0xe8, 0x20, 0x9c, 0xd4, 0xb7, 0x92, 0x30, 0x28, 0x40, 0x23, 0x4a, 0xdc]
 
-        let hmac = try! Authenticator.HMAC(key: key, variant: .sha384).authenticate(bytes: msg)
+        let hmac = try! Authenticator.HMAC(key: key, variant: .sha384).authenticate(msg)
         XCTAssertEqual(hmac, expectedMac, "Invalid authentication result")
     }
 
@@ -60,7 +60,7 @@ final class HMACTests: XCTestCase {
         let msg:Array<UInt8> = []
         let expectedMac:Array<UInt8> = [0xb9, 0x36, 0xce, 0xe8, 0x6c, 0x9f, 0x87, 0xaa, 0x5d, 0x3c, 0x6f, 0x2e, 0x84, 0xcb, 0x5a, 0x42, 0x39, 0xa5, 0xfe, 0x50, 0x48, 0x0a, 0x6e, 0xc6, 0x6b, 0x70, 0xab, 0x5b, 0x1f, 0x4a, 0xc6, 0x73, 0x0c, 0x6c, 0x51, 0x54, 0x21, 0xb3, 0x27, 0xec, 0x1d, 0x69, 0x40, 0x2e, 0x53, 0xdf, 0xb4, 0x9a, 0xd7, 0x38, 0x1e, 0xb0, 0x67, 0xb3, 0x38, 0xfd, 0x7b, 0x0c, 0xb2, 0x22, 0x47, 0x22, 0x5d, 0x47]
 
-        let hmac = try! Authenticator.HMAC(key: key, variant: .sha512).authenticate(bytes: msg)
+        let hmac = try! Authenticator.HMAC(key: key, variant: .sha512).authenticate(msg)
         XCTAssertEqual(hmac, expectedMac, "Invalid authentication result")
     }
 }

+ 12 - 16
CryptoSwiftTests/HashTests.swift

@@ -25,7 +25,7 @@ final class CryptoSwiftTests: XCTestCase {
     }
 
     func testMD5_emptyString() {
-        let data:NSData = "".data(using: NSUTF8StringEncoding, allowLossyConversion: false)!
+        let data:Data = "".data(using: String.Encoding.utf8, allowLossyConversion: false)!
         XCTAssertEqual(Hash.md5(data.arrayOfBytes()).calculate(), [0xd4,0x1d,0x8c,0xd9,0x8f,0x00,0xb2,0x04,0xe9,0x80,0x09,0x98,0xec,0xf8,0x42,0x7e], "MD5 calculation failed")
     }
 
@@ -42,14 +42,10 @@ final class CryptoSwiftTests: XCTestCase {
     
     func testMD5PerformanceSwift() {
         self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: false, for: { () -> Void in
-            let buf = UnsafeMutablePointer<UInt8>(calloc(1024 * 1024, sizeof(UInt8)))
-            let data = NSData(bytes: buf, length: 1024 * 1024)
-            let arr = data.arrayOfBytes()
+            let arr = Array<UInt8>(repeating: 200, count: 1024 * 1024)
             self.startMeasuring()
-                _ = Hash.md5(arr).calculate()
+            _ = Hash.md5(arr).calculate()
             self.stopMeasuring()
-            buf?.deallocateCapacity(1024 * 1024)
-            buf?.deinitialize()
         })
     }
     
@@ -70,7 +66,7 @@ final class CryptoSwiftTests: XCTestCase {
     }
     
     func testSHA1() {
-        let data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as Array<UInt8>, length: 3)
+        let data:Data = Data(bytes: UnsafePointer<UInt8>([0x31, 0x32, 0x33] as Array<UInt8>), count: 3)
         if let hash = data.sha1() {
             XCTAssertEqual(hash.toHexString(), "40bd001563085fc35165329ea1ff5c5ecbdbbeef", "SHA1 calculation failed");
         }
@@ -81,14 +77,14 @@ final class CryptoSwiftTests: XCTestCase {
     }
     
     func testSHA224() {
-        let data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as Array<UInt8>, length: 3)
+        let data:Data = Data(bytes: UnsafePointer<UInt8>([0x31, 0x32, 0x33] as Array<UInt8>), count: 3)
         if let hash = data.sha224() {
             XCTAssertEqual(hash.toHexString(), "78d8045d684abd2eece923758f3cd781489df3a48e1278982466017f", "SHA224 calculation failed");
         }
     }
 
     func testSHA256() {
-        let data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as Array<UInt8>, length: 3)
+        let data:Data = Data(bytes: UnsafePointer<UInt8>([0x31, 0x32, 0x33] as Array<UInt8>), count: 3)
         if let hash = data.sha256() {
             XCTAssertEqual(hash.toHexString(), "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3", "SHA256 calculation failed");
         }
@@ -98,7 +94,7 @@ final class CryptoSwiftTests: XCTestCase {
     }
 
     func testSHA384() {
-        let data:NSData = NSData(bytes: [49, 50, 51] as Array<UInt8>, length: 3)
+        let data:Data = Data(bytes: UnsafePointer<UInt8>([49, 50, 51] as Array<UInt8>), count: 3)
         if let hash = data.sha384() {
             XCTAssertEqual(hash.toHexString(), "9a0a82f0c0cf31470d7affede3406cc9aa8410671520b727044eda15b4c25532a9b5cd8aaf9cec4919d76255b6bfb00f", "SHA384 calculation failed");
         }
@@ -108,7 +104,7 @@ final class CryptoSwiftTests: XCTestCase {
     }
 
     func testSHA512() {
-        let data:NSData = NSData(bytes: [49, 50, 51] as Array<UInt8>, length: 3)
+        let data:Data = Data(bytes: UnsafePointer<UInt8>([49, 50, 51] as Array<UInt8>), count: 3)
         if let hash = data.sha512() {
             XCTAssertEqual(hash.toHexString(), "3c9909afec25354d551dae21590bb26e38d53f2173b8d3dc3eee4c047e7ab1c1eb8b85103e3be7ba613b31bb5c9c36214dc9f14a42fd7a2fdb84856bca5c44c2", "SHA512 calculation failed");
         }
@@ -118,7 +114,7 @@ final class CryptoSwiftTests: XCTestCase {
     }
     
     func testCRC32() {
-        let data:NSData = NSData(bytes: [49, 50, 51] as Array<UInt8>, length: 3)
+        let data:Data = Data(bytes: UnsafePointer<UInt8>([49, 50, 51] as Array<UInt8>), count: 3)
         if let crc = data.crc32(seed: nil) {
             XCTAssertEqual(crc.toHexString(), "884863d2", "CRC32 calculation failed");
         }
@@ -128,7 +124,7 @@ final class CryptoSwiftTests: XCTestCase {
     
     func testCRC32NotReflected() {
         let bytes : Array<UInt8> = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39]
-        let data:NSData = NSData(bytes: bytes, length: bytes.count)
+        let data:Data = Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count)
         if let crc = data.crc32(seed: nil, reflect: false) {
             XCTAssertEqual(crc.toHexString(), "fc891918", "CRC32 (with reflection) calculation failed");
         }
@@ -137,12 +133,12 @@ final class CryptoSwiftTests: XCTestCase {
     }
     
     func testCRC16() {
-        let result = CRC().crc16(message: [49,50,51,52,53,54,55,56,57] as Array<UInt8>)
+        let result = CRC().crc16([49,50,51,52,53,54,55,56,57] as Array<UInt8>)
         XCTAssert(result == 0xBB3D, "CRC16 failed")
     }
     
     func testChecksum() {
-        let data:NSData = NSData(bytes: [49, 50, 51] as Array<UInt8>, length: 3)
+        let data:Data = Data(bytes: UnsafePointer<UInt8>([49, 50, 51] as Array<UInt8>), count: 3)
         XCTAssert(data.checksum() == 0x96, "Invalid checksum")
     }
 

+ 2 - 2
CryptoSwiftTests/Helpers.swift

@@ -6,7 +6,7 @@
 //  Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
 //
 
-func compareMatrix(a:Array<Array<UInt8>>, b:Array<Array<UInt8>>) -> Bool {
+func compareMatrix(_ a:Array<Array<UInt8>>, b:Array<Array<UInt8>>) -> Bool {
     for (i,arr) in a.enumerated() {
         for (j,val) in arr.enumerated() {
             if (val != b[i][j]) {
@@ -16,4 +16,4 @@ func compareMatrix(a:Array<Array<UInt8>>, b:Array<Array<UInt8>>) -> Bool {
         }
     }
     return true
-}
+}

+ 1 - 1
CryptoSwiftTests/PBKDF.swift

@@ -33,4 +33,4 @@ class PBKDF: XCTestCase {
         XCTAssert(value.toHexString() == "a53cf3df485e5cd91c17c4978048e3ca86e03cced5f748fb55eff9c1edfce7f9f490c0beee768b85c1ba14ec5750cf059fea52565ffd9e4f9dba01c5c953955e7f1012b6a9eb40629ce767982e598df9081048e22781b35187c16d61ac43f69b88630a9e80233b4c58bdc74ea5c06b5bb1b2c2a86e3ddc2775b852c4508ac85a6a47c0e23a3d8dc6e4dca583", "PBKDF2 fail")
     }
 
-}
+}

+ 3 - 3
CryptoSwiftTests/Poly1305Tests.swift

@@ -24,12 +24,12 @@ final class Poly1305Tests: XCTestCase {
         let msg:Array<UInt8> = [0x79,0x7a,0x7b,0x7c,0x7d,0x7e,0x7f,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8a,0x8b,0x8c,0x8d,0x8e,0x8f,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0x9b,0x9c,0x9d,0x9e,0x9f,0xa0,0xa1,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xab,0xac,0xad,0xae,0xaf,0xb0,0xb1,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xbb,0xbc,0xbd,0xbe,0xbf,0xc0,0xc1]
         let expectedMac:Array<UInt8> = [0xdd,0xb9,0xda,0x7d,0xdd,0x5e,0x52,0x79,0x27,0x30,0xed,0x5c,0xda,0x5f,0x90,0xa4]
         
-        let mac = try! Authenticator.Poly1305(key: key).authenticate(bytes: msg)
+        let mac = try! Authenticator.Poly1305(key: key).authenticate(msg)
         XCTAssertEqual(mac, expectedMac, "Invalid authentication result")
         
         // extensions
-        let msgData = NSData.with(bytes: msg)
+        let msgData = Data(bytes: msg)
         let mac2 = try! msgData.authenticate(with: Authenticator.Poly1305(key: key))
-        XCTAssertEqual(mac2, NSData.with(bytes: expectedMac), "Invalid authentication result")
+        XCTAssertEqual(mac2, Data(bytes: expectedMac), "Invalid authentication result")
     }
 }

+ 5 - 5
CryptoSwiftTests/RabbitTests.swift

@@ -72,9 +72,9 @@ class RabbitTests: XCTestCase {
         let plainText = Array<UInt8>(repeating: 0, count: 48)
         for (key, expectedCipher) in cases {
             let rabbit = Rabbit(key: key)!
-            let cipherText = rabbit.encrypt(bytes: plainText)
+            let cipherText = rabbit.encrypt(plainText)
             XCTAssertEqual(cipherText, expectedCipher)
-            XCTAssertEqual(rabbit.decrypt(bytes: cipherText), plainText)
+            XCTAssertEqual(rabbit.decrypt(cipherText), plainText)
         }
     }
     
@@ -111,9 +111,9 @@ class RabbitTests: XCTestCase {
         let plainText = Array<UInt8>(repeating: 0, count: 48)
         for (iv, expectedCipher) in cases {
             let rabbit = Rabbit(key: key, iv: iv)!
-            let cipherText = rabbit.encrypt(bytes: plainText)
+            let cipherText = rabbit.encrypt(plainText)
             XCTAssertEqual(cipherText, expectedCipher)
-            XCTAssertEqual(rabbit.decrypt(bytes: cipherText), plainText)
+            XCTAssertEqual(rabbit.decrypt(cipherText), plainText)
         }
     }
     
@@ -122,7 +122,7 @@ class RabbitTests: XCTestCase {
         let iv: Array<UInt8> = Array<UInt8>(repeating: 0, count: Rabbit.ivSize)
         let message = Array<UInt8>(repeating: 7, count: (1024 * 1024) * 1)
         measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true, for: { () -> Void in
-            let encrypted = Rabbit(key: key, iv: iv)?.encrypt(bytes: message)
+            let encrypted = Rabbit(key: key, iv: iv)?.encrypt(message)
             self.stopMeasuring()
             XCTAssert(encrypted != nil, "not encrypted")
         })

+ 66 - 66
Sources/CryptoSwift/AES.swift

@@ -12,9 +12,9 @@ private typealias Key = SecureBytes
 
 final public class AES: BlockCipher {
     public enum Error: ErrorProtocol {
-        case DataPaddingRequired
-        case InvalidKeyOrInitializationVector
-        case InvalidInitializationVector
+        case dataPaddingRequired
+        case invalidKeyOrInitializationVector
+        case invalidInitializationVector
     }
     
     public enum AESVariant: Int {
@@ -51,8 +51,8 @@ final public class AES: BlockCipher {
     private let key: Key
     private let iv:Array<UInt8>
     private let padding:Padding
-    private lazy var expandedKey:Array<Array<UInt32>> = self.expandKey(key: self.key, variant: self.variant)
-    private lazy var expandedKeyInv:Array<Array<UInt32>> = self.expandKeyInv(key: self.key, variant: self.variant)
+    private lazy var expandedKey:Array<Array<UInt32>> = self.expandKey(self.key, variant: self.variant)
+    private lazy var expandedKeyInv:Array<Array<UInt32>> = self.expandKeyInv(self.key, variant: self.variant)
     
     private lazy var sBoxes:(sBox:Array<UInt32>, invSBox:Array<UInt32>) = self.calculateSBox()
     private lazy var sBox:Array<UInt32> = self.sBoxes.sBox
@@ -104,17 +104,17 @@ 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 Error.invalidInitializationVector
         }
     }
 }
 
 // MARK: Private
 extension AES {
-    private func encryptBlock(block:Array<UInt8>) -> Array<UInt8>? {
+    private func encryptBlock(_ block:Array<UInt8>) -> Array<UInt8>? {
         let rounds = self.variant.Nr
         let rk = self.expandedKey
-        var b = sliceToUInt32Array(block[block.startIndex..<block.endIndex])
+        var b = sliceToUInt32Array(block[block.indices])
 
         var t = Array<UInt32>(repeating: 0, count: 4)
 
@@ -158,10 +158,10 @@ extension AES {
         t[3] = b[3] ^ rk[r][3]
 
         // rounds
-        b[0] = F1(x0: t[0], t[1], t[2], t[3]) ^ rk[rounds][0]
-        b[1] = F1(x0: t[1], t[2], t[3], t[0]) ^ rk[rounds][1]
-        b[2] = F1(x0: t[2], t[3], t[0], t[1]) ^ rk[rounds][2]
-        b[3] = F1(x0: t[3], t[0], t[1], t[2]) ^ rk[rounds][3]
+        b[0] = F1(t[0], t[1], t[2], t[3]) ^ rk[rounds][0]
+        b[1] = F1(t[1], t[2], t[3], t[0]) ^ rk[rounds][1]
+        b[2] = F1(t[2], t[3], t[0], t[1]) ^ rk[rounds][2]
+        b[3] = F1(t[3], t[0], t[1], t[2]) ^ rk[rounds][3]
 
         var out = Array<UInt8>()
         out.reserveCapacity(b.count * 4)
@@ -175,10 +175,10 @@ extension AES {
         return out
     }
 
-    private func decryptBlock(block:Array<UInt8>) -> Array<UInt8>? {
+    private func decryptBlock(_ block:Array<UInt8>) -> Array<UInt8>? {
         let rounds = self.variant.Nr
         let rk = expandedKeyInv
-        var b = sliceToUInt32Array(block[block.startIndex..<block.endIndex])
+        var b = sliceToUInt32Array(block[block.indices])
 
         var t = Array<UInt32>(repeating: 0, count: 4)
 
@@ -221,28 +221,28 @@ extension AES {
 
         // rounds
 
-        let lb00 = sBoxInv[Int(B0(x: t[0]))]
-        let lb01 = (sBoxInv[Int(B1(x: t[3]))] << 8)
-        let lb02 = (sBoxInv[Int(B2(x: t[2]))] << 16)
-        let lb03 = (sBoxInv[Int(B3(x: t[1]))] << 24)
+        let lb00 = sBoxInv[Int(B0(t[0]))]
+        let lb01 = (sBoxInv[Int(B1(t[3]))] << 8)
+        let lb02 = (sBoxInv[Int(B2(t[2]))] << 16)
+        let lb03 = (sBoxInv[Int(B3(t[1]))] << 24)
         b[0] = lb00 | lb01 | lb02 | lb03 ^ rk[0][0]
 
-        let lb10 = sBoxInv[Int(B0(x: t[1]))]
-        let lb11 = (sBoxInv[Int(B1(x: t[0]))] << 8)
-        let lb12 = (sBoxInv[Int(B2(x: t[3]))] << 16)
-        let lb13 = (sBoxInv[Int(B3(x: t[2]))] << 24)
+        let lb10 = sBoxInv[Int(B0(t[1]))]
+        let lb11 = (sBoxInv[Int(B1(t[0]))] << 8)
+        let lb12 = (sBoxInv[Int(B2(t[3]))] << 16)
+        let lb13 = (sBoxInv[Int(B3(t[2]))] << 24)
         b[1] = lb10 | lb11 | lb12 | lb13 ^ rk[0][1]
 
-        let lb20 = sBoxInv[Int(B0(x: t[2]))]
-        let lb21 = (sBoxInv[Int(B1(x: t[1]))] << 8)
-        let lb22 = (sBoxInv[Int(B2(x: t[0]))] << 16)
-        let lb23 = (sBoxInv[Int(B3(x: t[3]))] << 24)
+        let lb20 = sBoxInv[Int(B0(t[2]))]
+        let lb21 = (sBoxInv[Int(B1(t[1]))] << 8)
+        let lb22 = (sBoxInv[Int(B2(t[0]))] << 16)
+        let lb23 = (sBoxInv[Int(B3(t[3]))] << 24)
         b[2] = lb20 | lb21 | lb22 | lb23 ^ rk[0][2]
 
-        let lb30 = sBoxInv[Int(B0(x: t[3]))]
-        let lb31 = (sBoxInv[Int(B1(x: t[2]))] << 8)
-        let lb32 = (sBoxInv[Int(B2(x: t[1]))] << 16)
-        let lb33 = (sBoxInv[Int(B3(x: t[0]))] << 24)
+        let lb30 = sBoxInv[Int(B0(t[3]))]
+        let lb31 = (sBoxInv[Int(B1(t[2]))] << 8)
+        let lb32 = (sBoxInv[Int(B2(t[1]))] << 16)
+        let lb33 = (sBoxInv[Int(B3(t[0]))] << 24)
         b[3] = lb30 | lb31 | lb32 | lb33 ^ rk[0][3]
 
         var out = Array<UInt8>()
@@ -257,32 +257,32 @@ extension AES {
         return out
     }
 
-    private func expandKeyInv(key: Key, variant: AESVariant) -> Array<Array<UInt32>> {
+    private func expandKeyInv(_ key: Key, variant: AESVariant) -> Array<Array<UInt32>> {
         let rounds = variant.Nr
-        var rk2:Array<Array<UInt32>> = expandKey(key: key, variant: variant)
+        var rk2:Array<Array<UInt32>> = expandKey(key, variant: variant)
 
         for r in 1..<rounds {
             var w:UInt32
 
             w = rk2[r][0];
-            rk2[r][0] = U1[Int(B0(x: w))] ^ U2[Int(B1(x: w))] ^ U3[Int(B2(x: w))] ^ U4[Int(B3(x: w))]
+            rk2[r][0] = U1[Int(B0(w))] ^ U2[Int(B1(w))] ^ U3[Int(B2(w))] ^ U4[Int(B3(w))]
 
             w = rk2[r][1];
-            rk2[r][1] = U1[Int(B0(x: w))] ^ U2[Int(B1(x: w))] ^ U3[Int(B2(x: w))] ^ U4[Int(B3(x: w))]
+            rk2[r][1] = U1[Int(B0(w))] ^ U2[Int(B1(w))] ^ U3[Int(B2(w))] ^ U4[Int(B3(w))]
 
             w = rk2[r][2];
-            rk2[r][2] = U1[Int(B0(x: w))] ^ U2[Int(B1(x: w))] ^ U3[Int(B2(x: w))] ^ U4[Int(B3(x: w))]
+            rk2[r][2] = U1[Int(B0(w))] ^ U2[Int(B1(w))] ^ U3[Int(B2(w))] ^ U4[Int(B3(w))]
 
             w = rk2[r][3];
-            rk2[r][3] = U1[Int(B0(x: w))] ^ U2[Int(B1(x: w))] ^ U3[Int(B2(x: w))] ^ U4[Int(B3(x: w))]
+            rk2[r][3] = U1[Int(B0(w))] ^ U2[Int(B1(w))] ^ U3[Int(B2(w))] ^ U4[Int(B3(w))]
         }
 
         return rk2
     }
 
-    private func expandKey(key:Key, variant:AESVariant) -> Array<Array<UInt32>> {
+    private func expandKey(_ key:Key, variant:AESVariant) -> Array<Array<UInt32>> {
 
-        func convertExpandedKey(expanded:Array<UInt8>) -> Array<Array<UInt32>> {
+        func convertExpandedKey(_ expanded:Array<UInt8>) -> Array<Array<UInt32>> {
             var arr = Array<UInt32>()
             for idx in stride(from: expanded.startIndex, to: expanded.endIndex, by: 4) {
                 let four = Array(expanded[idx..<idx.advanced(by: 4)].reversed())
@@ -302,7 +302,7 @@ extension AES {
          * input word and applies an S-box to each of the four bytes to
          * produce an output word.
          */
-        func subWord(word:Array<UInt8>) -> Array<UInt8> {
+        func subWord(_ word:Array<UInt8>) -> Array<UInt8> {
             var result = word
             for i in 0..<4 {
                 result[i] = UInt8(sBox[Int(word[i])])
@@ -326,10 +326,10 @@ extension AES {
                 tmp[wordIdx] = w[4*(i-1)+wordIdx]
             }
             if ((i % variant.Nk) == 0) {
-                tmp = subWord(word: rotateLeft(UInt32.with(bytes: tmp), by: 8).bytes(totalBytes: sizeof(UInt32)))
+                tmp = subWord(rotateLeft(UInt32.with(bytes: tmp), by: 8).bytes(totalBytes: sizeof(UInt32)))
                 tmp[0] = tmp.first! ^ Rcon[i/variant.Nk]
             } else if (variant.Nk > 6 && (i % variant.Nk) == 4) {
-                tmp = subWord(word: tmp)
+                tmp = subWord(tmp)
             }
 
             // xor array of bytes
@@ -337,31 +337,31 @@ extension AES {
                 w[4*i+wordIdx] = w[4*(i-variant.Nk)+wordIdx]^tmp[wordIdx];
             }
         }
-        return convertExpandedKey(expanded: w)
+        return convertExpandedKey(w)
     }
 
-    private func B0(x: UInt32) -> UInt32 {
+    private func B0(_ x: UInt32) -> UInt32 {
         return x & 0xFF
     }
     
-    private func B1(x: UInt32) -> UInt32 {
+    private func B1(_ x: UInt32) -> UInt32 {
         return (x >> 8) & 0xFF
     }
     
-    private func B2(x: UInt32) -> UInt32 {
+    private func B2(_ x: UInt32) -> UInt32 {
         return (x >> 16) & 0xFF
     }
     
-    private func B3(x: UInt32) -> UInt32 {
+    private func B3(_ x: UInt32) -> UInt32 {
         return (x >> 24) & 0xFF
     }
     
-    private func F1(x0: UInt32, _ x1: UInt32, _ x2: UInt32, _ x3: UInt32) -> UInt32 {
+    private func F1(_ x0: UInt32, _ x1: UInt32, _ x2: UInt32, _ x3: UInt32) -> UInt32 {
         var result:UInt32 = 0
-        result |= UInt32(B1(x: T0[Int(x0 & 255)]))
-        result |= UInt32(B1(x: T0[Int((x1 >> 8) & 255)])) << 8
-        result |= UInt32(B1(x: T0[Int((x2 >> 16) & 255)])) << 16
-        result |= UInt32(B1(x: T0[Int(x3 >> 24)])) << 24
+        result |= UInt32(B1(T0[Int(x0 & 255)]))
+        result |= UInt32(B1(T0[Int((x1 >> 8) & 255)])) << 8
+        result |= UInt32(B1(T0[Int((x2 >> 16) & 255)])) << 16
+        result |= UInt32(B1(T0[Int(x3 >> 24)])) << 24
         return result
     }
     
@@ -399,7 +399,7 @@ extension AES {
 
         init(aes: AES) {
             self.padding = aes.padding;
-            self.worker = aes.blockMode.worker(iv: aes.iv, cipherOperation: aes.encryptBlock)
+            self.worker = aes.blockMode.worker(aes.iv, cipherOperation: aes.encryptBlock)
             self.paddingRequired = aes.blockMode.options.contains(.PaddingRequired)
         }
 
@@ -413,9 +413,9 @@ extension AES {
             //CTR does not require full block therefore work with anything
             var encrypted = Array<UInt8>()
             encrypted.reserveCapacity(self.accumulated.count)
-            for chunk in self.accumulated.chunks(chunksize: AES.blockSize) {
+            for chunk in self.accumulated.chunks(size: AES.blockSize) {
                 if (!self.paddingRequired || self.accumulated.count >= AES.blockSize) {
-                    encrypted += worker.encrypt(plaintext: chunk)
+                    encrypted += worker.encrypt(chunk)
                     self.accumulated.removeFirst(chunk.count)
                 }
             }
@@ -438,9 +438,9 @@ extension AES {
             switch (aes.blockMode) {
             case .CFB, .OFB, .CTR:
                 // CFB, OFB, CTR uses encryptBlock to decrypt
-                self.worker = aes.blockMode.worker(iv: aes.iv, cipherOperation: aes.encryptBlock)
+                self.worker = aes.blockMode.worker(aes.iv, cipherOperation: aes.encryptBlock)
             default:
-                self.worker = aes.blockMode.worker(iv: aes.iv, cipherOperation: aes.decryptBlock)
+                self.worker = aes.blockMode.worker(aes.iv, cipherOperation: aes.decryptBlock)
             }
 
             self.paddingRequired = aes.blockMode.options.contains(.PaddingRequired);
@@ -451,9 +451,9 @@ extension AES {
 
             var plaintext = Array<UInt8>()
             plaintext.reserveCapacity(self.accumulated.count)
-            for chunk in self.accumulated.chunks(chunksize: AES.blockSize) {
+            for chunk in self.accumulated.chunks(size: AES.blockSize) {
                 if (!self.paddingRequired || self.accumulated.count >= AES.blockSize) {
-                    plaintext += worker.decrypt(ciphertext: chunk)
+                    plaintext += worker.decrypt(chunk)
                     self.accumulated.removeFirst(chunk.count)
                 }
             }
@@ -481,34 +481,34 @@ extension AES: Cryptors {
 
 // MARK: Cipher
 extension AES: Cipher {
-    public func encrypt(bytes:Array<UInt8>) throws -> Array<UInt8> {
-        let chunks = bytes.chunks(chunksize: AES.blockSize)
+    public func encrypt(_ bytes:Array<UInt8>) throws -> Array<UInt8> {
+        let chunks = bytes.chunks(size: AES.blockSize)
 
         var oneTimeCryptor = self.makeEncryptor()
         var out = Array<UInt8>()
         out.reserveCapacity(bytes.count)
         for idx in chunks.indices {
-            out += try oneTimeCryptor.update(withBytes: chunks[idx], isLast: idx == chunks.endIndex)
+            out += try oneTimeCryptor.update(withBytes: chunks[idx], isLast: idx == chunks.endIndex.advanced(by: -1))
         }
 
         if blockMode.options.contains(.PaddingRequired) && (out.count % AES.blockSize != 0) {
-            throw Error.DataPaddingRequired
+            throw Error.dataPaddingRequired
         }
 
         return out
     }
 
-    public func decrypt(bytes:Array<UInt8>) throws -> Array<UInt8> {
+    public func decrypt(_ bytes:Array<UInt8>) throws -> Array<UInt8> {
         if blockMode.options.contains(.PaddingRequired) && (bytes.count % AES.blockSize != 0) {
-            throw Error.DataPaddingRequired
+            throw Error.dataPaddingRequired
         }
 
         var oneTimeCryptor = self.makeDecryptor()
-        let chunks = bytes.chunks(chunksize: AES.blockSize)
+        let chunks = bytes.chunks(size: AES.blockSize)
         var out = Array<UInt8>()
         out.reserveCapacity(bytes.count)
         for idx in chunks.indices {
-            out += try oneTimeCryptor.update(withBytes: chunks[idx], isLast: idx == chunks.endIndex)
+            out += try oneTimeCryptor.update(withBytes: chunks[idx], isLast: idx == chunks.endIndex.advanced(by: -1))
         }
         return out
     }

+ 1 - 1
Sources/CryptoSwift/Array+Extension.swift

@@ -9,7 +9,7 @@
 extension Array {
 
     /** split in chunks with given chunk size */
-    func chunks(chunksize:Int) -> [Array<Element>] {
+    func chunks(size chunksize: Int) -> [Array<Element>] {
         var words = Array<Array<Element>>()
         words.reserveCapacity(self.count / chunksize)
         for idx in stride(from: chunksize, through: self.count, by: chunksize) {

+ 7 - 7
Sources/CryptoSwift/Authenticator.swift

@@ -12,7 +12,7 @@
 public enum Authenticator {
     
     public enum Error: ErrorProtocol {
-        case AuthenticateError
+        case authenticateError
     }
     
     /**
@@ -28,18 +28,18 @@ public enum Authenticator {
     
     - returns: 16-byte message authentication code
     */
-    public func authenticate(bytes: Array<UInt8>) throws -> Array<UInt8> {
+    public func authenticate(_ bytes: Array<UInt8>) throws -> Array<UInt8> {
         switch (self) {
         case .Poly1305(let key):
-            guard let auth = CryptoSwift.Poly1305(key: key)?.authenticate(bytes: bytes) else {
-                throw Error.AuthenticateError
+            guard let auth = CryptoSwift.Poly1305(key: key)?.authenticate(bytes) else {
+                throw Error.authenticateError
             }
             return auth
         case .HMAC(let key, let variant):
-            guard let auth = CryptoSwift.HMAC(key: key, variant: variant)?.authenticate(bytes: bytes) else {
-                throw Error.AuthenticateError
+            guard let auth = CryptoSwift.HMAC(key: key, variant: variant)?.authenticate(bytes) else {
+                throw Error.authenticateError
             }
             return auth
         }
     }
-}
+}

+ 3 - 3
Sources/CryptoSwift/Bit.swift

@@ -7,12 +7,12 @@
 //
 
 enum Bit: Int {
-    case Zero
-    case One
+    case zero
+    case one
 }
 
 extension Bit {
     func inverted() -> Bit {
-        return self == .Zero ? .One : .Zero
+        return self == .zero ? .one : .zero
     }
 }

+ 8 - 8
Sources/CryptoSwift/BlockMode/BlockMode.swift

@@ -11,19 +11,19 @@ typealias CipherOperationOnBlock = (block: Array<UInt8>) -> Array<UInt8>?
 public enum BlockMode {
     case ECB, CBC, PCBC, CFB, OFB, CTR
 
-    func worker(iv: Array<UInt8>?, cipherOperation: CipherOperationOnBlock) -> BlockModeWorker {
+    func worker(_ iv: Array<UInt8>?, cipherOperation: CipherOperationOnBlock) -> BlockModeWorker {
         switch (self) {
-        case ECB:
+        case .ECB:
             return ECBModeWorker(iv: iv ?? [], cipherOperation: cipherOperation)
-        case CBC:
+        case .CBC:
             return CBCModeWorker(iv: iv ?? [], cipherOperation: cipherOperation)
-        case PCBC:
+        case .PCBC:
             return PCBCModeWorker(iv: iv ?? [], cipherOperation: cipherOperation)
-        case CFB:
+        case .CFB:
             return CFBModeWorker(iv: iv ?? [], cipherOperation: cipherOperation)
-        case OFB:
+        case .OFB:
             return OFBModeWorker(iv: iv ?? [], cipherOperation: cipherOperation)
-        case CTR:
+        case .CTR:
             return CTRModeWorker(iv: iv ?? [], cipherOperation: cipherOperation)
         }
     }
@@ -44,4 +44,4 @@ public enum BlockMode {
             return [.InitializationVectorRequired, .PaddingRequired]
         }
     }
-}
+}

+ 2 - 2
Sources/CryptoSwift/BlockMode/BlockModeWorker.swift

@@ -8,6 +8,6 @@
 
 protocol BlockModeWorker {
     var cipherOperation: CipherOperationOnBlock { get }
-    mutating func encrypt(plaintext: Array<UInt8>) -> Array<UInt8>
-    mutating func decrypt(ciphertext: Array<UInt8>) -> Array<UInt8>
+    mutating func encrypt(_ plaintext: Array<UInt8>) -> Array<UInt8>
+    mutating func decrypt(_ ciphertext: Array<UInt8>) -> Array<UInt8>
 }

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

@@ -20,19 +20,19 @@ struct CBCModeWorker: BlockModeWorker {
         self.cipherOperation = cipherOperation
     }
 
-    mutating func encrypt(plaintext: Array<UInt8>) -> Array<UInt8> {
-        guard let ciphertext = cipherOperation(block: xor(a: prev ?? iv, plaintext)) else {
+    mutating func encrypt(_ plaintext: Array<UInt8>) -> Array<UInt8> {
+        guard let ciphertext = cipherOperation(block: xor(prev ?? iv, plaintext)) else {
             return plaintext
         }
         prev = ciphertext
         return ciphertext ?? []
     }
 
-    mutating func decrypt(ciphertext: Array<UInt8>) -> Array<UInt8> {
+    mutating func decrypt(_ ciphertext: Array<UInt8>) -> Array<UInt8> {
         guard let plaintext = cipherOperation(block: ciphertext) else {
             return ciphertext
         }
-        let result = xor(a: prev ?? iv, plaintext)
+        let result = xor(prev ?? iv, plaintext)
         self.prev = ciphertext
         return result
     }

+ 5 - 5
Sources/CryptoSwift/BlockMode/CFB.swift

@@ -20,20 +20,20 @@ struct CFBModeWorker: BlockModeWorker {
         self.cipherOperation = cipherOperation
     }
 
-    mutating func encrypt(plaintext: Array<UInt8>) -> Array<UInt8> {
+    mutating func encrypt(_ plaintext: Array<UInt8>) -> Array<UInt8> {
         guard let ciphertext = cipherOperation(block: prev ?? iv) else {
             return plaintext
         }
-        prev = xor(a: plaintext, ciphertext)
+        prev = xor(plaintext, ciphertext)
         return prev ?? []
     }
 
-    mutating func decrypt(ciphertext: Array<UInt8>) -> Array<UInt8> {
+    mutating func decrypt(_ ciphertext: Array<UInt8>) -> Array<UInt8> {
         guard let plaintext = cipherOperation(block: prev ?? iv) else {
             return ciphertext
         }
-        let result = xor(a: plaintext, ciphertext)
+        let result = xor(plaintext, ciphertext)
         self.prev = ciphertext
         return result
     }
-}
+}

+ 7 - 7
Sources/CryptoSwift/BlockMode/CTR.swift

@@ -20,29 +20,29 @@ struct CTRModeWorker: BlockModeWorker {
         self.cipherOperation = cipherOperation
     }
 
-    mutating func encrypt(plaintext: Array<UInt8>) -> Array<UInt8> {
-        let nonce = buildNonce(iv: iv, counter: UInt64(counter))
+    mutating func encrypt(_ plaintext: Array<UInt8>) -> Array<UInt8> {
+        let nonce = buildNonce(iv, counter: UInt64(counter))
         counter = counter + 1
 
         guard let ciphertext = cipherOperation(block: nonce) else {
             return plaintext
         }
 
-        return xor(a: plaintext, ciphertext)
+        return xor(plaintext, ciphertext)
     }
 
-    mutating func decrypt(ciphertext: Array<UInt8>) -> Array<UInt8> {
-        let nonce = buildNonce(iv: iv, counter: UInt64(counter))
+    mutating func decrypt(_ ciphertext: Array<UInt8>) -> Array<UInt8> {
+        let nonce = buildNonce(iv, counter: UInt64(counter))
         counter = counter + 1
 
         guard let plaintext = cipherOperation(block: nonce) else {
             return ciphertext
         }
-        return xor(a: plaintext, ciphertext)
+        return xor(plaintext, ciphertext)
     }
 }
 
-private func buildNonce(iv: Array<UInt8>, counter: UInt64) -> Array<UInt8> {
+private func buildNonce(_ iv: Array<UInt8>, counter: UInt64) -> Array<UInt8> {
     let noncePartLen = AES.blockSize / 2
     let noncePrefix = Array(iv[0..<noncePartLen])
     let nonceSuffix = Array(iv[noncePartLen..<iv.count])

+ 3 - 3
Sources/CryptoSwift/BlockMode/ECB.swift

@@ -16,14 +16,14 @@ struct ECBModeWorker: BlockModeWorker {
         self.cipherOperation = cipherOperation
     }
 
-    mutating func encrypt(plaintext: Array<UInt8>) -> Array<UInt8> {
+    mutating func encrypt(_ plaintext: Array<UInt8>) -> Array<UInt8> {
         guard let ciphertext = cipherOperation(block: plaintext) else {
             return plaintext
         }
         return ciphertext
     }
 
-    mutating func decrypt(ciphertext: Array<UInt8>) -> Array<UInt8> {
-        return encrypt(plaintext: ciphertext)
+    mutating func decrypt(_ ciphertext: Array<UInt8>) -> Array<UInt8> {
+        return encrypt(ciphertext)
     }
 }

+ 5 - 5
Sources/CryptoSwift/BlockMode/OFB.swift

@@ -20,20 +20,20 @@ struct OFBModeWorker: BlockModeWorker {
         self.cipherOperation = cipherOperation
     }
 
-    mutating func encrypt(plaintext: Array<UInt8>) -> Array<UInt8> {
+    mutating func encrypt(_ plaintext: Array<UInt8>) -> Array<UInt8> {
         guard let ciphertext = cipherOperation(block: prev ?? iv) else {
             return plaintext
         }
         prev = ciphertext
-        return xor(a: plaintext, ciphertext)
+        return xor(plaintext, ciphertext)
     }
 
-    mutating func decrypt(ciphertext: Array<UInt8>) -> Array<UInt8> {
+    mutating func decrypt(_ ciphertext: Array<UInt8>) -> Array<UInt8> {
         guard let decrypted = cipherOperation(block: prev ?? iv) else {
             return ciphertext
         }
-        let plaintext = xor(a: decrypted, ciphertext)
+        let plaintext = xor(decrypted, ciphertext)
         self.prev = decrypted
         return plaintext
     }
-}
+}

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

@@ -20,20 +20,20 @@ struct PCBCModeWorker: BlockModeWorker {
         self.cipherOperation = cipherOperation
     }
 
-    mutating func encrypt(plaintext: Array<UInt8>) -> Array<UInt8> {
-        guard let ciphertext = cipherOperation(block: xor(a: prev ?? iv, plaintext)) else {
+    mutating func encrypt(_ plaintext: Array<UInt8>) -> Array<UInt8> {
+        guard let ciphertext = cipherOperation(block: xor(prev ?? iv, plaintext)) else {
             return plaintext
         }
-        prev = xor(a: plaintext, ciphertext)
+        prev = xor(plaintext, ciphertext)
         return ciphertext ?? []
     }
 
-    mutating func decrypt(ciphertext: Array<UInt8>) -> Array<UInt8> {
+    mutating func decrypt(_ ciphertext: Array<UInt8>) -> Array<UInt8> {
         guard let plaintext = cipherOperation(block: ciphertext) else {
             return ciphertext
         }
-        let result = xor(a: prev ?? iv, plaintext)
-        self.prev = xor(a: plaintext, ciphertext)
+        let result = xor(prev ?? iv, plaintext)
+        self.prev = xor(plaintext, ciphertext)
         return result
     }
-}
+}

+ 5 - 5
Sources/CryptoSwift/CRC.swift

@@ -74,18 +74,18 @@ final class CRC {
         0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
         0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040]
     
-    func crc32(message:Array<UInt8>, seed: UInt32? = nil, reflect : Bool = true) -> UInt32 {
+    func crc32(_ message:Array<UInt8>, seed: UInt32? = nil, reflect : Bool = true) -> UInt32 {
         var crc:UInt32 = seed != nil ? seed! : 0xffffffff
         for chunk in BytesSequence(chunkSize: 256, data: message) {
             for b in chunk {
-                let idx = Int((crc ^ UInt32(reflect ? b : reverse(uint8: b))) & 0xff)
+                let idx = Int((crc ^ UInt32(reflect ? b : reversed(b))) & 0xff)
                 crc = (crc >> 8) ^ CRC.table32[idx]
             }
         }
-        return (reflect ? crc : reverse(uint32: crc)) ^ 0xffffffff
+        return (reflect ? crc : reversed(crc)) ^ 0xffffffff
     }
     
-    func crc16(message:Array<UInt8>, seed: UInt16? = nil) -> UInt16 {
+    func crc16(_ message:Array<UInt8>, seed: UInt16? = nil) -> UInt16 {
         var crc:UInt16 = seed != nil ? seed! : 0x0000
         for chunk in BytesSequence(chunkSize: 256, data: message) {
             for b in chunk {
@@ -94,4 +94,4 @@ final class CRC {
         }
         return crc
     }
-}
+}

+ 4 - 4
Sources/CryptoSwift/CSArrayType+Extensions.swift

@@ -56,14 +56,14 @@ public extension CSArrayType where Iterator.Element == UInt8 {
     }
     
     public func encrypt(cipher: Cipher) throws -> [Iterator.Element] {
-        return try cipher.encrypt(bytes: cs_arrayValue())
+        return try cipher.encrypt(cs_arrayValue())
     }
 
     public func decrypt(cipher: Cipher) throws -> [Iterator.Element] {
-        return try cipher.decrypt(bytes: cs_arrayValue())
+        return try cipher.decrypt(cs_arrayValue())
     }
     
     public func authenticate(with authenticator: Authenticator) throws -> [Iterator.Element] {
-        return try authenticator.authenticate(bytes: cs_arrayValue())
+        return try authenticator.authenticate(cs_arrayValue())
     }
-}
+}

+ 26 - 26
Sources/CryptoSwift/ChaCha20.swift

@@ -9,7 +9,7 @@
 final public class ChaCha20: BlockCipher {
     
     public enum Error: ErrorProtocol {
-        case MissingContext
+        case missingContext
     }
     
     static let blockSize = 64 // 512 / 8
@@ -27,14 +27,14 @@ final public class ChaCha20: BlockCipher {
     }
     
     public init?(key:Array<UInt8>, iv:Array<UInt8>) {
-        if let c = contextSetup(iv: iv, key: key) {
+        if let c = contextSetup(iv, key: key) {
             context = c
         } else {
             return nil
         }
     }
     
-    private final func wordToByte(input:Array<UInt32> /* 64 */) -> Array<UInt8>? /* 16 */ {
+    private final func wordToByte(_ input:Array<UInt32> /* 64 */) -> Array<UInt8>? /* 16 */ {
         if (input.count != stateSize) {
             return nil;
         }
@@ -42,14 +42,14 @@ final public class ChaCha20: BlockCipher {
         var x = input
 
         for _ in 0..<10 {
-            quarterround(a: &x[0], &x[4], &x[8], &x[12])
-            quarterround(a: &x[1], &x[5], &x[9],  &x[13])
-            quarterround(a: &x[2], &x[6], &x[10], &x[14])
-            quarterround(a: &x[3], &x[7], &x[11], &x[15])
-            quarterround(a: &x[0], &x[5], &x[10], &x[15])
-            quarterround(a: &x[1], &x[6], &x[11], &x[12])
-            quarterround(a: &x[2], &x[7], &x[8],  &x[13])
-            quarterround(a: &x[3], &x[4], &x[9],  &x[14])
+            quarterround(&x[0], &x[4], &x[8], &x[12])
+            quarterround(&x[1], &x[5], &x[9],  &x[13])
+            quarterround(&x[2], &x[6], &x[10], &x[14])
+            quarterround(&x[3], &x[7], &x[11], &x[15])
+            quarterround(&x[0], &x[5], &x[10], &x[15])
+            quarterround(&x[1], &x[6], &x[11], &x[12])
+            quarterround(&x[2], &x[7], &x[8],  &x[13])
+            quarterround(&x[3], &x[4], &x[9],  &x[14])
         }
 
         var output = Array<UInt8>()
@@ -63,7 +63,7 @@ final public class ChaCha20: BlockCipher {
         return output;
     }
         
-    private func contextSetup(iv:Array<UInt8>, key:Array<UInt8>) -> Context? {
+    private func contextSetup(_ iv:Array<UInt8>, key:Array<UInt8>) -> Context? {
         let ctx = Context()
         let kbits = key.count * 8
         
@@ -74,7 +74,7 @@ final public class ChaCha20: BlockCipher {
         // 4 - 8
         for i in 0..<4 {
             let start = i * 4
-            ctx.input[i + 4] = wordNumber(bytes: key[start..<(start + 4)])
+            ctx.input[i + 4] = wordNumber(key[start..<(start + 4)])
         }
         
         var addPos = 0;
@@ -100,22 +100,22 @@ final public class ChaCha20: BlockCipher {
             let start = addPos + (i*4)
             
             let bytes = key[start..<(start + 4)]
-            ctx.input[i + 8] = wordNumber(bytes: bytes)
+            ctx.input[i + 8] = wordNumber(bytes)
         }
 
         // iv
         ctx.input[12] = 0
         ctx.input[13] = 0
-        ctx.input[14] = wordNumber(bytes: iv[0..<4])
-        ctx.input[15] = wordNumber(bytes: iv[4..<8])
+        ctx.input[14] = wordNumber(iv[0..<4])
+        ctx.input[15] = wordNumber(iv[4..<8])
         
         return ctx
     }
     
-    private final func encryptBytes(message:Array<UInt8>) throws -> Array<UInt8> {
+    private final func encryptBytes(_ message:Array<UInt8>) throws -> Array<UInt8> {
         
         guard let ctx = context else {
-            throw Error.MissingContext
+            throw Error.missingContext
         }
         
         var c:Array<UInt8> = Array<UInt8>(repeating: 0, count: message.count)
@@ -125,7 +125,7 @@ final public class ChaCha20: BlockCipher {
         var bytes = message.count
         
         while (true) {
-            if let output = wordToByte(input: ctx.input) {
+            if let output = wordToByte(ctx.input) {
                 ctx.input[12] = ctx.input[12] &+ 1
                 if (ctx.input[12] == 0) {
                     ctx.input[13] = ctx.input[13] &+ 1
@@ -147,7 +147,7 @@ final public class ChaCha20: BlockCipher {
         }
     }
     
-    private final func quarterround(a:inout UInt32, _ b:inout UInt32, _ c:inout UInt32, _ d:inout UInt32) {
+    private final func quarterround(_ a:inout UInt32, _ b:inout UInt32, _ c:inout UInt32, _ d:inout UInt32) {
         a = a &+ b
         d = rotateLeft((d ^ a), by: 16) //FIXME: WAT? n:
         
@@ -164,23 +164,23 @@ final public class ChaCha20: BlockCipher {
 
 // MARK: Cipher
 extension ChaCha20: Cipher {
-    public func encrypt(bytes:Array<UInt8>) throws -> Array<UInt8> {
+    public func encrypt(_ bytes:Array<UInt8>) throws -> Array<UInt8> {
         guard context != nil else {
-            throw Error.MissingContext
+            throw Error.missingContext
         }
 
-        return try encryptBytes(message: bytes)
+        return try encryptBytes(bytes)
     }
 
-    public func decrypt(bytes:Array<UInt8>) throws -> Array<UInt8> {
-        return try encrypt(bytes: bytes)
+    public func decrypt(_ bytes:Array<UInt8>) throws -> Array<UInt8> {
+        return try encrypt(bytes)
     }
 }
 
 // MARK: Helpers
 
 /// Change array to number. It's here because arrayOfBytes is too slow
-private func wordNumber(bytes:ArraySlice<UInt8>) -> UInt32 {
+private func wordNumber(_ bytes:ArraySlice<UInt8>) -> UInt32 {
     var value:UInt32 = 0
     for i:UInt32 in 0..<4 {
         let j = bytes.startIndex + Int(i)

+ 5 - 5
Sources/CryptoSwift/Cipher.swift

@@ -7,8 +7,8 @@
 //
 
 public enum CipherError: ErrorProtocol {
-    case Encrypt
-    case Decrypt
+    case encrypt
+    case decrypt
 }
 
 public protocol Cipher {
@@ -16,11 +16,11 @@ public protocol Cipher {
     ///
     /// - parameter bytes: Plaintext data
     /// - returns: Encrypted data
-    func encrypt(bytes: Array<UInt8>) throws -> Array<UInt8>
+    func encrypt(_ bytes: Array<UInt8>) throws -> Array<UInt8>
 
     /// Decrypt given bytes at once
     ///
     /// - parameter bytes: Ciphertext data
     /// - returns: Plaintext data
-    func decrypt(bytes: Array<UInt8>) throws -> Array<UInt8>
-}
+    func decrypt(_ bytes: Array<UInt8>) throws -> Array<UInt8>
+}

+ 4 - 4
Sources/CryptoSwift/Cryptors.swift

@@ -23,15 +23,15 @@ public protocol Cryptors {
     func makeDecryptor() -> DecryptorType
 
     /// Generate array of random bytes. Helper function.
-    static func randomIV(blockSize:Int) -> Array<UInt8>
+    static func randomIV(_ blockSize:Int) -> Array<UInt8>
 }
 
 extension Cryptors {
-    static public func randomIV(blockSize:Int) -> Array<UInt8> {
+    static public func randomIV(_ blockSize:Int) -> Array<UInt8> {
         var randomIV:Array<UInt8> = Array<UInt8>();
         for _ in 0..<blockSize {
-            randomIV.append(UInt8(truncatingBitPattern: cs_arc4random_uniform(upperBound: 256)));
+            randomIV.append(UInt8(truncatingBitPattern: cs_arc4random_uniform(256)));
         }
         return randomIV
     }
-}
+}

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

@@ -10,10 +10,10 @@ 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: NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes(), let iiv = iv.bridge().data(using: NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes() else {
-            throw Error.InvalidKeyOrInitializationVector
+        guard let kkey = key.bridge().data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)?.arrayOfBytes(), let iiv = iv.bridge().data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)?.arrayOfBytes() else {
+            throw Error.invalidKeyOrInitializationVector
         }
         
         try self.init(key: kkey, iv: iiv, blockMode: blockMode, padding: padding)
     }
-}
+}

+ 4 - 4
Sources/CryptoSwift/Foundation/ArrayUInt8+Foundation.swift

@@ -9,8 +9,8 @@
 import Foundation
 
 extension Array where Element: _UInt8Type {
-    public init(_ data: NSData) {
-        self = Array<Element>(repeating: Element.Zero(), count: data.length)
-        data.getBytes(&self, length: self.count)
+    public init(_ data: Data) {
+        self = Array<Element>(repeating: Element.Zero(), count: data.count)
+        (data as NSData).getBytes(&self, length: self.count)
     }
-}
+}

+ 3 - 3
Sources/CryptoSwift/Foundation/CSArrayType+Foundation.swift

@@ -14,16 +14,16 @@ public extension CSArrayType where Iterator.Element == UInt8 {
             return nil
         }
 
-        return NSData(bytes: bytesArray).base64EncodedString([])
+        return Data(bytes: bytesArray).base64EncodedString()
     }
 
     public init(base64: String) {
         self.init()
 
-        guard let decodedData = NSData(base64Encoded: base64, options: []) else {
+        guard let decodedData = Data(base64Encoded: base64) else {
             return
         }
 
         self.append(contentsOf: decodedData.arrayOfBytes())
     }
-}
+}

+ 2 - 2
Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift

@@ -10,9 +10,9 @@ import Foundation
 
 extension ChaCha20 {
     convenience public init?(key:String, iv:String) {
-        guard let kkey = key.bridge().data(using: NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes(), let iiv = iv.bridge().data(using: NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes() else {
+        guard let kkey = key.bridge().data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)?.arrayOfBytes(), let iiv = iv.bridge().data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)?.arrayOfBytes() else {
             return nil
         }
         self.init(key: kkey, iv: iiv)
     }
-}
+}

+ 30 - 38
Sources/CryptoSwift/Foundation/NSData+Extension.swift → Sources/CryptoSwift/Foundation/Data+Extension.swift

@@ -11,13 +11,13 @@ import Foundation
 extension NSMutableData {
     
     /** Convenient way to append bytes */
-    internal func appendBytes(arrayOfBytes: Array<UInt8>) {
+    internal func appendBytes(_ arrayOfBytes: Array<UInt8>) {
         self.append(arrayOfBytes, length: arrayOfBytes.count)
     }
     
 }
 
-extension NSData {
+extension Data {
 
     /// Two octet checksum as defined in RFC-4880. Sum of all octets, mod 65536
     public func checksum() -> UInt16 {
@@ -30,81 +30,73 @@ extension NSData {
         return UInt16(s)
     }
     
-    @nonobjc public func md5() -> NSData {
+    public func md5() -> Data {
         let result = Hash.md5(self.arrayOfBytes()).calculate()
-        return NSData.with(bytes: result)
+        return Data(bytes: result)
     }
 
-    public func sha1() -> NSData? {
+    public func sha1() -> Data? {
         let result = Hash.sha1(self.arrayOfBytes()).calculate()
-        return NSData.with(bytes: result)
+        return Data(bytes: result)
     }
 
-    public func sha224() -> NSData? {
+    public func sha224() -> Data? {
         let result = Hash.sha224(self.arrayOfBytes()).calculate()
-        return NSData.with(bytes: result)
+        return Data(bytes: result)
     }
 
-    public func sha256() -> NSData? {
+    public func sha256() -> Data? {
         let result = Hash.sha256(self.arrayOfBytes()).calculate()
-        return NSData.with(bytes: result)
+        return Data(bytes: result)
     }
 
-    public func sha384() -> NSData? {
+    public func sha384() -> Data? {
         let result = Hash.sha384(self.arrayOfBytes()).calculate()
-        return NSData.with(bytes: result)
+        return Data(bytes: result)
     }
 
-    public func sha512() -> NSData? {
+    public func sha512() -> Data? {
         let result = Hash.sha512(self.arrayOfBytes()).calculate()
-        return NSData.with(bytes: result)
+        return Data(bytes: result)
     }
 
-    public func crc32(seed: UInt32? = nil, reflect : Bool = true) -> NSData? {
+    public func crc32(seed: UInt32? = nil, reflect : Bool = true) -> Data? {
         let result = Hash.crc32(self.arrayOfBytes(), seed: seed, reflect: reflect).calculate()
-        return NSData.with(bytes: result)
+        return Data(bytes: result)
     }
 
-    public func crc16(seed: UInt16? = nil) -> NSData? {
+    public func crc16(seed: UInt16? = nil) -> Data? {
         let result = Hash.crc16(self.arrayOfBytes(), seed: seed).calculate()
-        return NSData.with(bytes: result)
+        return Data(bytes: result)
     }
 
-    public func encrypt(cipher: Cipher) throws -> NSData {
-        let encrypted = try cipher.encrypt(bytes: self.arrayOfBytes())
-        return NSData.with(bytes: encrypted)
+    public func encrypt(cipher: Cipher) throws -> Data {
+        let encrypted = try cipher.encrypt(self.arrayOfBytes())
+        return Data(bytes: encrypted)
     }
 
-    public func decrypt(cipher: Cipher) throws -> NSData {
-        let decrypted = try cipher.decrypt(bytes: self.arrayOfBytes())
-        return NSData.with(bytes: decrypted)
+    public func decrypt(cipher: Cipher) throws -> Data {
+        let decrypted = try cipher.decrypt(self.arrayOfBytes())
+        return Data(bytes: decrypted)
     }
     
-    public func authenticate(with authenticator: Authenticator) throws -> NSData {
-        let result = try authenticator.authenticate(bytes: self.arrayOfBytes())
-        return NSData.with(bytes: result)
+    public func authenticate(with authenticator: Authenticator) throws -> Data {
+        let result = try authenticator.authenticate(self.arrayOfBytes())
+        return Data(bytes: result)
     }
 }
 
-extension NSData {
+extension Data {
     
     public func toHexString() -> String {
         return self.arrayOfBytes().toHexString()
     }
     
     public func arrayOfBytes() -> Array<UInt8> {
-        let count = self.length / sizeof(UInt8)
+        let count = self.count / sizeof(UInt8)
         var bytesArray = Array<UInt8>(repeating: 0, count: count)
-        self.getBytes(&bytesArray, length:count * sizeof(UInt8))
+        (self as NSData).getBytes(&bytesArray, length:count * sizeof(UInt8))
         return bytesArray
     }
-
-    public convenience init(bytes: Array<UInt8>) {
-        self.init(data: NSData.with(bytes: bytes))
-    }
-    
-    class public func with(bytes: Array<UInt8>) -> NSData {
-        return NSData(bytes: bytes, length: bytes.count)
-    }
 }
 

+ 3 - 3
Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift

@@ -10,7 +10,7 @@ import Foundation
 
 extension Rabbit {
     convenience public init?(key: String) {
-        guard let kkey = key.bridge().data(using: NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes() else {
+        guard let kkey = key.bridge().data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)?.arrayOfBytes() else {
             return nil
         }
         self.init(key: kkey)
@@ -18,8 +18,8 @@ extension Rabbit {
     }
     
     convenience public init?(key: String, iv: String) {
-        guard let kkey = key.bridge().data(using: NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes(),
-            let iiv = iv.bridge().data(using: NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes()
+        guard let kkey = key.bridge().data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)?.arrayOfBytes(),
+            let iiv = iv.bridge().data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)?.arrayOfBytes()
             else {
                 return nil
         }

+ 7 - 7
Sources/CryptoSwift/Foundation/String+FoundationExtension.swift

@@ -12,25 +12,25 @@ extension String {
 
     /// Return Base64 back to String
     public func decryptBase64ToString(cipher: Cipher) throws -> String {
-        guard let decodedData = NSData(base64Encoded: self, options: []) else {
-            throw CipherError.Decrypt
+        guard let decodedData = Data(base64Encoded: self, options: []) else {
+            throw CipherError.decrypt
         }
 
         let decrypted = try decodedData.decrypt(cipher: cipher)
 
-        if let decryptedString = String(data: decrypted, encoding: NSUTF8StringEncoding) {
+        if let decryptedString = String(data: decrypted, encoding: String.Encoding.utf8) {
             return decryptedString
         }
 
-        throw CipherError.Decrypt
+        throw CipherError.decrypt
     }
 
     public func decryptBase64(cipher: Cipher) throws -> Array<UInt8> {
-        guard let decodedData = NSData(base64Encoded: self, options: []) else {
-            throw CipherError.Decrypt
+        guard let decodedData = Data(base64Encoded: self, options: []) else {
+            throw CipherError.decrypt
         }
 
         return try decodedData.decrypt(cipher: cipher).arrayOfBytes()
     }
 
-}
+}

+ 4 - 4
Sources/CryptoSwift/Foundation/Utils+Foundation.swift

@@ -8,13 +8,13 @@
 
 import Foundation
 
-func perf(text: String, closure: () -> ()) {
-    let measurementStart = NSDate();
+func perf(_ text: String, closure: () -> ()) {
+    let measurementStart = Date();
     
     closure()
     
-    let measurementStop = NSDate();
+    let measurementStop = Date();
     let executionTime = measurementStop.timeIntervalSince(measurementStart)
     
     print("\(text) \(executionTime)");
-}
+}

+ 22 - 22
Sources/CryptoSwift/Generics.swift

@@ -20,11 +20,11 @@ extension UInt32:Initiable {}
 extension UInt64:Initiable {}
 
 /** build bit pattern from array of bits */
-func integerFrom<T: UnsignedInteger>(bits: Array<Bit>) -> T
+func integerFrom<T: UnsignedInteger>(_ bits: Array<Bit>) -> T
 {
     var bitPattern:T = 0
     for idx in bits.indices {
-        if bits[idx] == Bit.One {
+        if bits[idx] == Bit.one {
             let bit = T(UIntMax(1) << UIntMax(idx))
             bitPattern = bitPattern | bit
         }
@@ -34,7 +34,7 @@ func integerFrom<T: UnsignedInteger>(bits: Array<Bit>) -> T
 
 /// Initialize integer from array of bytes.
 /// This method may be slow
-func integerWith<T:Integer where T:ByteConvertible, T: BitshiftOperationsType>(bytes: Array<UInt8>) -> T {
+func integerWith<T:Integer where T:ByteConvertible, T: BitshiftOperationsType>(_ bytes: Array<UInt8>) -> T {
     var bytes = bytes.reversed() as Array<UInt8> //FIXME: check it this is equivalent of Array(...)
     if bytes.count < sizeof(T) {
         let paddingCount = sizeof(T) - bytes.count
@@ -91,7 +91,7 @@ func << <T:UnsignedInteger>(lhs: T, rhs: Int) -> UInt {
 
 // Generic function itself
 // FIXME: this generic function is not as generic as I would. It crashes for smaller types
-func shiftLeft<T: SignedInteger where T: Initiable>(value: T, by count: Int) -> T {
+func shiftLeft<T: SignedInteger where T: Initiable>(_ value: T, by count: Int) -> T {
     if (value == 0) {
         return 0;
     }
@@ -115,39 +115,39 @@ func shiftLeft<T: SignedInteger where T: Initiable>(value: T, by count: Int) ->
 }
 
 // for any f*** other Integer type - this part is so non-Generic
-func shiftLeft(value: UInt, by count: Int) -> UInt {
-    return UInt(shiftLeft(value: Int(value), by: count))
+func shiftLeft(_ value: UInt, by count: Int) -> UInt {
+    return UInt(shiftLeft(Int(value), by: count))
 }
 
-func shiftLeft(value: UInt8, by count: Int) -> UInt8 {
-    return UInt8(shiftLeft(value: UInt(value), by: count))
+func shiftLeft(_ value: UInt8, by count: Int) -> UInt8 {
+    return UInt8(shiftLeft(UInt(value), by: count))
 }
 
-func shiftLeft(value: UInt16, by count: Int) -> UInt16 {
-    return UInt16(shiftLeft(value: UInt(value), by: count))
+func shiftLeft(_ value: UInt16, by count: Int) -> UInt16 {
+    return UInt16(shiftLeft(UInt(value), by: count))
 }
 
-func shiftLeft(value: UInt32, by count: Int) -> UInt32 {
-    return UInt32(shiftLeft(value: UInt(value), by: count))
+func shiftLeft(_ value: UInt32, by count: Int) -> UInt32 {
+    return UInt32(shiftLeft(UInt(value), by: count))
 }
 
-func shiftLeft(value: UInt64, by count: Int) -> UInt64 {
-    return UInt64(shiftLeft(value: UInt(value), by: count))
+func shiftLeft(_ value: UInt64, by count: Int) -> UInt64 {
+    return UInt64(shiftLeft(UInt(value), by: count))
 }
 
-func shiftLeft(value: Int8, by count: Int) -> Int8 {
-    return Int8(shiftLeft(value: Int(value), by: count))
+func shiftLeft(_ value: Int8, by count: Int) -> Int8 {
+    return Int8(shiftLeft(Int(value), by: count))
 }
 
-func shiftLeft(value: Int16, by count: Int) -> Int16 {
-    return Int16(shiftLeft(value: Int(value), by: count))
+func shiftLeft(_ value: Int16, by count: Int) -> Int16 {
+    return Int16(shiftLeft(Int(value), by: count))
 }
 
-func shiftLeft(value: Int32, by count: Int) -> Int32 {
-    return Int32(shiftLeft(value: Int(value), by: count))
+func shiftLeft(_ value: Int32, by count: Int) -> Int32 {
+    return Int32(shiftLeft(Int(value), by: count))
 }
 
-func shiftLeft(value: Int64, by count: Int) -> Int64 {
-    return Int64(shiftLeft(value: Int(value), by: count))
+func shiftLeft(_ value: Int64, by count: Int) -> Int64 {
+    return Int64(shiftLeft(Int(value), by: count))
 }
 

+ 6 - 6
Sources/CryptoSwift/HMAC.swift

@@ -26,7 +26,7 @@ final public class HMAC {
             }
         }
         
-        func calculateHash(bytes:Array<UInt8>) -> Array<UInt8>? {
+        func calculateHash(_ bytes:Array<UInt8>) -> Array<UInt8>? {
             switch (self) {
             case .sha1:
                 return Hash.sha1(bytes).calculate()
@@ -59,7 +59,7 @@ final public class HMAC {
         self.key = key
 
         if (key.count > variant.blockSize()) {
-            if let hash = variant.calculateHash(bytes: key) {
+            if let hash = variant.calculateHash(key) {
                 self.key = hash
             }
         }
@@ -67,7 +67,7 @@ final public class HMAC {
         self.key = ZeroPadding().add(to: key, blockSize: variant.blockSize())
     }
 
-    public func authenticate(bytes:Array<UInt8>) -> Array<UInt8>? {
+    public func authenticate(_ bytes:Array<UInt8>) -> Array<UInt8>? {
         var opad = Array<UInt8>(repeating: 0x5c, count: variant.blockSize())
         for idx in key.indices {
             opad[idx] = key[idx] ^ opad[idx]
@@ -78,9 +78,9 @@ final public class HMAC {
         }
 
         var finalHash:Array<UInt8>? = nil;
-        if let ipadAndMessageHash = variant.calculateHash(bytes: ipad + bytes) {
-            finalHash = variant.calculateHash(bytes: opad + ipadAndMessageHash);
+        if let ipadAndMessageHash = variant.calculateHash(ipad + bytes) {
+            finalHash = variant.calculateHash(opad + ipadAndMessageHash);
         }
         return finalHash
     }
-}
+}

+ 5 - 5
Sources/CryptoSwift/Hash.swift

@@ -27,10 +27,10 @@ public enum Hash {
             return SHA2(bytes, variant: .sha384).calculate64()
         case sha512(let bytes):
             return SHA2(bytes, variant: .sha512).calculate64()
-        case crc32(let bytes):
-            return CRC().crc32(message: bytes.0, seed: bytes.seed, reflect: bytes.reflect).bytes()
-        case crc16(let bytes):
-            return UInt32(CRC().crc16(message: bytes.0, seed: bytes.seed)).bytes(totalBytes: 2)
+        case crc32(let bytes, let seed, let reflect):
+            return CRC().crc32(bytes, seed: seed, reflect: reflect).bytes()
+        case crc16(let bytes, let seed):
+            return UInt32(CRC().crc16(bytes, seed: seed)).bytes(totalBytes: 2)
         }
     }
-}
+}

+ 3 - 3
Sources/CryptoSwift/HashProtocol.swift

@@ -10,12 +10,12 @@ internal protocol HashProtocol {
     var message: Array<UInt8> { get }
     
     /** Common part for hash calculation. Prepare header data. */
-    func prepare(len:Int) -> Array<UInt8>
+    func prepare(_ len:Int) -> Array<UInt8>
 }
 
 extension HashProtocol {
     
-    func prepare(len:Int) -> Array<UInt8> {
+    func prepare(_ len:Int) -> Array<UInt8> {
         var tmpMessage = message
         
         // Step 1. Append Padding Bits
@@ -33,4 +33,4 @@ extension HashProtocol {
         tmpMessage += Array<UInt8>(repeating: 0, count: counter)
         return tmpMessage
     }
-}
+}

+ 6 - 6
Sources/CryptoSwift/IntExtension.swift

@@ -24,7 +24,7 @@
 /* array of bits */
 extension Int {
     init(bits: [Bit]) {
-        self.init(bitPattern: integerFrom(bits: bits) as UInt)
+        self.init(bitPattern: integerFrom(bits) as UInt)
     }
 }
 
@@ -35,13 +35,13 @@ extension Int {
         return arrayOfBytes(value: self, length: totalBytes)
     }
 
-    public static func with(bytes: ArraySlice<UInt8>) -> Int {
-        return Int.with(bytes: Array(bytes))
+    public static func with(_ bytes: ArraySlice<UInt8>) -> Int {
+        return integerWith(Array(bytes))
     }
 
     /** Int with array bytes (little-endian) */
-    public static func with(bytes: Array<UInt8>) -> Int {
-        return integerWith(bytes: bytes)
+    public static func with(_ bytes: Array<UInt8>) -> Int {
+        return integerWith(bytes)
     }
 }
 
@@ -52,7 +52,7 @@ extension Int {
     
     /** Shift bits to the left. All bits are shifted (including sign bit) */
     private mutating func shiftLeft(by count: Int) {
-        self = CryptoSwift.shiftLeft(value: self, by: count) //FIXME: count:
+        self = CryptoSwift.shiftLeft(self, by: count) //FIXME: count:
     }
     
     /** Shift bits to the right. All bits are shifted (including sign bit) */

+ 1 - 1
Sources/CryptoSwift/MD5.swift

@@ -41,7 +41,7 @@ final class MD5 : HashProtocol  {
     private let h:Array<UInt32> = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
     
     func calculate() -> Array<UInt8> {
-        var tmpMessage = prepare(len: 64)
+        var tmpMessage = prepare(64)
         tmpMessage.reserveCapacity(tmpMessage.count + 4)
 
         // initialize hh with hash values

+ 2 - 2
Sources/CryptoSwift/Multiplatform.swift

@@ -13,10 +13,10 @@
     import Darwin
 #endif
 
-func cs_arc4random_uniform(upperBound: UInt32) -> UInt32 {
+func cs_arc4random_uniform(_ upperBound: UInt32) -> UInt32 {
     #if os(Linux)
         return _swift_stdlib_arc4random_uniform(upperBound)
     #else
         return arc4random_uniform(upperBound)
     #endif
-}
+}

+ 8 - 8
Sources/CryptoSwift/PKCS5/PBKDF1.swift

@@ -16,8 +16,8 @@ public extension PKCS5 {
     public struct PBKDF1 {
 
         public enum Error: ErrorProtocol {
-            case InvalidInput
-            case DerivedKeyTooLong
+            case invalidInput
+            case derivedKeyTooLong
         }
 
         public enum Variant {
@@ -32,7 +32,7 @@ public extension PKCS5 {
                 }
             }
 
-            private func calculateHash(bytes:Array<UInt8>) -> Array<UInt8>? {
+            private func calculateHash(_ bytes:Array<UInt8>) -> Array<UInt8>? {
                 switch (self) {
                 case .sha1:
                     return Hash.sha1(bytes).calculate()
@@ -57,11 +57,11 @@ public extension PKCS5 {
             precondition(salt.count == 8)
 
             if (keyLength > variant.size) {
-                throw Error.DerivedKeyTooLong
+                throw Error.derivedKeyTooLong
             }
 
-            guard let t1 = variant.calculateHash(bytes: password + salt) else {
-                throw Error.InvalidInput
+            guard let t1 = variant.calculateHash(password + salt) else {
+                throw Error.invalidInput
             }
 
             self.iterations = iterations
@@ -74,9 +74,9 @@ public extension PKCS5 {
         public func calculate() -> Array<UInt8> {
             var t = t1
             for _ in 2...self.iterations {
-                t = self.variant.calculateHash(bytes: t)!
+                t = self.variant.calculateHash(t)!
             }
             return Array(t[0..<self.keyLength])
         }
     }
-}
+}

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

@@ -20,8 +20,8 @@ public extension PKCS5 {
     public struct PBKDF2 {
 
         public enum Error: ErrorProtocol {
-            case InvalidInput
-            case DerivedKeyTooLong
+            case invalidInput
+            case derivedKeyTooLong
         }
 
         private let salt: Array<UInt8>   // S
@@ -38,13 +38,13 @@ public extension PKCS5 {
             precondition(iterations > 0)
             
             guard let prf = HMAC(key: password, variant: variant) where iterations > 0 && !password.isEmpty && !salt.isEmpty else {
-                throw Error.InvalidInput
+                throw Error.invalidInput
             }
 
             let keyLengthFinal = Double(keyLength ?? variant.size)
             let hLen = Double(prf.variant.size)
             if keyLengthFinal > (pow(2,32) - 1) * hLen {
-                throw Error.DerivedKeyTooLong
+                throw Error.derivedKeyTooLong
             }
 
             self.salt = salt
@@ -59,7 +59,7 @@ public extension PKCS5 {
             var ret = Array<UInt8>()
             for i in 1...self.numBlocks {
                 // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
-                if let value = calculateBlock(salt: self.salt, blockNum: i) {
+                if let value = calculateBlock(self.salt, blockNum: i) {
                     ret.append(contentsOf: value)
                 }
             }
@@ -69,7 +69,7 @@ public extension PKCS5 {
 }
 
 private extension PKCS5.PBKDF2 {
-    private func INT(i: UInt) -> Array<UInt8> {
+    private func INT(_ i: UInt) -> Array<UInt8> {
         var inti = Array<UInt8>(repeating: 0, count: 4)
         inti[0] = UInt8((i >> 24) & 0xFF)
         inti[1] = UInt8((i >> 16) & 0xFF)
@@ -80,8 +80,8 @@ private extension PKCS5.PBKDF2 {
 
     // F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c
     // U_1 = PRF (P, S || INT (i))
-    private func calculateBlock(salt: Array<UInt8>, blockNum: UInt) -> Array<UInt8>? {
-        guard let u1 = prf.authenticate(bytes: salt + INT(i: blockNum)) else {
+    private func calculateBlock(_ salt: Array<UInt8>, blockNum: UInt) -> Array<UInt8>? {
+        guard let u1 = prf.authenticate(salt + INT(blockNum)) else {
             return nil
         }
 
@@ -91,7 +91,7 @@ private extension PKCS5.PBKDF2 {
             // U_2 = PRF (P, U_1) ,
             // U_c = PRF (P, U_{c-1}) .
             for _ in 2...self.iterations {
-                u = prf.authenticate(bytes: u)!
+                u = prf.authenticate(u)!
                 for x in 0..<ret.count {
                     ret[x] = ret[x] ^ u[x]
                 }

+ 2 - 2
Sources/CryptoSwift/PKCS7.swift

@@ -12,7 +12,7 @@
 public struct PKCS7: Padding {
 
     public enum Error: ErrorProtocol {
-        case InvalidPaddingValue
+        case invalidPaddingValue
     }
     
     public init() {
@@ -55,4 +55,4 @@ public struct PKCS7: Padding {
         }
         return bytes
     }
-}
+}

+ 1 - 1
Sources/CryptoSwift/Padding.swift

@@ -9,4 +9,4 @@
 public protocol Padding {
     func add(to: Array<UInt8>, blockSize:Int) -> Array<UInt8>
     func remove(from: Array<UInt8>, blockSize:Int?) -> Array<UInt8>
-}
+}

+ 23 - 23
Sources/CryptoSwift/Poly1305.swift

@@ -84,10 +84,10 @@ final public class Poly1305 {
 
      - returns: Message Authentication Code
      */
-    public func authenticate(bytes:Array<UInt8>) -> Array<UInt8>? {
+    public func authenticate(_ bytes:Array<UInt8>) -> Array<UInt8>? {
         if let ctx = self.ctx {
-            update(context: ctx, message: bytes)
-            return finish(context: ctx)
+            update(ctx, message: bytes)
+            return finish(ctx)
         }
         return nil
     }
@@ -108,7 +108,7 @@ final public class Poly1305 {
     - parameter message: message
     - parameter bytes:   length of the message fragment to be processed
     */
-    private func update(context:Context, message:Array<UInt8>, bytes:Int? = nil) {
+    private func update(_ context:Context, message:Array<UInt8>, bytes:Int? = nil) {
         var bytes = bytes ?? message.count
         var mPos = 0
         
@@ -131,14 +131,14 @@ final public class Poly1305 {
                 return
             }
             
-            blocks(context: context, m: context.buffer)
+            blocks(context, m: context.buffer)
             context.leftover = 0
         }
         
         /* process full blocks */
         if (bytes >= blockSize) {
             let want = bytes & ~(blockSize - 1)
-            blocks(context: context, m: message, startPos: mPos)
+            blocks(context, m: message, startPos: mPos)
             mPos += want
             bytes -= want;
         }
@@ -153,7 +153,7 @@ final public class Poly1305 {
         }
     }
     
-    private func finish(context:Context) -> Array<UInt8>? {
+    private func finish(_ context:Context) -> Array<UInt8>? {
         var mac = Array<UInt8>(repeating: 0, count: 16);
         
         /* process the remaining block */
@@ -165,15 +165,15 @@ final public class Poly1305 {
             }
             context.final = 1
             
-            blocks(context: context, m: context.buffer)
+            blocks(context, m: context.buffer)
         }
         
         
         /* fully reduce h */
-        freeze(context: context)
+        freeze(context)
         
         /* h = (h + pad) % (1 << 128) */
-        add(context: context, c: context.pad)
+        add(context, c: context.pad)
         for i in 0..<mac.count {
             mac[i] = context.h[i]
         }
@@ -183,7 +183,7 @@ final public class Poly1305 {
     
     // MARK: - Utils
     
-    private func add(context:Context, c:Array<UInt8>) {
+    private func add(_ context:Context, c:Array<UInt8>) {
         if (context.h.count != 17 && c.count != 17) {
             assertionFailure()
             return
@@ -192,13 +192,13 @@ final public class Poly1305 {
         var u:UInt16 = 0
         for i in 0..<17 {
             u += UInt16(context.h[i]) + UInt16(c[i])
-            context.h[i] = UInt8.withValue(v: u)
+            context.h[i] = UInt8.with(value: u)
             u = u >> 8
         }
         return
     }
     
-    private func squeeze(context:Context, hr:Array<UInt32>) {
+    private func squeeze(_ context:Context, hr:Array<UInt32>) {
         if (context.h.count != 17 && hr.count != 17) {
             assertionFailure()
             return
@@ -208,23 +208,23 @@ final public class Poly1305 {
         
         for i in 0..<16 {
             u += hr[i];
-            context.h[i] = UInt8.withValue(v: u) // crash! h[i] = UInt8(u) & 0xff
+            context.h[i] = UInt8.with(value: u) // crash! h[i] = UInt8(u) & 0xff
             u >>= 8;
         }
         
         u += hr[16]
-        context.h[16] = UInt8.withValue(v: u) & 0x03
+        context.h[16] = UInt8.with(value: u) & 0x03
         u >>= 2
         u += (u << 2); /* u *= 5; */
         for i in 0..<16 {
             u += UInt32(context.h[i])
-            context.h[i] = UInt8.withValue(v: u) // crash! h[i] = UInt8(u) & 0xff
+            context.h[i] = UInt8.with(value: u) // crash! h[i] = UInt8(u) & 0xff
             u >>= 8
         }
-        context.h[16] += UInt8.withValue(v: u);
+        context.h[16] += UInt8.with(value: u);
     }
     
-    private func freeze(context:Context) {
+    private func freeze(_ context:Context) {
         assert(context.h.count == 17,"Invalid length")
         if (context.h.count != 17) {
             return
@@ -238,7 +238,7 @@ final public class Poly1305 {
             horig[i] = context.h[i]
         }
         
-        add(context: context, c: minusp)
+        add(context, c: minusp)
         
         /* select h if h < p, or h + -p if h >= p */
         let bits:[Bit] = (context.h[16] >> 7).bits()
@@ -252,7 +252,7 @@ final public class Poly1305 {
         }
     }
     
-    private func blocks(context:Context, m:Array<UInt8>, startPos:Int = 0) {
+    private func blocks(_ context:Context, m:Array<UInt8>, startPos:Int = 0) {
         var bytes = m.count
         let hibit = context.final ^ 1 // 1 <<128
         var mPos = startPos
@@ -268,7 +268,7 @@ final public class Poly1305 {
             }
             c[16] = hibit
             
-            add(context: context, c: c)
+            add(context, c: c)
             
             /* h *= r */
             for i in 0..<17 {
@@ -284,10 +284,10 @@ final public class Poly1305 {
                 hr[i] = u
             }
             
-            squeeze(context: context, hr: hr)
+            squeeze(context, hr: hr)
             
             mPos += blockSize
             bytes -= blockSize
         }
     }
-}
+}

+ 18 - 18
Sources/CryptoSwift/Rabbit.swift

@@ -93,17 +93,17 @@ final public class Rabbit: BlockCipher {
         }
         
         if let iv = iv {
-            setupIV(iv: iv)
+            setupIV(iv)
         }
     }
     
-    private func setupIV(iv: Array<UInt8>) {
+    private func setupIV(_ iv: Array<UInt8>) {
         // 63...56 55...48 47...40 39...32 31...24 23...16 15...8 7...0 IV bits
         //    0       1       2       3       4       5       6     7   IV bytes in array
-        let iv0: UInt32 = integerWith(bytes: [iv[4], iv[5], iv[6], iv[7]])
-        let iv1: UInt32 = integerWith(bytes: [iv[0], iv[1], iv[4], iv[5]])
-        let iv2: UInt32 = integerWith(bytes: [iv[0], iv[1], iv[2], iv[3]])
-        let iv3: UInt32 = integerWith(bytes: [iv[2], iv[3], iv[6], iv[7]])
+        let iv0: UInt32 = integerWith([iv[4], iv[5], iv[6], iv[7]])
+        let iv1: UInt32 = integerWith([iv[0], iv[1], iv[4], iv[5]])
+        let iv2: UInt32 = integerWith([iv[0], iv[1], iv[2], iv[3]])
+        let iv3: UInt32 = integerWith([iv[2], iv[3], iv[6], iv[7]])
         
         // Modify the counter state as function of the IV
         c[0] = c[0] ^ iv0
@@ -134,18 +134,18 @@ final public class Rabbit: BlockCipher {
         
         // Iteration of the system
         var newX = Array<UInt32>(repeating: 0, count: 8)
-        newX[0] = g(j: 0) &+ rotateLeft(g(j: 7), by: 16) &+ rotateLeft(g(j: 6), by: 16)
-        newX[1] = g(j: 1) &+ rotateLeft(g(j: 0), by: 8)  &+ g(j: 7)
-        newX[2] = g(j: 2) &+ rotateLeft(g(j: 1), by: 16) &+ rotateLeft(g(j: 0), by: 16)
-        newX[3] = g(j: 3) &+ rotateLeft(g(j: 2), by: 8)  &+ g(j: 1)
-        newX[4] = g(j: 4) &+ rotateLeft(g(j: 3), by: 16) &+ rotateLeft(g(j: 2), by: 16)
-        newX[5] = g(j: 5) &+ rotateLeft(g(j: 4), by: 8)  &+ g(j: 3)
-        newX[6] = g(j: 6) &+ rotateLeft(g(j: 5), by: 16) &+ rotateLeft(g(j: 4), by: 16)
-        newX[7] = g(j: 7) &+ rotateLeft(g(j: 6), by: 8)  &+ g(j: 5)
+        newX[0] = g(0) &+ rotateLeft(g(7), by: 16) &+ rotateLeft(g(6), by: 16)
+        newX[1] = g(1) &+ rotateLeft(g(0), by: 8)  &+ g(7)
+        newX[2] = g(2) &+ rotateLeft(g(1), by: 16) &+ rotateLeft(g(0), by: 16)
+        newX[3] = g(3) &+ rotateLeft(g(2), by: 8)  &+ g(1)
+        newX[4] = g(4) &+ rotateLeft(g(3), by: 16) &+ rotateLeft(g(2), by: 16)
+        newX[5] = g(5) &+ rotateLeft(g(4), by: 8)  &+ g(3)
+        newX[6] = g(6) &+ rotateLeft(g(5), by: 16) &+ rotateLeft(g(4), by: 16)
+        newX[7] = g(7) &+ rotateLeft(g(6), by: 8)  &+ g(5)
         x = newX
     }
     
-    private func g(j: Int) -> UInt32 {
+    private func g(_ j: Int) -> UInt32 {
         let sum = x[j] &+ c[j]
         let square = UInt64(sum) * UInt64(sum)
         return UInt32(truncatingBitPattern: square ^ (square >> 32))
@@ -175,7 +175,7 @@ final public class Rabbit: BlockCipher {
 
 // MARK: Cipher
 extension Rabbit: Cipher {
-    public func encrypt(bytes: Array<UInt8>) -> Array<UInt8> {
+    public func encrypt(_ bytes: Array<UInt8>) -> Array<UInt8> {
         setup()
 
         var result = Array<UInt8>(repeating: 0, count: bytes.count)
@@ -196,7 +196,7 @@ extension Rabbit: Cipher {
         return result
     }
 
-    public func decrypt(bytes: Array<UInt8>) -> Array<UInt8> {
-        return encrypt(bytes: bytes)
+    public func decrypt(_ bytes: Array<UInt8>) -> Array<UInt8> {
+        return encrypt(bytes)
     }
 }

+ 2 - 2
Sources/CryptoSwift/SHA1.swift

@@ -17,7 +17,7 @@ final class SHA1 : HashProtocol {
     private let h:Array<UInt32> = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
         
     func calculate() -> Array<UInt8> {
-        var tmpMessage = self.prepare(len: 64)
+        var tmpMessage = self.prepare(64)
         
         // hash values
         var hh = h
@@ -101,4 +101,4 @@ final class SHA1 : HashProtocol {
         }
         return result
     }
-}
+}

+ 6 - 6
Sources/CryptoSwift/SHA2.swift

@@ -99,7 +99,7 @@ final class SHA2 : HashProtocol {
             }
         }
         
-        private func resultingArray<T>(hh:[T]) -> ArraySlice<T> {
+        private func resultingArray<T>(_ hh:[T]) -> ArraySlice<T> {
             switch (self) {
             case .sha224:
                 return hh[0..<7]
@@ -114,7 +114,7 @@ final class SHA2 : HashProtocol {
     
     //FIXME: I can't do Generic func out of calculate32 and calculate64 (UInt32 vs UInt64), but if you can - please do pull request.
     func calculate32() -> Array<UInt8> {
-        var tmpMessage = self.prepare(len: 64)
+        var tmpMessage = self.prepare(64)
         
         // hash values
         var hh = Array<UInt32>()
@@ -188,7 +188,7 @@ final class SHA2 : HashProtocol {
         // Produce the final hash value (big-endian) as a 160 bit number:
         var result = Array<UInt8>()
         result.reserveCapacity(hh.count / 4)
-        variant.resultingArray(hh: hh).forEach {
+        variant.resultingArray(hh).forEach {
             let item = $0.bigEndian
             result += [UInt8(item & 0xff), UInt8((item >> 8) & 0xff), UInt8((item >> 16) & 0xff), UInt8((item >> 24) & 0xff)]
         }
@@ -196,7 +196,7 @@ final class SHA2 : HashProtocol {
     }
     
     func calculate64() -> Array<UInt8> {
-        var tmpMessage = self.prepare(len: 128)
+        var tmpMessage = self.prepare(128)
         
         // hash values
         var hh = Array<UInt64>()
@@ -271,7 +271,7 @@ final class SHA2 : HashProtocol {
         // Produce the final hash value (big-endian)
         var result = Array<UInt8>()
         result.reserveCapacity(hh.count / 4)
-        variant.resultingArray(hh: hh).forEach {
+        variant.resultingArray(hh).forEach {
             let item = $0.bigEndian
             var partialResult = Array<UInt8>()
             partialResult.reserveCapacity(8)
@@ -283,4 +283,4 @@ final class SHA2 : HashProtocol {
         }
         return result
     }
-}
+}

+ 1 - 1
Sources/CryptoSwift/String+Extension.swift

@@ -53,4 +53,4 @@ extension String {
     public func authenticate(with authenticator: Authenticator) throws -> String {
         return try self.utf8.lazy.map({ $0 as UInt8 }).authenticate(with: authenticator).toHexString()
     }
-}
+}

+ 3 - 3
Sources/CryptoSwift/UInt32Extension.swift

@@ -23,12 +23,12 @@ extension UInt32 {
     }
 
     public static func with(bytes: ArraySlice<UInt8>) -> UInt32 {
-        return UInt32.with(bytes: Array(bytes))
+        return integerWith(Array(bytes))
     }
 
     /** Int with array bytes (little-endian) */
     public static func with(bytes: Array<UInt8>) -> UInt32 {
-        return integerWith(bytes: bytes)
+        return integerWith(bytes)
     }
 }
 
@@ -111,4 +111,4 @@ func &>> (lhs: UInt32, rhs: UInt32) -> UInt32 {
     var l = lhs;
     l.shiftRight(by: rhs)
     return l
-}
+}

+ 3 - 3
Sources/CryptoSwift/UInt64Extension.swift

@@ -13,11 +13,11 @@ extension UInt64 {
     }
 
     public static func with(bytes: ArraySlice<UInt8>) -> UInt64 {
-        return UInt64.with(bytes: Array(bytes))
+        return integerWith(Array(bytes))
     }
 
     /** Int with array bytes (little-endian) */
     public static func with(bytes: Array<UInt8>) -> UInt64 {
-        return integerWith(bytes: bytes)
+        return integerWith(bytes)
     }
-}
+}

+ 11 - 11
Sources/CryptoSwift/UInt8Extension.swift

@@ -27,18 +27,18 @@ extension _UInt8Type {
 extension UInt8 {
     
     /** cast because UInt8(<UInt32>) because std initializer crash if value is > byte */
-    static func withValue(v:UInt64) -> UInt8 {
-        let tmp = v & 0xFF
+    static func with(value:UInt64) -> UInt8 {
+        let tmp = value & 0xFF
         return UInt8(tmp)
     }
 
-    static func withValue(v:UInt32) -> UInt8 {
-        let tmp = v & 0xFF
+    static func with(value: UInt32) -> UInt8 {
+        let tmp = value & 0xFF
         return UInt8(tmp)
     }
     
-    static func withValue(v:UInt16) -> UInt8 {
-        let tmp = v & 0xFF
+    static func with(value: UInt16) -> UInt8 {
+        let tmp = value & 0xFF
         return UInt8(tmp)
     }
 
@@ -48,21 +48,21 @@ extension UInt8 {
 extension UInt8 {
 
     init(bits: [Bit]) {
-        self.init(integerFrom(bits: bits) as UInt8)
+        self.init(integerFrom(bits) as UInt8)
     }
     
     /** array of bits */
     func bits() -> [Bit] {
         let totalBitsCount = sizeofValue(self) * 8
         
-        var bitsArray = [Bit](repeating: Bit.Zero, count: totalBitsCount)
+        var bitsArray = [Bit](repeating: Bit.zero, count: totalBitsCount)
         
         for j in 0..<totalBitsCount {
             let bitVal:UInt8 = 1 << UInt8(totalBitsCount - 1 - j)
             let check = self & bitVal
             
             if (check != 0) {
-                bitsArray[j] = Bit.One;
+                bitsArray[j] = Bit.one;
             }
         }
         return bitsArray
@@ -72,7 +72,7 @@ extension UInt8 {
         var s = String()
         let arr:[Bit] = self.bits()
         for idx in arr.indices {
-            s += (arr[idx] == Bit.One ? "1" : "0")
+            s += (arr[idx] == Bit.one ? "1" : "0")
             if (idx.advanced(by: 1) % 8 == 0) { s += " " }
         }
         return s
@@ -112,4 +112,4 @@ func &>> (lhs: UInt8, rhs: UInt8) -> UInt8 {
     var l = lhs;
     l.shiftRight(by: rhs)
     return l
-}
+}

+ 4 - 4
Sources/CryptoSwift/Utils.swift

@@ -34,7 +34,7 @@ func rotateRight(_ value:UInt64, by:UInt64) -> UInt64 {
     return ((value >> by) | (value << (64 - by)))
 }
 
-func reverse(uint8 : UInt8) -> UInt8 {
+func reversed(_ uint8 : UInt8) -> UInt8 {
     var v = uint8
     v = (v & 0xF0) >> 4 | (v & 0x0F) << 4
     v = (v & 0xCC) >> 2 | (v & 0x33) << 2
@@ -42,7 +42,7 @@ func reverse(uint8 : UInt8) -> UInt8 {
     return v
 }
 
-func reverse(uint32 : UInt32) -> UInt32 {
+func reversed(_ uint32 : UInt32) -> UInt32 {
     var v = uint32
     v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1)
     v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2)
@@ -84,10 +84,10 @@ func sliceToUInt64Array(_ slice: ArraySlice<UInt8>) -> Array<UInt64> {
     return result
 }
 
-func xor(a: Array<UInt8>, _ b:Array<UInt8>) -> Array<UInt8> {
+func xor(_ a: Array<UInt8>, _ b:Array<UInt8>) -> Array<UInt8> {
     var xored = Array<UInt8>(repeating: 0, count: min(a.count, b.count))
     for i in 0..<xored.count {
         xored[i] = a[i] ^ b[i]
     }
     return xored
-}
+}