Quellcode durchsuchen

Merge branch 'develop'

Marcin Krzyżanowski vor 10 Jahren
Ursprung
Commit
af6d4155a1
37 geänderte Dateien mit 599 neuen und 458 gelöschten Zeilen
  1. 33 31
      CryptoSwift.xcodeproj/project.pbxproj
  2. 8 5
      CryptoSwift.xcodeproj/xcshareddata/xcschemes/CryptoSwift.xcscheme
  3. 64 61
      CryptoSwift/AES.swift
  4. 4 4
      CryptoSwift/ArrayExtension.swift
  5. 2 2
      CryptoSwift/Authenticator.swift
  6. 9 5
      CryptoSwift/CRC.swift
  7. 48 45
      CryptoSwift/ChaCha20.swift
  8. 35 21
      CryptoSwift/Cipher.swift
  9. 102 45
      CryptoSwift/CipherBlockMode.swift
  10. 19 20
      CryptoSwift/Generics.swift
  11. 5 5
      CryptoSwift/HMAC.swift
  12. 0 2
      CryptoSwift/Hash.swift
  13. 16 21
      CryptoSwift/HashProtocol.swift
  14. 6 6
      CryptoSwift/IntExtension.swift
  15. 16 15
      CryptoSwift/MD5.swift
  16. 7 11
      CryptoSwift/NSDataExtension.swift
  17. 26 0
      CryptoSwift/NSDataSequence.swift
  18. 7 7
      CryptoSwift/PKCS7.swift
  19. 2 2
      CryptoSwift/Padding.swift
  20. 9 9
      CryptoSwift/Poly1305.swift
  21. 11 12
      CryptoSwift/SHA1.swift
  22. 33 33
      CryptoSwift/SHA2.swift
  23. 4 4
      CryptoSwift/StringExtension.swift
  24. 4 4
      CryptoSwift/UInt16Extension.swift
  25. 8 8
      CryptoSwift/UInt32Extension.swift
  26. 1 1
      CryptoSwift/UInt64Extension.swift
  27. 5 5
      CryptoSwift/UInt8Extension.swift
  28. 2 8
      CryptoSwift/Utils.swift
  29. 61 27
      CryptoSwiftTests/AESTests.swift
  30. 14 12
      CryptoSwiftTests/ChaCha20Tests.swift
  31. 6 6
      CryptoSwiftTests/ExtensionsTest.swift
  32. 1 1
      CryptoSwiftTests/HMACTests.swift
  33. 11 11
      CryptoSwiftTests/HashTests.swift
  34. 3 3
      CryptoSwiftTests/Helpers.swift
  35. 4 4
      CryptoSwiftTests/PaddingTests.swift
  36. 1 1
      CryptoSwiftTests/Poly1305Tests.swift
  37. 12 1
      README.md

+ 33 - 31
CryptoSwift.xcodeproj/project.pbxproj

@@ -21,21 +21,22 @@
 /* End PBXAggregateTarget section */
 
 /* Begin PBXBuildFile section */
-		750A54601992D2680017DA75 /* MD5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 750A545F1992D2680017DA75 /* MD5.swift */; };
 		75100F8F19B0BC890005C5F5 /* Poly1305Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75100F8E19B0BC890005C5F5 /* Poly1305Tests.swift */; };
-		75153D4219AA3C7900750381 /* SHA2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75153D4119AA3C7900750381 /* SHA2.swift */; };
 		75164E4919AD30AC00737F30 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75164E4819AD30AC00737F30 /* Utils.swift */; };
 		751C5C3D19B26B000094C75D /* Poly1305.swift in Sources */ = {isa = PBXBuildFile; fileRef = 751C5C3C19B26B000094C75D /* Poly1305.swift */; };
-		752DEF7719693EA000E17557 /* NSDataExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 752DEF7619693EA000E17557 /* NSDataExtension.swift */; };
-		752E087B199FF27C005B0EA0 /* SHA1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 752E087A199FF27C005B0EA0 /* SHA1.swift */; };
-		753988211AB72E4100FAF3FC /* ArrayExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 754C8FEC19979F94005AD904 /* ArrayExtension.swift */; };
+		7539E3291B3B4A530037F4E1 /* MD5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 750A545F1992D2680017DA75 /* MD5.swift */; };
+		7539E32A1B3B4C480037F4E1 /* NSDataExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 752DEF7619693EA000E17557 /* NSDataExtension.swift */; };
+		7539E32B1B3B4C6B0037F4E1 /* HMAC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 758A94251A65AEB100E46135 /* HMAC.swift */; };
+		7539E32C1B3B4C750037F4E1 /* StringExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7599C9C5199EA28700A3988B /* StringExtension.swift */; };
+		7539E32D1B3B4E950037F4E1 /* SHA1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 752E087A199FF27C005B0EA0 /* SHA1.swift */; };
+		7539E32E1B3B4E970037F4E1 /* SHA2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75153D4119AA3C7900750381 /* SHA2.swift */; };
 		75445821196AA2A5002FF20E /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 75445820196AA2A5002FF20E /* Security.framework */; settings = {ATTRIBUTES = (Required, ); }; };
 		7547195119931802002FA5F1 /* IntExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7547195019931802002FA5F1 /* IntExtension.swift */; };
 		754BE45B19693E190098E6F3 /* CryptoSwift.h in Headers */ = {isa = PBXBuildFile; fileRef = 754BE45A19693E190098E6F3 /* CryptoSwift.h */; settings = {ATTRIBUTES = (Public, ); }; };
 		754BE46819693E190098E6F3 /* HashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 754BE46719693E190098E6F3 /* HashTests.swift */; };
 		754C30B71AA13BC000E6FFA4 /* PKCS7.swift in Sources */ = {isa = PBXBuildFile; fileRef = 754C30B61AA13BC000E6FFA4 /* PKCS7.swift */; };
 		754C8FED19979F94005AD904 /* ArrayExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 754C8FEC19979F94005AD904 /* ArrayExtension.swift */; };
-		754DD76E19A149AF00E52288 /* HashBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 754DD76D19A149AF00E52288 /* HashBase.swift */; };
+		754DD76E19A149AF00E52288 /* HashProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 754DD76D19A149AF00E52288 /* HashProtocol.swift */; };
 		755111E819B7B7DF00C2AD86 /* Authenticator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 755111E719B7B7DF00C2AD86 /* Authenticator.swift */; };
 		7552614E1993051E000D2B20 /* Hash.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7552614D1993051E000D2B20 /* Hash.swift */; };
 		755FB1DA199E347D00475437 /* ExtensionsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 755FB1D9199E347D00475437 /* ExtensionsTest.swift */; };
@@ -45,13 +46,11 @@
 		757DA2571A4ED47B002BA3EF /* Helpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757DA2561A4ED47B002BA3EF /* Helpers.swift */; };
 		757DA2591A4ED4D7002BA3EF /* ChaCha20Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757DA2581A4ED4D7002BA3EF /* ChaCha20Tests.swift */; };
 		757EF7F519AAA82400586276 /* CRC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757EF7F419AAA82400586276 /* CRC.swift */; };
-		758A94261A65AEB100E46135 /* HMAC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 758A94251A65AEB100E46135 /* HMAC.swift */; };
 		758A94281A65C59200E46135 /* HMACTests.swift in Resources */ = {isa = PBXBuildFile; fileRef = 758A94271A65C59200E46135 /* HMACTests.swift */; };
 		758A94291A65C67400E46135 /* HMACTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 758A94271A65C59200E46135 /* HMACTests.swift */; };
 		758C764119B61AE500653BC6 /* Generics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 758C764019B61AE500653BC6 /* Generics.swift */; };
 		758C764319B61DE900653BC6 /* UInt16Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 758C764219B61DE900653BC6 /* UInt16Extension.swift */; };
 		758F3F781992F6CE0014BBDA /* UInt8Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 758F3F771992F6CE0014BBDA /* UInt8Extension.swift */; };
-		7599C9C6199EA28700A3988B /* StringExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7599C9C5199EA28700A3988B /* StringExtension.swift */; };
 		759D481119B517BC005FF7FC /* BitExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 759D481019B517BC005FF7FC /* BitExtension.swift */; };
 		75A663A61AA0CAD00052110B /* Padding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75A663A51AA0CAD00052110B /* Padding.swift */; };
 		75A74B271A1FF6B2004419F1 /* AES.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75A74B261A1FF6B2004419F1 /* AES.swift */; };
@@ -59,6 +58,7 @@
 		75B601EB197D6A6C0009B53D /* CryptoSwift.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 754BE45519693E190098E6F3 /* CryptoSwift.framework */; };
 		75BC3AE31A4E412000ADF343 /* CipherBlockMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75BC3AE21A4E412000ADF343 /* CipherBlockMode.swift */; };
 		75BE4EB11B1E4A9F007A2B57 /* IntegerConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75BE4EB01B1E4A9F007A2B57 /* IntegerConvertible.swift */; };
+		75D2D1A01B5689EB000A2615 /* NSDataSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75D2D19F1B5689EB000A2615 /* NSDataSequence.swift */; };
 		75D94E2419B60C08007CB2A4 /* Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75D94E2319B60C08007CB2A4 /* Operators.swift */; };
 		75D94E2619B60C4F007CB2A4 /* UInt32Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75D94E2519B60C4F007CB2A4 /* UInt32Extension.swift */; };
 		75D94E2819B60DDE007CB2A4 /* UInt64Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75D94E2719B60DDE007CB2A4 /* UInt64Extension.swift */; };
@@ -147,7 +147,7 @@
 		754BE46719693E190098E6F3 /* HashTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HashTests.swift; sourceTree = "<group>"; };
 		754C30B61AA13BC000E6FFA4 /* PKCS7.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PKCS7.swift; sourceTree = "<group>"; };
 		754C8FEC19979F94005AD904 /* ArrayExtension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ArrayExtension.swift; sourceTree = "<group>"; };
-		754DD76D19A149AF00E52288 /* HashBase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HashBase.swift; sourceTree = "<group>"; };
+		754DD76D19A149AF00E52288 /* HashProtocol.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HashProtocol.swift; sourceTree = "<group>"; };
 		755111E719B7B7DF00C2AD86 /* Authenticator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Authenticator.swift; sourceTree = "<group>"; };
 		7552614D1993051E000D2B20 /* Hash.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Hash.swift; sourceTree = "<group>"; };
 		755FB1D9199E347D00475437 /* ExtensionsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ExtensionsTest.swift; sourceTree = "<group>"; };
@@ -170,6 +170,7 @@
 		75B0A56F1AB1A1BB000BD8D2 /* PKCS5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PKCS5.swift; sourceTree = "<group>"; };
 		75BC3AE21A4E412000ADF343 /* CipherBlockMode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CipherBlockMode.swift; sourceTree = "<group>"; };
 		75BE4EB01B1E4A9F007A2B57 /* IntegerConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IntegerConvertible.swift; sourceTree = "<group>"; };
+		75D2D19F1B5689EB000A2615 /* NSDataSequence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDataSequence.swift; sourceTree = "<group>"; };
 		75D94E2319B60C08007CB2A4 /* Operators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Operators.swift; sourceTree = "<group>"; };
 		75D94E2519B60C4F007CB2A4 /* UInt32Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UInt32Extension.swift; sourceTree = "<group>"; };
 		75D94E2719B60DDE007CB2A4 /* UInt64Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UInt64Extension.swift; sourceTree = "<group>"; };
@@ -234,7 +235,7 @@
 				75B0A56F1AB1A1BB000BD8D2 /* PKCS5.swift */,
 				754C30B61AA13BC000E6FFA4 /* PKCS7.swift */,
 				755111E719B7B7DF00C2AD86 /* Authenticator.swift */,
-				754DD76D19A149AF00E52288 /* HashBase.swift */,
+				754DD76D19A149AF00E52288 /* HashProtocol.swift */,
 				750A545F1992D2680017DA75 /* MD5.swift */,
 				752E087A199FF27C005B0EA0 /* SHA1.swift */,
 				75153D4119AA3C7900750381 /* SHA2.swift */,
@@ -256,6 +257,7 @@
 				75164E4819AD30AC00737F30 /* Utils.swift */,
 				758C764019B61AE500653BC6 /* Generics.swift */,
 				75BE4EB01B1E4A9F007A2B57 /* IntegerConvertible.swift */,
+				75D2D19F1B5689EB000A2615 /* NSDataSequence.swift */,
 				754BE45819693E190098E6F3 /* Supporting Files */,
 			);
 			path = CryptoSwift;
@@ -357,7 +359,8 @@
 		754BE44C19693E190098E6F3 /* Project object */ = {
 			isa = PBXProject;
 			attributes = {
-				LastUpgradeCheck = 0600;
+				LastSwiftUpdateCheck = 0700;
+				LastUpgradeCheck = 0700;
 				ORGANIZATIONNAME = "Marcin Krzyzanowski";
 				TargetAttributes = {
 					3F8849E11B0647D6006AB604 = {
@@ -430,35 +433,36 @@
 			isa = PBXSourcesBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
+				75D2D1A01B5689EB000A2615 /* NSDataSequence.swift in Sources */,
 				75D94E2819B60DDE007CB2A4 /* UInt64Extension.swift in Sources */,
 				751C5C3D19B26B000094C75D /* Poly1305.swift in Sources */,
 				7552614E1993051E000D2B20 /* Hash.swift in Sources */,
 				75BC3AE31A4E412000ADF343 /* CipherBlockMode.swift in Sources */,
-				7599C9C6199EA28700A3988B /* StringExtension.swift in Sources */,
 				75BE4EB11B1E4A9F007A2B57 /* IntegerConvertible.swift in Sources */,
+				7539E32E1B3B4E970037F4E1 /* SHA2.swift in Sources */,
+				7539E32C1B3B4C750037F4E1 /* StringExtension.swift in Sources */,
 				7563B2E819B14D4300B152CD /* Cipher.swift in Sources */,
-				752E087B199FF27C005B0EA0 /* SHA1.swift in Sources */,
+				7539E32B1B3B4C6B0037F4E1 /* HMAC.swift in Sources */,
+				7539E32A1B3B4C480037F4E1 /* NSDataExtension.swift in Sources */,
 				75EB380119ABDD710002375A /* ChaCha20.swift in Sources */,
 				75A663A61AA0CAD00052110B /* Padding.swift in Sources */,
-				750A54601992D2680017DA75 /* MD5.swift in Sources */,
 				75164E4919AD30AC00737F30 /* Utils.swift in Sources */,
-				758A94261A65AEB100E46135 /* HMAC.swift in Sources */,
-				752DEF7719693EA000E17557 /* NSDataExtension.swift in Sources */,
 				759D481119B517BC005FF7FC /* BitExtension.swift in Sources */,
 				754C8FED19979F94005AD904 /* ArrayExtension.swift in Sources */,
+				7539E3291B3B4A530037F4E1 /* MD5.swift in Sources */,
 				7547195119931802002FA5F1 /* IntExtension.swift in Sources */,
 				758C764319B61DE900653BC6 /* UInt16Extension.swift in Sources */,
 				75D94E2419B60C08007CB2A4 /* Operators.swift in Sources */,
+				7539E32D1B3B4E950037F4E1 /* SHA1.swift in Sources */,
 				75B0A5701AB1A1BB000BD8D2 /* PKCS5.swift in Sources */,
 				757EF7F519AAA82400586276 /* CRC.swift in Sources */,
 				75D94E2619B60C4F007CB2A4 /* UInt32Extension.swift in Sources */,
 				75A74B271A1FF6B2004419F1 /* AES.swift in Sources */,
 				754C30B71AA13BC000E6FFA4 /* PKCS7.swift in Sources */,
 				755111E819B7B7DF00C2AD86 /* Authenticator.swift in Sources */,
-				754DD76E19A149AF00E52288 /* HashBase.swift in Sources */,
+				754DD76E19A149AF00E52288 /* HashProtocol.swift in Sources */,
 				758C764119B61AE500653BC6 /* Generics.swift in Sources */,
 				758F3F781992F6CE0014BBDA /* UInt8Extension.swift in Sources */,
-				75153D4219AA3C7900750381 /* SHA2.swift in Sources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
@@ -469,7 +473,6 @@
 				758A94291A65C67400E46135 /* HMACTests.swift in Sources */,
 				75100F8F19B0BC890005C5F5 /* Poly1305Tests.swift in Sources */,
 				757DA2571A4ED47B002BA3EF /* Helpers.swift in Sources */,
-				753988211AB72E4100FAF3FC /* ArrayExtension.swift in Sources */,
 				754BE46819693E190098E6F3 /* HashTests.swift in Sources */,
 				757DA2591A4ED4D7002BA3EF /* ChaCha20Tests.swift in Sources */,
 				755FB1DA199E347D00475437 /* ExtensionsTest.swift in Sources */,
@@ -554,6 +557,7 @@
 				COPY_PHASE_STRIP = NO;
 				CURRENT_PROJECT_VERSION = 1;
 				ENABLE_STRICT_OBJC_MSGSEND = YES;
+				ENABLE_TESTABILITY = YES;
 				GCC_C_LANGUAGE_STANDARD = gnu99;
 				GCC_DYNAMIC_NO_PIC = NO;
 				GCC_OPTIMIZATION_LEVEL = 0;
@@ -573,7 +577,6 @@
 				ONLY_ACTIVE_ARCH = YES;
 				SDKROOT = iphoneos;
 				SWIFT_OPTIMIZATION_LEVEL = "-Onone";
-				SWIFT_WHOLE_MODULE_OPTIMIZATION = YES;
 				TARGETED_DEVICE_FAMILY = "1,2";
 				VERSIONING_SYSTEM = "apple-generic";
 				VERSION_INFO_PREFIX = "";
@@ -612,7 +615,6 @@
 				IPHONEOS_DEPLOYMENT_TARGET = 8.0;
 				METAL_ENABLE_DEBUG_INFO = NO;
 				SDKROOT = iphoneos;
-				SWIFT_WHOLE_MODULE_OPTIMIZATION = YES;
 				TARGETED_DEVICE_FAMILY = "1,2";
 				VALIDATE_PRODUCT = YES;
 				VERSIONING_SYSTEM = "apple-generic";
@@ -628,6 +630,7 @@
 				DYLIB_COMPATIBILITY_VERSION = 1;
 				DYLIB_CURRENT_VERSION = 1;
 				DYLIB_INSTALL_NAME_BASE = "@rpath";
+				ENABLE_TESTABILITY = YES;
 				HEADER_SEARCH_PATHS = (
 					"$(inherited)",
 					"/Applications/Xcode6-Beta3.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include",
@@ -636,6 +639,7 @@
 				INFOPLIST_FILE = CryptoSwift/Info.plist;
 				INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
 				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
+				PRODUCT_BUNDLE_IDENTIFIER = "com.hakore.${PRODUCT_NAME:rfc1034identifier}";
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				SKIP_INSTALL = YES;
 				SWIFT_OPTIMIZATION_LEVEL = "-Onone";
@@ -650,6 +654,7 @@
 				DYLIB_COMPATIBILITY_VERSION = 1;
 				DYLIB_CURRENT_VERSION = 1;
 				DYLIB_INSTALL_NAME_BASE = "@rpath";
+				ENABLE_TESTABILITY = YES;
 				GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
 				GCC_UNROLL_LOOPS = YES;
 				HEADER_SEARCH_PATHS = (
@@ -661,19 +666,17 @@
 				INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
 				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
 				LLVM_LTO = YES;
+				PRODUCT_BUNDLE_IDENTIFIER = "com.hakore.${PRODUCT_NAME:rfc1034identifier}";
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				SKIP_INSTALL = YES;
-				SWIFT_OPTIMIZATION_LEVEL = "-Ounchecked";
+				SWIFT_DISABLE_SAFETY_CHECKS = YES;
+				SWIFT_OPTIMIZATION_LEVEL = "-O";
 			};
 			name = Release;
 		};
 		754BE46F19693E190098E6F3 /* Debug */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
-				FRAMEWORK_SEARCH_PATHS = (
-					"$(SDKROOT)/Developer/Library/Frameworks",
-					"$(inherited)",
-				);
 				GCC_PREPROCESSOR_DEFINITIONS = (
 					"DEBUG=1",
 					"$(inherited)",
@@ -687,6 +690,7 @@
 				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
 				LLVM_LTO = NO;
 				METAL_ENABLE_DEBUG_INFO = YES;
+				PRODUCT_BUNDLE_IDENTIFIER = "com.hakore.${PRODUCT_NAME:rfc1034identifier}";
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				SWIFT_OBJC_BRIDGING_HEADER = CryptoSwiftTests/Bridging.h;
 			};
@@ -695,10 +699,6 @@
 		754BE47019693E190098E6F3 /* Release */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
-				FRAMEWORK_SEARCH_PATHS = (
-					"$(SDKROOT)/Developer/Library/Frameworks",
-					"$(inherited)",
-				);
 				GCC_OPTIMIZATION_LEVEL = fast;
 				GCC_UNROLL_LOOPS = YES;
 				HEADER_SEARCH_PATHS = (
@@ -710,9 +710,11 @@
 				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
 				LLVM_LTO = YES;
 				METAL_ENABLE_DEBUG_INFO = NO;
+				PRODUCT_BUNDLE_IDENTIFIER = "com.hakore.${PRODUCT_NAME:rfc1034identifier}";
 				PRODUCT_NAME = "$(TARGET_NAME)";
+				SWIFT_DISABLE_SAFETY_CHECKS = YES;
 				SWIFT_OBJC_BRIDGING_HEADER = CryptoSwiftTests/Bridging.h;
-				SWIFT_OPTIMIZATION_LEVEL = "-Ounchecked";
+				SWIFT_OPTIMIZATION_LEVEL = "-O";
 			};
 			name = Release;
 		};

+ 8 - 5
CryptoSwift.xcodeproj/xcshareddata/xcschemes/CryptoSwift.xcscheme

@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <Scheme
-   LastUpgradeVersion = "0610"
+   LastUpgradeVersion = "0700"
    version = "1.3">
    <BuildAction
       parallelizeBuildables = "NO"
@@ -37,10 +37,10 @@
       </BuildActionEntries>
    </BuildAction>
    <TestAction
+      buildConfiguration = "Debug"
       selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
       selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
-      shouldUseLaunchSchemeArgsEnv = "YES"
-      buildConfiguration = "Release">
+      shouldUseLaunchSchemeArgsEnv = "YES">
       <Testables>
          <TestableReference
             skipped = "NO">
@@ -76,15 +76,18 @@
             ReferencedContainer = "container:CryptoSwift.xcodeproj">
          </BuildableReference>
       </MacroExpansion>
+      <AdditionalOptions>
+      </AdditionalOptions>
    </TestAction>
    <LaunchAction
+      buildConfiguration = "Debug"
       selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
       selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
       launchStyle = "0"
       useCustomWorkingDirectory = "NO"
-      buildConfiguration = "Debug"
       ignoresPersistentStateOnLaunch = "NO"
       debugDocumentVersioning = "YES"
+      debugServiceExtension = "internal"
       allowLocationSimulation = "YES">
       <MacroExpansion>
          <BuildableReference
@@ -99,10 +102,10 @@
       </AdditionalOptions>
    </LaunchAction>
    <ProfileAction
+      buildConfiguration = "Release"
       shouldUseLaunchSchemeArgsEnv = "YES"
       savedToolIdentifier = ""
       useCustomWorkingDirectory = "NO"
-      buildConfiguration = "Release"
       debugDocumentVersioning = "YES">
       <MacroExpansion>
          <BuildableReference

+ 64 - 61
CryptoSwift/AES.swift

@@ -10,6 +10,10 @@ import Foundation
 
 final public class AES {
     
+    enum Error: ErrorType {
+        case BlockSizeExceeded
+    }
+    
     public enum AESVariant:Int {
         case aes128 = 1, aes192, aes256
         
@@ -46,21 +50,21 @@ final public class AES {
     public lazy var expandedKey:[UInt8] = { AES.expandKey(self.key, variant: self.variant) }()
     
     static private let sBox:[UInt8] = [
-        0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 
-        0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 
-        0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 
-        0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 
-        0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 
-        0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 
-        0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 
-        0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 
-        0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 
-        0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 
-        0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 
-        0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 
-        0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 
-        0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 
-        0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 
+        0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
+        0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
+        0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
+        0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
+        0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
+        0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
+        0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
+        0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
+        0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
+        0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
+        0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
+        0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
+        0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
+        0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
+        0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
         0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]
     
     static private let invSBox:[UInt8] = [
@@ -128,8 +132,8 @@ final public class AES {
     convenience public init?(key:String, iv:String, blockMode:CipherBlockMode = .CBC) {
         if let kkey = key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes(), let iiv = iv.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes() {
             self.init(key: kkey, iv: iiv, blockMode: blockMode)
-        } else {
-            self.init(key: [UInt8](), iv: [UInt8](), blockMode: blockMode) //FIXME: this is due Swift bug, remove this line later, when fixed
+        }
+        else {
             return nil
         }
     }
@@ -137,23 +141,22 @@ final public class AES {
     /**
     Encrypt message. If padding is necessary, then PKCS7 padding is added and needs to be removed after decryption.
     
-    :param: message Plaintext data
+    - parameter message: Plaintext data
     
-    :returns: Encrypted data
+    - returns: Encrypted data
     */
-
-    public func encrypt(bytes:[UInt8], padding:Padding? = PKCS7()) -> [UInt8]? {
+    
+    public func encrypt(bytes:[UInt8], padding:Padding? = PKCS7()) throws -> [UInt8] {
         var finalBytes = bytes;
-
+        
         if let padding = padding {
             finalBytes = padding.add(bytes, blockSize: AES.blockSize)
-        } else if (bytes.count % AES.blockSize != 0) {
-            assert(false, "AES block size exceeded!");
-            return nil
+        } else if bytes.count % AES.blockSize != 0 {
+            throw Error.BlockSizeExceeded
         }
-
+        
         let blocks = finalBytes.chunks(AES.blockSize) // 0.34
-        return blockMode.encryptBlocks(blocks, iv: self.iv, cipherOperation: encryptBlock)
+        return try blockMode.encryptBlocks(blocks, iv: self.iv, cipherOperation: encryptBlock)
     }
     
     private func encryptBlock(block:[UInt8]) -> [UInt8]? {
@@ -161,8 +164,8 @@ final public class AES {
         
         autoreleasepool { () -> () in
             var state:[[UInt8]] = [[UInt8]](count: variant.Nb, repeatedValue: [UInt8](count: variant.Nb, repeatedValue: 0))
-            for (i, row) in enumerate(state) {
-                for (j, val) in enumerate(row) {
+            for (i, row) in state.enumerate() {
+                for (j, _) in row.enumerate() {
                     state[j][i] = block[i * row.count + j]
                 }
             }
@@ -179,8 +182,8 @@ final public class AES {
             subBytes(&state)
             state = shiftRows(state)
             state = addRoundKey(state, expandedKey, variant.Nr)
-
-
+            
+            
             out = [UInt8](count: state.count * state.first!.count, repeatedValue: 0)
             for i in 0..<state.count {
                 for j in 0..<state[i].count {
@@ -191,39 +194,39 @@ final public class AES {
         return out
     }
     
-    public func decrypt(bytes:[UInt8], padding:Padding? = PKCS7()) -> [UInt8]? {
-        if (bytes.count % AES.blockSize != 0) {
-            assert(false,"AES block size exceeded!")
-            return nil
+    public func decrypt(bytes:[UInt8], padding:Padding? = PKCS7()) throws -> [UInt8] {
+        if bytes.count % AES.blockSize != 0 {
+            throw Error.BlockSizeExceeded
         }
         
         let blocks = bytes.chunks(AES.blockSize)
-        let out:[UInt8]?
-        if (blockMode == .CFB) {
-            // CFB uses encryptBlock to decrypt
-            out = blockMode.decryptBlocks(blocks, iv: self.iv, cipherOperation: encryptBlock)
-        } else {
-            out = blockMode.decryptBlocks(blocks, iv: self.iv, cipherOperation: decryptBlock)
+        let out:[UInt8]
+        switch (blockMode) {
+        case .CFB, .CTR:
+            // CFB, CTR uses encryptBlock to decrypt
+            out = try blockMode.decryptBlocks(blocks, iv: self.iv, cipherOperation: encryptBlock)
+        default:
+            out = try blockMode.decryptBlocks(blocks, iv: self.iv, cipherOperation: decryptBlock)
         }
         
-        if let out = out, let padding = padding {
+        if let padding = padding {
             return padding.remove(out, blockSize: nil)
         }
         
-        return out;
+        return out
     }
     
     private func decryptBlock(block:[UInt8]) -> [UInt8]? {
         var state:[[UInt8]] = [[UInt8]](count: variant.Nb, repeatedValue: [UInt8](count: variant.Nb, repeatedValue: 0))
-        for (i, row) in enumerate(state) {
-            for (j, val) in enumerate(row) {
+        for (i, row) in state.enumerate() {
+            for (j, _) in row.enumerate() {
                 state[j][i] = block[i * row.count + j]
             }
         }
         
         state = addRoundKey(state,expandedKey, variant.Nr)
         
-        for roundCount in reverse(1..<variant.Nr) {
+        for roundCount in (1..<variant.Nr).reverse() {
             state = invShiftRows(state)
             state = invSubBytes(state)
             state = addRoundKey(state, expandedKey, roundCount)
@@ -258,7 +261,7 @@ final public class AES {
             }
             return result
         }
-
+        
         var w = [UInt8](count: variant.Nb * (variant.Nr + 1) * 4, repeatedValue: 0)
         for i in 0..<variant.Nk {
             for wordIdx in 0..<4 {
@@ -274,13 +277,13 @@ final public class AES {
                 tmp[wordIdx] = w[4*(i-1)+wordIdx]
             }
             if ((i % variant.Nk) == 0) {
-                let rotWord = rotateLeft(UInt32.withBytes(tmp), 8).bytes(sizeof(UInt32)) // RotWord
+                let rotWord = rotateLeft(UInt32.withBytes(tmp), n: 8).bytes(sizeof(UInt32)) // RotWord
                 tmp = subWord(rotWord)
                 tmp[0] = tmp[0] ^ Rcon[i/variant.Nk]
             } else if (variant.Nk > 6 && (i % variant.Nk) == 4) {
                 tmp = subWord(tmp)
             }
-
+            
             // xor array of bytes
             for wordIdx in 0..<4 {
                 w[4*i+wordIdx] = w[4*(i-variant.Nk)+wordIdx]^tmp[wordIdx];
@@ -294,8 +297,8 @@ extension AES {
     
     // byte substitution with table (S-box)
     public func subBytes(inout state:[[UInt8]]) {
-        for (i,row) in enumerate(state) {
-            for (j,value) in enumerate(row) {
+        for (i,row) in state.enumerate() {
+            for (j,value) in row.enumerate() {
                 state[i][j] = AES.sBox[Int(value)]
             }
         }
@@ -303,8 +306,8 @@ extension AES {
     
     public func invSubBytes(state:[[UInt8]]) -> [[UInt8]] {
         var result = state
-        for (i,row) in enumerate(state) {
-            for (j,value) in enumerate(row) {
+        for (i,row) in state.enumerate() {
+            for (j,value) in row.enumerate() {
                 result[i][j] = AES.invSBox[Int(value)]
             }
         }
@@ -337,7 +340,7 @@ extension AES {
         var a = a, b = b
         var p:UInt8 = 0, hbs:UInt8 = 0
         
-        for i in 0..<8 {
+        for _ in 0..<8 {
             if (b & 1 == 1) {
                 p ^= a
             }
@@ -353,14 +356,14 @@ extension AES {
     
     public func matrixMultiplyPolys(matrix:[[UInt8]], _ array:[UInt8]) -> [UInt8] {
         var returnArray:[UInt8] = [UInt8](count: array.count, repeatedValue: 0)
-        for (i, row) in enumerate(matrix) {
-            for (j, boxVal) in enumerate(row) {
+        for (i, row) in matrix.enumerate() {
+            for (j, boxVal) in row.enumerate() {
                 returnArray[i] = multiplyPolys(boxVal, array[j]) ^ returnArray[i]
             }
         }
         return returnArray
     }
-
+    
     public func addRoundKey(state:[[UInt8]], _ expandedKeyW:[UInt8], _ round:Int) -> [[UInt8]] {
         var newState = [[UInt8]](count: state.count, repeatedValue: [UInt8](count: variant.Nb, repeatedValue: 0))
         let idxRow = 4*variant.Nb*round
@@ -377,7 +380,7 @@ extension AES {
     // mixes data (independently of one another)
     public func mixColumns(state:[[UInt8]]) -> [[UInt8]] {
         var state = state
-        var colBox:[[UInt8]] = [[2,3,1,1],[1,2,3,1],[1,1,2,3],[3,1,1,2]]
+        let colBox:[[UInt8]] = [[2,3,1,1],[1,2,3,1],[1,1,2,3],[3,1,1,2]]
         
         var rowMajorState = [[UInt8]](count: state.count, repeatedValue: [UInt8](count: state.first!.count, repeatedValue: 0)) //state.map({ val -> [UInt8] in return val.map { _ in return 0 } }) // zeroing
         var newRowMajorState = rowMajorState
@@ -388,7 +391,7 @@ extension AES {
             }
         }
         
-        for (i, row) in enumerate(rowMajorState) {
+        for (i, row) in rowMajorState.enumerate() {
             newRowMajorState[i] = matrixMultiplyPolys(colBox, row)
         }
         
@@ -403,7 +406,7 @@ extension AES {
     
     public func invMixColumns(state:[[UInt8]]) -> [[UInt8]] {
         var state = state
-        var invColBox:[[UInt8]] = [[14,11,13,9],[9,14,11,13],[13,9,14,11],[11,13,9,14]]
+        let invColBox:[[UInt8]] = [[14,11,13,9],[9,14,11,13],[13,9,14,11],[11,13,9,14]]
         
         var colOrderState = state.map({ val -> [UInt8] in return val.map { _ in return 0 } }) // zeroing
         
@@ -415,7 +418,7 @@ extension AES {
         
         var newState = state.map({ val -> [UInt8] in return val.map { _ in return 0 } })
         
-        for (i, row) in enumerate(colOrderState) {
+        for (i, row) in colOrderState.enumerate() {
             newState[i] = matrixMultiplyPolys(invColBox, row)
         }
         

+ 4 - 4
CryptoSwift/ArrayExtension.swift

@@ -11,17 +11,17 @@ import Foundation
 extension Array {
     
     /** split in chunks with given chunk size */
-    func chunks(chunksize:Int) -> [Array<T>] {
-        var words = [[T]]()
+    func chunks(chunksize:Int) -> [Array<Element>] {
+        var words = [[Element]]()
         words.reserveCapacity(self.count / chunksize)        
         for var idx = chunksize; idx <= self.count; idx = idx + chunksize {
             let word = Array(self[idx - chunksize..<idx]) // this is slow for large table
             words.append(word)
         }
-        let reminder = Array(suffix(self, self.count % chunksize))
+        let reminder = Array(self.suffix(self.count % chunksize))
         if (reminder.count > 0) {
             words.append(reminder)
         }
         return words
     }
-}
+}

+ 2 - 2
CryptoSwift/Authenticator.swift

@@ -15,7 +15,7 @@ public enum Authenticator {
     /**
     Poly1305
     
-    :param: key 256-bit key
+    - parameter key: 256-bit key
     */
     case Poly1305(key: [UInt8])
     case HMAC(key: [UInt8], variant:CryptoSwift.HMAC.Variant)
@@ -23,7 +23,7 @@ public enum Authenticator {
     /**
     Generates an authenticator for message using a one-time key and returns the 16-byte result
     
-    :returns: 16-byte message authentication code
+    - returns: 16-byte message authentication code
     */
     public func authenticate(message: [UInt8]) -> [UInt8]? {
         switch (self) {

+ 9 - 5
CryptoSwift/CRC.swift

@@ -45,15 +45,19 @@ final class CRC {
     
     func crc32(message:NSData) -> NSData {
         var crc:UInt32 = 0xffffffff
-        for b in message.arrayOfBytes() {
-            var idx = Int((crc ^ UInt32(b)) & 0xff)
-            crc = (crc >> 8) ^ table[idx]
+        
+        for chunk in NSDataSequence(chunkSize: 256, data: message) {
+            for b in chunk.arrayOfBytes() {
+                let idx = Int((crc ^ UInt32(b)) & 0xff)
+                crc = (crc >> 8) ^ table[idx]
+            }
         }
+        
         crc = crc ^ 0xffffffff
         
         // reverse bytes
-        let bytes = NSMutableData(bytes: &crc, length: 4).arrayOfBytes().reverse()
-        var data = NSData(bytes: bytes, length: bytes.count)
+        let bytes = Array(NSMutableData(bytes: &crc, length: 4).arrayOfBytes().reverse()) //FIXME: Array ??
+        let data = NSData(bytes: bytes, length: bytes.count)
         return data
     }
     

+ 48 - 45
CryptoSwift/ChaCha20.swift

@@ -10,6 +10,10 @@ import Foundation
 
 final public class ChaCha20 {
     
+    enum Error: ErrorType {
+        case MissingContext
+    }
+    
     static let blockSize = 64 // 512 / 8
     private let stateSize = 16
     private var context:Context?
@@ -35,23 +39,21 @@ final public class ChaCha20 {
     convenience public init?(key:String, iv:String) {
         if let kkey = key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes(), let iiv = iv.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes() {
             self.init(key: kkey, iv: iiv)
-        } else {
-            self.init(key: [UInt8](), iv: [UInt8]()) //FIXME: this is due Swift bug, remove this line later, when fixed
-            return nil
         }
+        return nil
     }
 
     
-    public func encrypt(bytes:[UInt8]) -> [UInt8]? {
-        if (context == nil) {
-            return nil
+    public func encrypt(bytes:[UInt8]) throws -> [UInt8] {
+        guard context != nil else {
+            throw Error.MissingContext
         }
         
-        return encryptBytes(bytes)
+        return try encryptBytes(bytes)
     }
     
-    public func decrypt(bytes:[UInt8]) -> [UInt8]? {
-        return encrypt(bytes)
+    public func decrypt(bytes:[UInt8]) throws -> [UInt8] {
+        return try encrypt(bytes)
     }
     
     private final func wordToByte(input:[UInt32] /* 64 */) -> [UInt8]? /* 16 */ {
@@ -78,18 +80,18 @@ final public class ChaCha20 {
         output.reserveCapacity(16)
 
         for i in 0..<16 {
-            x[i] = x[i] &+ input[i]
-            output += [UInt8((x[i] & 0xFFFFFFFF) >> 24),
+            x[i] = x[i] &+ input[i]            
+            output.appendContentsOf([UInt8((x[i] & 0xFFFFFFFF) >> 24),
                        UInt8((x[i] & 0xFFFFFF) >> 16),
                        UInt8((x[i] & 0xFFFF) >> 8),
-                       UInt8((x[i] & 0xFF) >> 0)]
+                       UInt8((x[i] & 0xFF) >> 0)])
         }
 
         return output;
     }
         
-    private func contextSetup(# iv:[UInt8], key:[UInt8]) -> Context? {
-        var ctx = Context()
+    private func contextSetup(iv  iv:[UInt8], key:[UInt8]) -> Context? {
+        let ctx = Context()
         let kbits = key.count * 8
         
         if (kbits != 128 && kbits != 256) {
@@ -137,52 +139,53 @@ final public class ChaCha20 {
         return ctx
     }
     
-    private final func encryptBytes(message:[UInt8]) -> [UInt8]? {
+    private final func encryptBytes(message:[UInt8]) throws -> [UInt8] {
         
-        if let ctx = context {
-            var c:[UInt8] = [UInt8](count: message.count, repeatedValue: 0)
-            
-            var cPos:Int = 0
-            var mPos:Int = 0
-            var bytes = message.count
-            
-            while (true) {
-                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
-                        /* stopping at 2^70 bytes per nonce is user's responsibility */
-                    }
-                    if (bytes <= ChaCha20.blockSize) {
-                        for (var i = 0; i < bytes; i++) {
-                            c[i + cPos] = message[i + mPos] ^ output[i]
-                        }
-                        return c
-                    }
-                    for (var i = 0; i < ChaCha20.blockSize; i++) {
+        guard let ctx = context else {
+            throw Error.MissingContext
+        }
+        
+        var c:[UInt8] = [UInt8](count: message.count, repeatedValue: 0)
+        
+        var cPos:Int = 0
+        var mPos:Int = 0
+        var bytes = message.count
+        
+        while (true) {
+            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
+                    /* stopping at 2^70 bytes per nonce is user's responsibility */
+                }
+                if (bytes <= ChaCha20.blockSize) {
+                    for (var i = 0; i < bytes; i++) {
                         c[i + cPos] = message[i + mPos] ^ output[i]
                     }
-                    bytes -= ChaCha20.blockSize
-                    cPos += ChaCha20.blockSize
-                    mPos += ChaCha20.blockSize
+                    return c
+                }
+                for (var i = 0; i < ChaCha20.blockSize; i++) {
+                    c[i + cPos] = message[i + mPos] ^ output[i]
                 }
+                bytes -= ChaCha20.blockSize
+                cPos += ChaCha20.blockSize
+                mPos += ChaCha20.blockSize
             }
         }
-        return nil;
     }
     
     private final func quarterround(inout a:UInt32, inout _ b:UInt32, inout _ c:UInt32, inout _ d:UInt32) {
         a = a &+ b
-        d = rotateLeft((d ^ a), 16)
+        d = rotateLeft((d ^ a), n: 16) //FIXME: WAT? n:
         
         c = c &+ d
-        b = rotateLeft((b ^ c), 12);
+        b = rotateLeft((b ^ c), n: 12);
         
         a = a &+ b
-        d = rotateLeft((d ^ a), 8);
+        d = rotateLeft((d ^ a), n: 8);
 
         c = c &+ d
-        b = rotateLeft((b ^ c), 7);
+        b = rotateLeft((b ^ c), n: 7);
     }
 }
 
@@ -191,7 +194,7 @@ final public class ChaCha20 {
 /// Change array to number. It's here because arrayOfBytes is too slow
 private func wordNumber(bytes:ArraySlice<UInt8>) -> UInt32 {
     var value:UInt32 = 0
-    for (var i:UInt32 = 0, j = 0; i < 4; i++, j++) {
+    for (var i:UInt32 = 0, j = bytes.startIndex; i < 4; i++, j++) {
         value = value | UInt32(bytes[j]) << (8 * i)
     }
     return value

+ 35 - 21
CryptoSwift/Cipher.swift

@@ -9,59 +9,73 @@
 import Foundation
 
 public enum Cipher {
+    
+    public enum Error: ErrorType {
+        case EncryptError
+        case DecryptError
+    }
+    
     /**
     ChaCha20
     
-    :param: key Encryption key
-    :param: iv  Initialization Vector
+    - parameter key: Encryption key
+    - parameter iv:  Initialization Vector
     
-    :returns: Value of Cipher
+    - returns: Value of Cipher
     */
     case ChaCha20(key: [UInt8], iv: [UInt8])
     /**
     AES
     
-    :param: key       Encryption key
-    :param: iv        Initialization Vector
-    :param: blockMode Block mode (CBC by default)
+    - parameter key:       Encryption key
+    - parameter iv:        Initialization Vector
+    - parameter blockMode: Block mode (CBC by default)
     
-    :returns: Value of Cipher
+    - returns: Value of Cipher
     */
     case AES(key: [UInt8], iv: [UInt8], blockMode: CipherBlockMode)
     
     /**
     Encrypt message
     
-    :param: message Plaintext message
+    - parameter message: Plaintext message
     
-    :returns: encrypted message
+    - returns: encrypted message
     */
-    public func encrypt(bytes: [UInt8]) -> [UInt8]? {
+    public func encrypt(bytes: [UInt8]) throws -> [UInt8] {
         switch (self) {
             case .ChaCha20(let key, let iv):
-                var chacha = CryptoSwift.ChaCha20(key: key, iv: iv)
-                return chacha?.encrypt(bytes)
+                guard let chacha = CryptoSwift.ChaCha20(key: key, iv: iv) else {
+                    throw Error.EncryptError
+                }
+                return try chacha.encrypt(bytes)
             case .AES(let key, let iv, let blockMode):
-                var aes = CryptoSwift.AES(key: key, iv: iv, blockMode: blockMode)
-                return aes?.encrypt(bytes)
+                guard let aes = CryptoSwift.AES(key: key, iv: iv, blockMode: blockMode) else {
+                    throw Error.EncryptError
+                }
+                return try aes.encrypt(bytes)
         }
     }
     
     /**
     Decrypt message
     
-    :param: message Message data
+    - parameter message: Message data
     
-    :returns: Plaintext message
+    - returns: Plaintext message
     */
-    public func decrypt(bytes: [UInt8]) -> [UInt8]? {
+    public func decrypt(bytes: [UInt8]) throws -> [UInt8] {
         switch (self) {
             case .ChaCha20(let key, let iv):
-                var chacha = CryptoSwift.ChaCha20(key: key, iv: iv);
-                return chacha?.decrypt(bytes)
+                guard let chacha = CryptoSwift.ChaCha20(key: key, iv: iv) else {
+                    throw Error.DecryptError
+                }
+                return try chacha.decrypt(bytes)
             case .AES(let key, let iv, let blockMode):
-                var aes = CryptoSwift.AES(key: key, iv: iv, blockMode: blockMode);
-                return aes?.decrypt(bytes)
+                guard let aes = CryptoSwift.AES(key: key, iv: iv, blockMode: blockMode) else {
+                    throw Error.DecryptError
+                }
+                return try aes.decrypt(bytes)
         }
     }
 

+ 102 - 45
CryptoSwift/CipherBlockMode.swift

@@ -11,14 +11,18 @@ import Foundation
 // I have no better name for that
 typealias CipherOperationOnBlock = (block: [UInt8]) -> [UInt8]?
 
+enum BlockError: ErrorType {
+    case MissingInitializationVector
+}
+
 private protocol BlockMode {
     var needIV:Bool { get }
-    func encryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) -> [UInt8]?
-    func decryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) -> [UInt8]?
+    func encryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) throws -> [UInt8]
+    func decryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) throws -> [UInt8]
 }
 
 public enum CipherBlockMode {
-    case ECB, CBC, CFB
+    case ECB, CBC, CFB, CTR
     
     private var mode:BlockMode {
         switch (self) {
@@ -28,6 +32,8 @@ public enum CipherBlockMode {
             return CFBMode()
         case ECB:
             return ECBMode()
+        case CTR:
+            return CTRMode()
         }
     }
     
@@ -38,13 +44,13 @@ public enum CipherBlockMode {
     /**
     Process input blocks with given block cipher mode. With fallback to plain mode.
     
-    :param: blocks cipher block size blocks
-    :param: iv     IV
-    :param: cipher single block encryption closure
+    - parameter blocks: cipher block size blocks
+    - parameter iv:     IV
+    - parameter cipher: single block encryption closure
     
-    :returns: encrypted bytes
+    - returns: encrypted bytes
     */
-    func encryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) -> [UInt8]? {
+    func encryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) throws -> [UInt8] {
         
         // if IV is not available, fallback to plain
         var finalBlockMode:CipherBlockMode = self
@@ -52,59 +58,56 @@ public enum CipherBlockMode {
             finalBlockMode = .ECB
         }
         
-        return finalBlockMode.mode.encryptBlocks(blocks, iv: iv, cipherOperation: cipherOperation)
+        return try finalBlockMode.mode.encryptBlocks(blocks, iv: iv, cipherOperation: cipherOperation)
     }
     
-    func decryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:(block:[UInt8]) -> [UInt8]?) -> [UInt8]? {
+    func decryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) throws -> [UInt8] {
         // if IV is not available, fallback to plain
         var finalBlockMode:CipherBlockMode = self
         if (iv == nil) {
             finalBlockMode = .ECB
         }
 
-        return finalBlockMode.mode.decryptBlocks(blocks, iv: iv, cipherOperation: cipherOperation)
+        return try finalBlockMode.mode.decryptBlocks(blocks, iv: iv, cipherOperation: cipherOperation)
     }
 }
 
 /**
-*  Cipher-block chaining (CBC)
+Cipher-block chaining (CBC)
 */
 private struct CBCMode: BlockMode {
-    var needIV:Bool = true
+    let needIV = true
     
-    func encryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) -> [UInt8]? {
+    func encryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) throws -> [UInt8] {
         precondition(blocks.count > 0)
-        assert(iv != nil, "CFB require IV")
-        if (iv == nil) {
-            return nil;
+        guard let iv = iv else {
+            throw BlockError.MissingInitializationVector
         }
         
-        
         var out:[UInt8] = [UInt8]()
         out.reserveCapacity(blocks.count * blocks[0].count)
-        var prevCiphertext = iv! // for the first time prevCiphertext = iv
+        var prevCiphertext = iv // for the first time prevCiphertext = iv
         for plaintext in blocks {
-            if let encrypted = cipherOperation(block: xor(prevCiphertext, plaintext)) {
-                out.extend(encrypted)
+            if let encrypted = cipherOperation(block: xor(prevCiphertext, b: plaintext)) {
+                out.appendContentsOf(encrypted)
                 prevCiphertext = encrypted
             }
         }
-        return out;
+        return out
     }
     
-    func decryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) -> [UInt8]? {
+    func decryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) throws -> [UInt8] {
         precondition(blocks.count > 0)
-        assert(iv != nil, "CFB require IV")
-        if (iv == nil) {
-            return nil
+        guard let iv = iv else {
+            throw BlockError.MissingInitializationVector
         }
 
         var out:[UInt8] = [UInt8]()
         out.reserveCapacity(blocks.count * blocks[0].count)
-        var prevCiphertext = iv! // for the first time prevCiphertext = iv
+        var prevCiphertext = iv // for the first time prevCiphertext = iv
         for ciphertext in blocks {
             if let decrypted = cipherOperation(block: ciphertext) { // decrypt
-                out.extend(xor(prevCiphertext, decrypted))
+                out.appendContentsOf(xor(prevCiphertext, b: decrypted)) //FIXME: b:
             }
             prevCiphertext = ciphertext
         }
@@ -114,53 +117,107 @@ private struct CBCMode: BlockMode {
 }
 
 /**
-*  Cipher feedback (CFB)
+Cipher feedback (CFB)
 */
 private struct CFBMode: BlockMode {
-    var needIV:Bool = true
+    let needIV = true
     
-    func encryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) -> [UInt8]? {
-        assert(iv != nil, "CFB require IV")
-        if (iv == nil) {
-            return nil
+    func encryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) throws -> [UInt8] {
+        guard let iv = iv else {
+            throw BlockError.MissingInitializationVector
         }
         
         var out:[UInt8] = [UInt8]()
         out.reserveCapacity(blocks.count * blocks[0].count)
 
-        var lastCiphertext = iv!
+        var lastCiphertext = iv
         for plaintext in blocks {
             if let encrypted = cipherOperation(block: lastCiphertext) {
-                lastCiphertext = xor(plaintext,encrypted)
-                out.extend(lastCiphertext)
+                lastCiphertext = xor(plaintext,b: encrypted)
+                out.appendContentsOf(lastCiphertext)
             }
         }
-        return out;
+        return out
     }
     
-    func decryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) -> [UInt8]? {
-        return encryptBlocks(blocks, iv: iv, cipherOperation: cipherOperation)
+    func decryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) throws -> [UInt8] {
+        return try encryptBlocks(blocks, iv: iv, cipherOperation: cipherOperation)
     }
 }
 
 
 /**
-*  Electronic codebook (ECB)
+Electronic codebook (ECB)
 */
 private struct ECBMode: BlockMode {
-    var needIV:Bool = false
-    func encryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) -> [UInt8]? {
+    let needIV = false
+    
+    func encryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) -> [UInt8] {
         var out:[UInt8] = [UInt8]()
         out.reserveCapacity(blocks.count * blocks[0].count)
         for plaintext in blocks {
             if let encrypted = cipherOperation(block: plaintext) {
-                out.extend(encrypted)
+                out.appendContentsOf(encrypted)
             }
         }
         return out
     }
     
-    func decryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) -> [UInt8]? {
+    func decryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) -> [UInt8] {
         return encryptBlocks(blocks, iv: iv, cipherOperation: cipherOperation)
     }
 }
+
+/**
+Counter (CTR)
+*/
+private struct CTRMode: BlockMode {
+    let needIV = true
+    
+    private func buildNonce(iv: [UInt8], counter: UInt) -> [UInt8] {
+        let noncePartLen = AES.blockSize / 2
+        let noncePrefix = Array(iv[0..<noncePartLen])
+        let nonceSuffix = arrayOfBytes(counter)
+        
+        var nonce = noncePrefix
+        nonce += nonceSuffix
+        return nonce
+    }
+    
+    func encryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) throws -> [UInt8] {
+        //var counter:UInt = 17940646550795321087
+        
+        guard let iv = iv else {
+            throw BlockError.MissingInitializationVector
+        }
+
+        var counter:UInt = 0
+        var out:[UInt8] = [UInt8]()
+        out.reserveCapacity(blocks.count * blocks[0].count)
+        for plaintext in blocks {
+            let nonce = buildNonce(iv, counter: counter++)
+            if let encrypted = cipherOperation(block: nonce) {
+                out.appendContentsOf(xor(plaintext, b: encrypted))
+            }
+        }
+        return out
+    }
+    
+    func decryptBlocks(blocks:[[UInt8]], iv:[UInt8]?, cipherOperation:CipherOperationOnBlock) throws -> [UInt8] {
+        guard let iv = iv else {
+            throw BlockError.MissingInitializationVector
+        }
+        
+        var counter:UInt = 0
+        var out:[UInt8] = [UInt8]()
+        out.reserveCapacity(blocks.count * blocks[0].count)
+        for plaintext in blocks {
+            let nonce = buildNonce(iv, counter: counter++)
+            if let encrypted = cipherOperation(block: nonce) {
+                out.appendContentsOf(xor(encrypted, b: plaintext))
+            }
+        }
+        return out
+    }
+
+}

+ 19 - 20
CryptoSwift/Generics.swift

@@ -25,7 +25,7 @@ extension UInt64:Initiable {}
 func integerFromBitsArray<T: UnsignedIntegerType>(bits: [Bit]) -> T
 {
     var bitPattern:T = 0
-    for (idx,b) in enumerate(bits) {
+    for (idx,b) in bits.enumerate() {
         if (b == Bit.One) {
             let bit = T(UIntMax(1) << UIntMax(idx))
             bitPattern = bitPattern | bit
@@ -37,7 +37,7 @@ func integerFromBitsArray<T: UnsignedIntegerType>(bits: [Bit]) -> T
 /// Initialize integer from array of bytes.
 /// This method may be slow
 func integerWithBytes<T: IntegerType where T:ByteConvertible, T: BitshiftOperationsType>(bytes: [UInt8]) -> T {
-    var bytes = bytes.reverse()
+    var bytes = bytes.reverse() as Array<UInt8> //FIXME: check it this is equivalent of Array(...)
     if bytes.count < sizeof(T) {
         let paddingCount = sizeof(T) - bytes.count
         if (paddingCount > 0) {
@@ -50,7 +50,7 @@ func integerWithBytes<T: IntegerType where T:ByteConvertible, T: BitshiftOperati
     }
     
     var result: T = 0
-    for byte in bytes.reverse() {
+    for byte in Array(bytes.reverse()) { //FIXME: Array??
         result = result << 8 | T(byte)
     }
     return result
@@ -60,12 +60,11 @@ func integerWithBytes<T: IntegerType where T:ByteConvertible, T: BitshiftOperati
 /// I found this method slow
 func arrayOfBytes<T>(value:T, length:Int? = nil) -> [UInt8] {
     let totalBytes = length ?? sizeof(T)
-    var v = value
     
-    var valuePointer = UnsafeMutablePointer<T>.alloc(1)
+    let valuePointer = UnsafeMutablePointer<T>.alloc(1)
     valuePointer.memory = value
     
-    var bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer)
+    let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer)
     var bytes = [UInt8](count: totalBytes, repeatedValue: 0)
     for j in 0..<min(sizeof(T),totalBytes) {
         bytes[totalBytes - 1 - j] = (bytesPointer + j).memory
@@ -80,13 +79,13 @@ func arrayOfBytes<T>(value:T, length:Int? = nil) -> [UInt8] {
 // MARK: - shiftLeft
 
 // helper to be able tomake shift operation on T
-func <<<T:SignedIntegerType>(lhs: T, rhs: Int) -> Int {
+func << <T:SignedIntegerType>(lhs: T, rhs: Int) -> Int {
     let a = lhs as! Int
     let b = rhs
     return a << b
 }
 
-func <<<T:UnsignedIntegerType>(lhs: T, rhs: Int) -> UInt {
+func << <T:UnsignedIntegerType>(lhs: T, rhs: Int) -> UInt {
     let a = lhs as! UInt
     let b = rhs
     return a << b
@@ -99,12 +98,12 @@ func shiftLeft<T: SignedIntegerType where T: Initiable>(value: T, count: Int) ->
         return 0;
     }
     
-    var bitsCount = (sizeofValue(value) * 8)
-    var shiftCount = Int(Swift.min(count, bitsCount - 1))
+    let bitsCount = (sizeofValue(value) * 8)
+    let shiftCount = Int(Swift.min(count, bitsCount - 1))
     
     var shiftedValue:T = 0;
     for bitIdx in 0..<bitsCount {
-        var bit = T(IntMax(1 << bitIdx))
+        let bit = T(IntMax(1 << bitIdx))
         if ((value & bit) == bit) {
             shiftedValue = shiftedValue | T(bit << shiftCount)
         }
@@ -119,38 +118,38 @@ func shiftLeft<T: SignedIntegerType where T: Initiable>(value: T, count: Int) ->
 
 // for any f*** other Integer type - this part is so non-Generic
 func shiftLeft(value: UInt, count: Int) -> UInt {
-    return UInt(shiftLeft(Int(value), count))
+    return UInt(shiftLeft(Int(value), count: count)) //FIXME: count:
 }
 
 func shiftLeft(value: UInt8, count: Int) -> UInt8 {
-    return UInt8(shiftLeft(UInt(value), count))
+    return UInt8(shiftLeft(UInt(value), count: count))
 }
 
 func shiftLeft(value: UInt16, count: Int) -> UInt16 {
-    return UInt16(shiftLeft(UInt(value), count))
+    return UInt16(shiftLeft(UInt(value), count: count))
 }
 
 func shiftLeft(value: UInt32, count: Int) -> UInt32 {
-    return UInt32(shiftLeft(UInt(value), count))
+    return UInt32(shiftLeft(UInt(value), count: count))
 }
 
 func shiftLeft(value: UInt64, count: Int) -> UInt64 {
-    return UInt64(shiftLeft(UInt(value), count))
+    return UInt64(shiftLeft(UInt(value), count: count))
 }
 
 func shiftLeft(value: Int8, count: Int) -> Int8 {
-    return Int8(shiftLeft(Int(value), count))
+    return Int8(shiftLeft(Int(value), count: count))
 }
 
 func shiftLeft(value: Int16, count: Int) -> Int16 {
-    return Int16(shiftLeft(Int(value), count))
+    return Int16(shiftLeft(Int(value), count: count))
 }
 
 func shiftLeft(value: Int32, count: Int) -> Int32 {
-    return Int32(shiftLeft(Int(value), count))
+    return Int32(shiftLeft(Int(value), count: count))
 }
 
 func shiftLeft(value: Int64, count: Int) -> Int64 {
-    return Int64(shiftLeft(Int(value), count))
+    return Int64(shiftLeft(Int(value), count: count))
 }
 

+ 5 - 5
CryptoSwift/HMAC.swift

@@ -28,7 +28,7 @@ final public class HMAC {
             }
         }
         
-        func calculateHash(# bytes:[UInt8]) -> [UInt8]? {
+        func calculateHash(bytes  bytes:[UInt8]) -> [UInt8]? {
             switch (self) {
             case .sha1:
                 return NSData.withBytes(bytes).sha1()?.arrayOfBytes()
@@ -56,7 +56,7 @@ final public class HMAC {
     var key:[UInt8]
     let variant:Variant
     
-    class internal func authenticate(# key: [UInt8], message: [UInt8], variant:HMAC.Variant = .md5) -> [UInt8]? {
+    class internal func authenticate(key  key: [UInt8], message: [UInt8], variant:HMAC.Variant = .md5) -> [UInt8]? {
         return HMAC(key, variant: variant)?.authenticate(message: message)
     }
 
@@ -77,13 +77,13 @@ final public class HMAC {
         }
     }
     
-    internal func authenticate(# message:[UInt8]) -> [UInt8]? {
+    internal func authenticate(message  message:[UInt8]) -> [UInt8]? {
         var opad = [UInt8](count: variant.blockSize(), repeatedValue: 0x5c)
-        for (idx, val) in enumerate(key) {
+        for (idx, _) in key.enumerate() {
             opad[idx] = key[idx] ^ opad[idx]
         }
         var ipad = [UInt8](count: variant.blockSize(), repeatedValue: 0x36)
-        for (idx, val) in enumerate(key) {
+        for (idx, _) in key.enumerate() {
             ipad[idx] = key[idx] ^ ipad[idx]
         }
 

+ 0 - 2
CryptoSwift/Hash.swift

@@ -30,8 +30,6 @@ public enum Hash {
             return SHA2(data, variant: .sha512).calculate64()
         case crc32(let data):
             return CRC().crc32(data);
-        default:
-            return nil
         }
     }
 }

+ 16 - 21
CryptoSwift/HashBase.swift → CryptoSwift/HashProtocol.swift

@@ -1,5 +1,5 @@
 //
-//  Hash.swift
+//  HashProtocol.swift
 //  CryptoSwift
 //
 //  Created by Marcin Krzyzanowski on 17/08/14.
@@ -8,22 +8,17 @@
 
 import Foundation
 
-protocol _Hash {
-    var size:Int { get }
-    func prepare(len:Int) -> NSMutableData;
-}
+internal protocol HashProtocol {
+    var message: NSData { get }
 
-internal class HashBase {
-    
-    var message: NSData
-    
-    internal init(_ message: NSData) {
-        self.message = message
-    }
-    
     /** Common part for hash calculation. Prepare header data. */
-    internal func prepare(_ len:Int = 64) -> NSMutableData {
-        var tmpMessage: NSMutableData = NSMutableData(data: self.message)
+    func prepare(len:Int) -> NSMutableData
+}
+
+extension HashProtocol {
+
+    func prepare(len:Int) -> NSMutableData {
+        let tmpMessage: NSMutableData = NSMutableData(data: self.message)
         
         // Step 1. Append Padding Bits
         tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message
@@ -31,19 +26,19 @@ internal class HashBase {
         // append "0" bit until message length in bits ≡ 448 (mod 512)
         var msgLength = tmpMessage.length
         var counter = 0
-      
+        
         while msgLength % len != (len - 8) {
             counter++
             msgLength++
         }
-      
-        var bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8)))
-      
+        
+        let bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8)))
+        
         tmpMessage.appendBytes(bufZeros, length: counter)
-      
+        
         bufZeros.destroy()
         bufZeros.dealloc(1)
-      
+        
         return tmpMessage
     }
 }

+ 6 - 6
CryptoSwift/IntExtension.swift

@@ -26,7 +26,7 @@ extension Int {
 /* array of bytes */
 extension Int {
     /** Array of bytes with optional padding (little-endian) */
-    public func bytes(_ totalBytes: Int = sizeof(Int)) -> [UInt8] {
+    public func bytes(totalBytes: Int = sizeof(Int)) -> [UInt8] {
         return arrayOfBytes(self, length: totalBytes)
     }
 
@@ -47,7 +47,7 @@ extension Int {
     
     /** Shift bits to the left. All bits are shifted (including sign bit) */
     private mutating func shiftLeft(count: Int) -> Int {
-        self = CryptoSwift.shiftLeft(self, count)
+        self = CryptoSwift.shiftLeft(self, count: count) //FIXME: count:
         return self
     }
     
@@ -57,19 +57,19 @@ extension Int {
             return self;
         }
         
-        var bitsCount = sizeofValue(self) * 8
+        let bitsCount = sizeofValue(self) * 8
 
         if (count >= bitsCount) {
             return 0
         }
 
-        var maxBitsForValue = Int(floor(log2(Double(self)) + 1))
-        var shiftCount = Swift.min(count, maxBitsForValue - 1)
+        let maxBitsForValue = Int(floor(log2(Double(self)) + 1))
+        let shiftCount = Swift.min(count, maxBitsForValue - 1)
         var shiftedValue:Int = 0;
         
         for bitIdx in 0..<bitsCount {
             // if bit is set then copy to result and shift left 1
-            var bit = 1 << bitIdx
+            let bit = 1 << bitIdx
             if ((self & bit) == bit) {
                 shiftedValue = shiftedValue | (bit >> shiftCount)
             }

+ 16 - 15
CryptoSwift/MD5.swift

@@ -8,9 +8,14 @@
 
 import Foundation
 
-final class MD5 : CryptoSwift.HashBase, _Hash {
+final class MD5 : HashProtocol  {
     var size:Int = 16 // 128 / 8
+    let message: NSData
     
+    init (_ message: NSData) {
+        self.message = message
+    }
+
     /** specifies the per-round shift amounts */
     private let s: [UInt32] = [7, 12, 17, 22,  7, 12, 17, 22,  7, 12, 17, 22,  7, 12, 17, 22,
                        5,  9, 14, 20,  5,  9, 14, 20,  5,  9, 14, 20,  5,  9, 14, 20,
@@ -38,25 +43,21 @@ final class MD5 : CryptoSwift.HashBase, _Hash {
     private let h:[UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
     
     func calculate() -> NSData {
-        var tmpMessage = prepare()
+        let tmpMessage = prepare(64)
 
         // hash values
         var hh = h
         
         // Step 2. Append Length a 64-bit representation of lengthInBits
-        var lengthInBits = (message.length * 8)
-        var lengthBytes = lengthInBits.bytes(64 / 8)
-        tmpMessage.appendBytes(reverse(lengthBytes));
+        let lengthInBits = (message.length * 8)
+        let lengthBytes = lengthInBits.bytes(64 / 8)
+        tmpMessage.appendBytes(Array(lengthBytes.reverse())); //FIXME: Array?
 
         // Process the message in successive 512-bit chunks:
         let chunkSizeBytes = 512 / 8 // 64
-        var leftMessageBytes = tmpMessage.length
-        for (var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes) {
-            let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes)))
-            let bytes = tmpMessage.bytes;
-            
+        for chunk in NSDataSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
             // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
-            var M:[UInt32] = [UInt32](count: 16, repeatedValue: 0)
+            var M = [UInt32](count: 16, repeatedValue: 0)
             let range = NSRange(location:0, length: M.count * sizeof(UInt32))
             chunk.getBytes(UnsafeMutablePointer<Void>(M), range: range)
             
@@ -96,7 +97,7 @@ final class MD5 : CryptoSwift.HashBase, _Hash {
                 dTemp = D
                 D = C
                 C = B
-                B = B &+ rotateLeft((A &+ F &+ k[j] &+ M[g]), s[j])
+                B = B &+ rotateLeft((A &+ F &+ k[j] &+ M[g]), n: s[j])
                 A = dTemp    
             }
             
@@ -106,13 +107,13 @@ final class MD5 : CryptoSwift.HashBase, _Hash {
             hh[3] = hh[3] &+ D
         }
 
-        var buf: NSMutableData = NSMutableData();
-        hh.map({ (item) -> () in
+        let buf: NSMutableData = NSMutableData();
+        hh.forEach({ (item) -> () in
             var i:UInt32 = item.littleEndian
             buf.appendBytes(&i, length: sizeofValue(i))
         })
         
-        return buf.copy() as! NSData;
+        return buf.copy() as! NSData
     }
 }
 

+ 7 - 11
CryptoSwift/NSDataExtension.swift

@@ -25,7 +25,7 @@ extension NSData {
         var bytesArray = self.arrayOfBytes()
         
         for (var i = 0; i < bytesArray.count; i++) {
-            var b = bytesArray[i]
+            _ = bytesArray[i]
             s = s + UInt32(bytesArray[i])
         }
         s = s % 65536;
@@ -60,18 +60,14 @@ extension NSData {
         return Hash.crc32(self).calculate()
     }
 
-    public func encrypt(cipher: Cipher) -> NSData? {
-        if let encrypted = cipher.encrypt(self.arrayOfBytes()) {
-            return NSData.withBytes(encrypted)
-        }
-        return nil
+    public func encrypt(cipher: Cipher) throws -> NSData? {
+        let encrypted = try cipher.encrypt(self.arrayOfBytes())
+        return NSData.withBytes(encrypted)
     }
 
-    public func decrypt(cipher: Cipher) -> NSData? {
-        if let decrypted = cipher.decrypt(self.arrayOfBytes()) {
-            return NSData.withBytes(decrypted)
-        }
-        return nil;
+    public func decrypt(cipher: Cipher) throws -> NSData? {
+        let decrypted = try cipher.decrypt(self.arrayOfBytes())
+        return NSData.withBytes(decrypted)
     }
     
     public func authenticate(authenticator: Authenticator) -> NSData? {

+ 26 - 0
CryptoSwift/NSDataSequence.swift

@@ -0,0 +1,26 @@
+//
+//  NSDataSequence.swift
+//  CryptoSwift
+//
+//  Created by Marcin Krzyzanowski on 15/07/15.
+//  Copyright © 2015 Marcin Krzyzanowski. All rights reserved.
+//
+
+import Foundation
+
+struct NSDataSequence: SequenceType {
+    
+    let chunkSize: Int
+    let data: NSData
+    
+    func generate() -> AnyGenerator<NSData> {
+        
+        var offset:Int = 0
+        
+        return anyGenerator {
+            let result = self.data.subdataWithRange(NSRange(location: offset, length: min(self.chunkSize, self.data.length - offset)))
+            offset += result.length
+            return result.length > 0 ? result : nil
+        }
+    }
+}

+ 7 - 7
CryptoSwift/PKCS7.swift

@@ -18,25 +18,25 @@ public struct PKCS7: Padding {
     }
     
     public func add(bytes: [UInt8] , blockSize:Int) -> [UInt8] {
-        var padding = UInt8(blockSize - (bytes.count % blockSize))
+        let padding = UInt8(blockSize - (bytes.count % blockSize))
         var withPadding = bytes
         if (padding == 0) {
             // If the original data is a multiple of N bytes, then an extra block of bytes with value N is added.
-            for i in 0..<blockSize {
-                withPadding.extend([UInt8(blockSize)])
+            for _ in 0..<blockSize {
+                withPadding.appendContentsOf([UInt8(blockSize)])
             }
         } else {
             // The value of each added byte is the number of bytes that are added
-            for i in 0..<padding {
-                withPadding.extend([UInt8(padding)])
+            for _ in 0..<padding {
+                withPadding.appendContentsOf([UInt8(padding)])
             }
         }
         return withPadding
     }
     
-    public func remove(bytes: [UInt8], blockSize:Int? = nil) -> [UInt8] {
+    public func remove(bytes: [UInt8], blockSize:Int?) -> [UInt8] {
         let lastByte = bytes.last!
-        var padding = Int(lastByte) // last byte
+        let padding = Int(lastByte) // last byte
         
         if padding >= 1 { //TODO: need test for that, what about empty padding
             return Array(bytes[0..<(bytes.count - padding)])

+ 2 - 2
CryptoSwift/Padding.swift

@@ -9,6 +9,6 @@
 import Foundation
 
 public protocol Padding {
-    func add(data: [UInt8], blockSize:Int) -> [UInt8];
-    func remove(data: [UInt8], blockSize:Int?) -> [UInt8];
+    func add(data: [UInt8], blockSize:Int) -> [UInt8]
+    func remove(data: [UInt8], blockSize:Int?) -> [UInt8]
 }

+ 9 - 9
CryptoSwift/Poly1305.swift

@@ -83,12 +83,12 @@ final public class Poly1305 {
     Calculate Message Authentication Code (MAC) for message.
     Calculation context is discarder on instance deallocation.
     
-    :param: key     256-bit key
-    :param: message Message
+    - parameter key:     256-bit key
+    - parameter message: Message
     
-    :returns: Message Authentication Code
+    - returns: Message Authentication Code
     */
-    class internal func authenticate(# key: [UInt8], message: [UInt8]) -> [UInt8]? {
+    class internal func authenticate(key  key: [UInt8], message: [UInt8]) -> [UInt8]? {
         return Poly1305(key)?.authenticate(message: message)
     }
     
@@ -101,7 +101,7 @@ final public class Poly1305 {
         }
     }
     
-    private func authenticate(# message:[UInt8]) -> [UInt8]? {
+    private func authenticate(message  message:[UInt8]) -> [UInt8]? {
         if let ctx = self.ctx {
             update(ctx, message: message)
             return finish(ctx)
@@ -112,9 +112,9 @@ final public class Poly1305 {
     /**
     Add message to be processed
     
-    :param: context Context
-    :param: message message
-    :param: bytes   length of the message fragment to be processed
+    - parameter context: Context
+    - parameter message: message
+    - parameter bytes:   length of the message fragment to be processed
     */
     private func update(context:Context, message:[UInt8], bytes:Int? = nil) {
         var bytes = bytes ?? message.count
@@ -145,7 +145,7 @@ final public class Poly1305 {
         
         /* process full blocks */
         if (bytes >= blockSize) {
-            var want = bytes & ~(blockSize - 1)
+            let want = bytes & ~(blockSize - 1)
             blocks(context, m: message, startPos: mPos)
             mPos += want
             bytes -= want;

+ 11 - 12
CryptoSwift/SHA1.swift

@@ -8,29 +8,28 @@
 
 import Foundation
 
-final class SHA1 : CryptoSwift.HashBase, _Hash {
+final class SHA1 : HashProtocol {
     var size:Int = 20 // 160 / 8
+    let message: NSData
     
-    override init(_ message: NSData) {
-        super.init(message)
+    init(_ message: NSData) {
+        self.message = message
     }
     
     private let h:[UInt32] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
         
     func calculate() -> NSData {
-        var tmpMessage = self.prepare()
+        let tmpMessage = self.prepare(64)
         
         // hash values
         var hh = h
         
         // append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits.
-        tmpMessage.appendBytes((message.length * 8).bytes(64 / 8));
+        tmpMessage.appendBytes((self.message.length * 8).bytes(64 / 8));
         
         // Process the message in successive 512-bit chunks:
         let chunkSizeBytes = 512 / 8 // 64
-        var leftMessageBytes = tmpMessage.length
-        for var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes {
-            let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes)))
+        for chunk in NSDataSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
             // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian
             // Extend the sixteen 32-bit words into eighty 32-bit words:
             var M:[UInt32] = [UInt32](count: 80, repeatedValue: 0)
@@ -42,7 +41,7 @@ final class SHA1 : CryptoSwift.HashBase, _Hash {
                     M[x] = le.bigEndian
                     break
                 default:
-                    M[x] = rotateLeft(M[x-3] ^ M[x-8] ^ M[x-14] ^ M[x-16], 1)
+                    M[x] = rotateLeft(M[x-3] ^ M[x-8] ^ M[x-14] ^ M[x-16], n: 1) //FIXME: n:
                     break
                 }
             }
@@ -79,10 +78,10 @@ final class SHA1 : CryptoSwift.HashBase, _Hash {
                     break
                 }
                 
-                var temp = (rotateLeft(A,5) &+ f &+ E &+ M[j] &+ k) & 0xffffffff
+                let temp = (rotateLeft(A,n: 5) &+ f &+ E &+ M[j] &+ k) & 0xffffffff
                 E = D
                 D = C
-                C = rotateLeft(B, 30)
+                C = rotateLeft(B, n: 30)
                 B = A
                 A = temp
             }
@@ -95,7 +94,7 @@ final class SHA1 : CryptoSwift.HashBase, _Hash {
         }
         
         // Produce the final hash value (big-endian) as a 160 bit number:
-        var buf: NSMutableData = NSMutableData();
+        let buf: NSMutableData = NSMutableData();
         for item in hh {
             var i:UInt32 = item.bigEndian
             buf.appendBytes(&i, length: sizeofValue(i))

+ 33 - 33
CryptoSwift/SHA2.swift

@@ -9,10 +9,17 @@
 import Foundation
 
 
-final class SHA2 : HashBase, _Hash {
+final class SHA2 : HashProtocol {
     var size:Int { return variant.rawValue }
     let variant:SHA2.Variant
     
+    let message: NSData
+    
+    init(_ message:NSData, variant: SHA2.Variant) {
+        self.variant = variant
+        self.message = message
+    }
+    
     enum Variant: RawRepresentable {
         case sha224, sha256, sha384, sha512
         
@@ -111,29 +118,22 @@ final class SHA2 : HashBase, _Hash {
         }
     }
     
-    init(_ message:NSData, variant: SHA2.Variant) {
-        self.variant = variant
-        super.init(message)
-    }
-    
     //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() -> NSData {
-        var tmpMessage = self.prepare()
+        let tmpMessage = self.prepare(64)
         
         // hash values
         var hh = [UInt32]()
-        variant.h.map({(h) -> () in
+        variant.h.forEach {(h) -> () in
             hh.append(UInt32(h))
-        })
-        
+        }
+		
         // append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits.
         tmpMessage.appendBytes((message.length * 8).bytes(64 / 8));
         
         // Process the message in successive 512-bit chunks:
         let chunkSizeBytes = 512 / 8 // 64
-        var leftMessageBytes = tmpMessage.length
-        for var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes {
-            let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes)))
+        for chunk in NSDataSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
             // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian
             // Extend the sixteen 32-bit words into sixty-four 32-bit words:
             var M:[UInt32] = [UInt32](count: variant.k.count, repeatedValue: 0)
@@ -145,8 +145,8 @@ final class SHA2 : HashBase, _Hash {
                     M[x] = le.bigEndian
                     break
                 default:
-                    let s0 = rotateRight(M[x-15], 7) ^ rotateRight(M[x-15], 18) ^ (M[x-15] >> 3)
-                    let s1 = rotateRight(M[x-2], 17) ^ rotateRight(M[x-2], 19) ^ (M[x-2] >> 10)
+                    let s0 = rotateRight(M[x-15], n: 7) ^ rotateRight(M[x-15], n: 18) ^ (M[x-15] >> 3) //FIXME: n
+                    let s1 = rotateRight(M[x-2], n: 17) ^ rotateRight(M[x-2], n: 19) ^ (M[x-2] >> 10)
                     M[x] = M[x-16] &+ s0 &+ M[x-7] &+ s1
                     break
                 }
@@ -163,10 +163,10 @@ final class SHA2 : HashBase, _Hash {
             
             // Main loop
             for j in 0..<variant.k.count {
-                let s0 = rotateRight(A,2) ^ rotateRight(A,13) ^ rotateRight(A,22)
+                let s0 = rotateRight(A,n: 2) ^ rotateRight(A,n: 13) ^ rotateRight(A,n: 22)
                 let maj = (A & B) ^ (A & C) ^ (B & C)
                 let t2 = s0 &+ maj
-                let s1 = rotateRight(E,6) ^ rotateRight(E,11) ^ rotateRight(E,25)
+                let s1 = rotateRight(E,n: 6) ^ rotateRight(E,n: 11) ^ rotateRight(E,n: 25)
                 let ch = (E & F) ^ ((~E) & G)
                 let t1 = H &+ s1 &+ ch &+ UInt32(variant.k[j]) &+ M[j]
                 
@@ -191,25 +191,25 @@ final class SHA2 : HashBase, _Hash {
         }
         
         // Produce the final hash value (big-endian) as a 160 bit number:
-        var buf: NSMutableData = NSMutableData();
-        
-        variant.resultingArray(hh).map({ (item) -> () in
+        let buf: NSMutableData = NSMutableData();
+        variant.resultingArray(hh).forEach{ (item) -> () in
             var i:UInt32 = UInt32(item.bigEndian)
             buf.appendBytes(&i, length: sizeofValue(i))
-        })
-        
+        }
+		
         return buf.copy() as! NSData;
     }
     
     func calculate64() -> NSData {
-        var tmpMessage = self.prepare(128)
+        let tmpMessage = self.prepare(128)
         
         // hash values
         var hh = [UInt64]()
-        variant.h.map({(h) -> () in
+        variant.h.forEach {(h) -> () in
             hh.append(h)
-        })
-        
+        }
+		
+  
         // append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits.
         tmpMessage.appendBytes((message.length * 8).bytes(64 / 8));
         
@@ -217,7 +217,7 @@ final class SHA2 : HashBase, _Hash {
         let chunkSizeBytes = 1024 / 8 // 128
         var leftMessageBytes = tmpMessage.length
         for var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes {
-            var chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes)))
+            let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes)))
             // break chunk into sixteen 64-bit words M[j], 0 ≤ j ≤ 15, big-endian
             // Extend the sixteen 64-bit words into eighty 64-bit words:
             var M = [UInt64](count: variant.k.count, repeatedValue: 0)
@@ -229,8 +229,8 @@ final class SHA2 : HashBase, _Hash {
                     M[x] = le.bigEndian
                     break
                 default:
-                    let s0 = rotateRight(M[x-15], 1) ^ rotateRight(M[x-15], 8) ^ (M[x-15] >> 7)
-                    let s1 = rotateRight(M[x-2], 19) ^ rotateRight(M[x-2], 61) ^ (M[x-2] >> 6)
+                    let s0 = rotateRight(M[x-15], n: 1) ^ rotateRight(M[x-15], n: 8) ^ (M[x-15] >> 7)
+                    let s1 = rotateRight(M[x-2], n: 19) ^ rotateRight(M[x-2], n: 61) ^ (M[x-2] >> 6)
                     M[x] = M[x-16] &+ s0 &+ M[x-7] &+ s1
                     break
                 }
@@ -247,10 +247,10 @@ final class SHA2 : HashBase, _Hash {
             
             // Main loop
             for j in 0..<variant.k.count {
-                let s0 = rotateRight(A,28) ^ rotateRight(A,34) ^ rotateRight(A,39)
+                let s0 = rotateRight(A,n: 28) ^ rotateRight(A,n: 34) ^ rotateRight(A,n: 39) //FIXME: n:
                 let maj = (A & B) ^ (A & C) ^ (B & C)
                 let t2 = s0 &+ maj
-                let s1 = rotateRight(E,14) ^ rotateRight(E,18) ^ rotateRight(E,41)
+                let s1 = rotateRight(E,n: 14) ^ rotateRight(E,n: 18) ^ rotateRight(E,n: 41)
                 let ch = (E & F) ^ ((~E) & G)
                 let t1 = H &+ s1 &+ ch &+ variant.k[j] &+ UInt64(M[j])
                 
@@ -275,9 +275,9 @@ final class SHA2 : HashBase, _Hash {
         }
         
         // Produce the final hash value (big-endian)
-        var buf: NSMutableData = NSMutableData();
+        let buf: NSMutableData = NSMutableData();
         
-        variant.resultingArray(hh).map({ (item) -> () in
+        variant.resultingArray(hh).forEach({ (item) -> () in
             var i = item.bigEndian
             buf.appendBytes(&i, length: sizeofValue(i))
         })

+ 4 - 4
CryptoSwift/StringExtension.swift

@@ -40,12 +40,12 @@ extension String {
         return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.crc32()?.toHexString()
     }
 
-    public func encrypt(cipher: Cipher) -> String? {
-        return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.encrypt(cipher)?.toHexString()
+    public func encrypt(cipher: Cipher) throws -> String? {
+        return try self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.encrypt(cipher)?.toHexString()
     }
 
-    public func decrypt(cipher: Cipher) -> String? {
-        return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.decrypt(cipher)?.toHexString()
+    public func decrypt(cipher: Cipher) throws -> String? {
+        return try self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.decrypt(cipher)?.toHexString()
     }
     
     public func authenticate(authenticator: Authenticator) -> String? {

+ 4 - 4
CryptoSwift/UInt16Extension.swift

@@ -16,18 +16,18 @@ extension UInt16 {
             return self;
         }
 
-        var bitsCount = UInt16(sizeofValue(self) * 8)
+        let bitsCount = UInt16(sizeofValue(self) * 8)
 
         if (count >= bitsCount) {
             return 0
         }
 
-        var maxBitsForValue = UInt16(floor(log2(Double(self) + 1)))
-        var shiftCount = Swift.min(count, maxBitsForValue - 1)
+        let maxBitsForValue = UInt16(floor(log2(Double(self) + 1)))
+        let shiftCount = Swift.min(count, maxBitsForValue - 1)
         var shiftedValue:UInt16 = 0;
         
         for bitIdx in 0..<bitsCount {
-            var byte = 1 << bitIdx
+            let byte = 1 << bitIdx
             if ((self & byte) == byte) {
                 shiftedValue = shiftedValue | (byte >> shiftCount)
             }

+ 8 - 8
CryptoSwift/UInt32Extension.swift

@@ -10,7 +10,7 @@ import Foundation
 
 /** array of bytes */
 extension UInt32 {
-    public func bytes(_ totalBytes: Int = sizeof(UInt32)) -> [UInt8] {
+    public func bytes(totalBytes: Int = sizeof(UInt32)) -> [UInt8] {
         return arrayOfBytes(self, length: totalBytes)
     }
 
@@ -33,13 +33,13 @@ extension UInt32 {
             return self;
         }
         
-        var bitsCount = UInt32(sizeof(UInt32) * 8)
-        var shiftCount = Swift.min(count, bitsCount - 1)
+        let bitsCount = UInt32(sizeof(UInt32) * 8)
+        let shiftCount = Swift.min(count, bitsCount - 1)
         var shiftedValue:UInt32 = 0;
         
         for bitIdx in 0..<bitsCount {
             // if bit is set then copy to result and shift left 1
-            var bit = 1 << bitIdx
+            let bit = 1 << bitIdx
             if ((self & bit) == bit) {
                 shiftedValue = shiftedValue | (bit << shiftCount)
             }
@@ -60,19 +60,19 @@ extension UInt32 {
             return self;
         }
         
-        var bitsCount = UInt32(sizeofValue(self) * 8)
+        let bitsCount = UInt32(sizeofValue(self) * 8)
 
         if (count >= bitsCount) {
             return 0
         }
 
-        var maxBitsForValue = UInt32(floor(log2(Double(self)) + 1))
-        var shiftCount = Swift.min(count, maxBitsForValue - 1)
+        let maxBitsForValue = UInt32(floor(log2(Double(self)) + 1))
+        let shiftCount = Swift.min(count, maxBitsForValue - 1)
         var shiftedValue:UInt32 = 0;
         
         for bitIdx in 0..<bitsCount {
             // if bit is set then copy to result and shift left 1
-            var bit = 1 << bitIdx
+            let bit = 1 << bitIdx
             if ((self & bit) == bit) {
                 shiftedValue = shiftedValue | (bit >> shiftCount)
             }

+ 1 - 1
CryptoSwift/UInt64Extension.swift

@@ -10,7 +10,7 @@ import Foundation
 
 /** array of bytes */
 extension UInt64 {
-    public func bytes(_ totalBytes: Int = sizeof(UInt64)) -> [UInt8] {
+    public func bytes(totalBytes: Int = sizeof(UInt64)) -> [UInt8] {
         return arrayOfBytes(self, length: totalBytes)
     }
 

+ 5 - 5
CryptoSwift/UInt8Extension.swift

@@ -56,7 +56,7 @@ extension UInt8 {
     func bits() -> String {
         var s = String()
         let arr:[Bit] = self.bits()
-        for (idx,b) in enumerate(arr) {
+        for (idx,b) in arr.enumerate() {
             s += (b == Bit.One ? "1" : "0")
             if ((idx + 1) % 8 == 0) { s += " " }
         }
@@ -72,18 +72,18 @@ extension UInt8 {
             return self;
         }
 
-        var bitsCount = UInt8(sizeof(UInt8) * 8)
+        let bitsCount = UInt8(sizeof(UInt8) * 8)
 
         if (count >= bitsCount) {
             return 0
         }
 
-        var maxBitsForValue = UInt8(floor(log2(Double(self) + 1)))
-        var shiftCount = Swift.min(count, maxBitsForValue - 1)
+        let maxBitsForValue = UInt8(floor(log2(Double(self) + 1)))
+        let shiftCount = Swift.min(count, maxBitsForValue - 1)
         var shiftedValue:UInt8 = 0;
         
         for bitIdx in 0..<bitsCount {
-            var byte = 1 << bitIdx
+            let byte = 1 << bitIdx
             if ((self & byte) == byte) {
                 shiftedValue = shiftedValue | (byte >> shiftCount)
             }

+ 2 - 8
CryptoSwift/Utils.swift

@@ -37,13 +37,7 @@ func rotateRight(x:UInt64, n:UInt64) -> UInt64 {
 }
 
 func reverseBytes(value: UInt32) -> UInt32 {
-    // rdar://18060945 - not working since Xcode6-Beta6, need to split in two variables
-    // return = ((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8) | ((value & 0x00FF0000) >> 8)  | ((value & 0xFF000000) >> 24);
-    
-    // workaround
-    var tmp1 = ((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8)
-    var tmp2 = ((value & 0x00FF0000) >> 8)  | ((value & 0xFF000000) >> 24)
-    return tmp1 | tmp2
+    return ((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8) | ((value & 0x00FF0000) >> 8)  | ((value & 0xFF000000) >> 24);
 }
 
 func xor(a: [UInt8], b:[UInt8]) -> [UInt8] {
@@ -62,5 +56,5 @@ func perf(text: String, closure: () -> ()) {
     let measurementStop = NSDate();
     let executionTime = measurementStop.timeIntervalSinceDate(measurementStart)
     
-    println("\(text) \(executionTime)");
+    print("\(text) \(executionTime)");
 }

+ 61 - 27
CryptoSwiftTests/AESTests.swift

@@ -8,7 +8,7 @@
 
 import Foundation
 import XCTest
-import CryptoSwift
+@testable import CryptoSwift
 
 final class AESTests: XCTestCase {
     // 128 bit key
@@ -22,15 +22,32 @@ final class AESTests: XCTestCase {
         let expected:[UInt8] = [0xae,0x8c,0x59,0x95,0xb2,0x6f,0x8e,0x3d,0xb0,0x6f,0x0a,0xa5,0xfe,0xc4,0xf0,0xc2];
         
         if let aes = AES(key: key, iv: iv, blockMode: .CBC) {
-            let encrypted = aes.encrypt(input, padding: nil)
-            XCTAssertEqual(encrypted!, expected, "encryption failed")
-            let decrypted = aes.decrypt(encrypted!, padding: nil)
-            XCTAssertEqual(decrypted!, input, "decryption failed")
+            let encrypted = try! aes.encrypt(input, padding: nil)
+            XCTAssertEqual(encrypted, expected, "encryption failed")
+            let decrypted = try! aes.decrypt(encrypted, padding: nil)
+            XCTAssertEqual(decrypted, input, "decryption failed")
         } else {
             XCTAssert(false, "failed")
         }
     }
 
+    func testAES_encrypt3() {
+        let key = "679fb1ddf7d81bee"
+        let iv = "kdf67398DF7383fd"
+        let input:[UInt8] = [0x62, 0x72, 0x61, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
+        
+        let expected:[UInt8] = [0xae,0x8c,0x59,0x95,0xb2,0x6f,0x8e,0x3d,0xb0,0x6f,0x0a,0xa5,0xfe,0xc4,0xf0,0xc2];
+        
+        if let aes = AES(key: key, iv: iv, blockMode: .CBC) {
+            let encrypted = try! aes.encrypt(input, padding: nil)
+            XCTAssertEqual(encrypted, expected, "encryption failed")
+            let decrypted = try! aes.decrypt(encrypted, padding: nil)
+            XCTAssertEqual(decrypted, input, "decryption failed")
+        } else {
+            XCTAssert(false, "failed")
+        }
+    }
+    
     func testAES_encrypt() {
         let input:[UInt8] = [0x00, 0x11, 0x22, 0x33,
             0x44, 0x55, 0x66, 0x77,
@@ -43,10 +60,10 @@ final class AESTests: XCTestCase {
             0x70, 0xb4, 0xc5, 0x5a];
         
         if let aes = AES(key: aesKey, blockMode: .ECB) {
-            let encrypted = aes.encrypt(input, padding: nil)
-            XCTAssertEqual(encrypted!, expected, "encryption failed")
-            let decrypted = aes.decrypt(encrypted!, padding: nil)
-            XCTAssertEqual(decrypted!, input, "decryption failed")
+            let encrypted = try! aes.encrypt(input, padding: nil)
+            XCTAssertEqual(encrypted, expected, "encryption failed")
+            let decrypted = try! aes.decrypt(encrypted, padding: nil)
+            XCTAssertEqual(decrypted, input, "decryption failed")
         } else {
             XCTAssert(false, "failed")
         }
@@ -60,10 +77,10 @@ final class AESTests: XCTestCase {
         
         if let aes = AES(key: key, iv:iv, blockMode: .CBC) {
             XCTAssertTrue(aes.blockMode == .CBC, "Invalid block mode")
-            let encrypted = aes.encrypt(plaintext, padding: nil)
-            XCTAssertEqual(encrypted!, expected, "encryption failed")
-            let decrypted = aes.decrypt(encrypted!, padding: nil)
-            XCTAssertEqual(decrypted!, plaintext, "decryption failed")
+            let encrypted = try! aes.encrypt(plaintext, padding: nil)
+            XCTAssertEqual(encrypted, expected, "encryption failed")
+            let decrypted = try! aes.decrypt(encrypted, padding: nil)
+            XCTAssertEqual(decrypted, plaintext, "decryption failed")
         } else {
             XCTAssert(false, "failed")
         }
@@ -77,10 +94,27 @@ final class AESTests: XCTestCase {
         
         if let aes = AES(key: key, iv:iv, blockMode: .CFB) {
             XCTAssertTrue(aes.blockMode == .CFB, "Invalid block mode")
-            let encrypted = aes.encrypt(plaintext, padding: nil)
-            XCTAssertEqual(encrypted!, expected, "encryption failed")
-            let decrypted = aes.decrypt(encrypted!, padding: nil)
-            XCTAssertEqual(decrypted!, plaintext, "decryption failed")
+            let encrypted = try! aes.encrypt(plaintext, padding: nil)
+            XCTAssertEqual(encrypted, expected, "encryption failed")
+            let decrypted = try! aes.decrypt(encrypted, padding: nil)
+            XCTAssertEqual(decrypted, plaintext, "decryption failed")
+        } else {
+            XCTAssert(false, "failed")
+        }
+    }
+    
+    func testAES_encrypt_ctr() {
+        let key:[UInt8] = [0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c];
+        let iv:[UInt8] = [0xf0,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa,0xfb,0xfc,0xfd,0xfe,0xff]
+        let plaintext:[UInt8] = [0x6b,0xc1,0xbe,0xe2,0x2e,0x40,0x9f,0x96,0xe9,0x3d,0x7e,0x11,0x73,0x93,0x17,0x2a]
+        let expected:[UInt8] = [103, 238, 5, 84, 116, 153, 248, 188, 240, 195, 131, 36, 232, 96, 92, 40]
+        
+        if let aes = AES(key: key, iv:iv, blockMode: .CTR) {
+            XCTAssertTrue(aes.blockMode == .CTR, "Invalid block mode")
+            let encrypted = try! aes.encrypt(plaintext, padding: nil)
+            XCTAssertEqual(encrypted, expected, "encryption failed")
+            let decrypted = try! aes.decrypt(encrypted, padding: nil)
+            XCTAssertEqual(decrypted, plaintext, "decryption failed")
         } else {
             XCTAssert(false, "failed")
         }
@@ -99,9 +133,9 @@ final class AESTests: XCTestCase {
         
         var substituted = input
         AES(key: aesKey, blockMode: .CBC)!.subBytes(&substituted)
-        XCTAssertTrue(compareMatrix(expected, substituted), "subBytes failed")
+        XCTAssertTrue(compareMatrix(expected, b: substituted), "subBytes failed")
         let inverted = AES(key: aesKey, blockMode: .CBC)!.invSubBytes(substituted)
-        XCTAssertTrue(compareMatrix(input, inverted), "invSubBytes failed")
+        XCTAssertTrue(compareMatrix(input, b: inverted), "invSubBytes failed")
     }
     
     func testAES_shiftRows() {
@@ -116,9 +150,9 @@ final class AESTests: XCTestCase {
             [0x8c, 0x4, 0x51, 0xe7]]
         
         let shifted = AES(key: aesKey, blockMode: .CBC)!.shiftRows(input)
-        XCTAssertTrue(compareMatrix(expected, shifted), "shiftRows failed")
+        XCTAssertTrue(compareMatrix(expected, b: shifted), "shiftRows failed")
         let inverted = AES(key: aesKey, blockMode: .CBC)!.invShiftRows(shifted)
-        XCTAssertTrue(compareMatrix(input, inverted), "invShiftRows failed")
+        XCTAssertTrue(compareMatrix(input, b: inverted), "invShiftRows failed")
     }
     
     func testAES_multiply() {
@@ -148,7 +182,7 @@ final class AESTests: XCTestCase {
         
         if let aes = AES(key: aesKey, blockMode: .CBC) {
             let result = aes.addRoundKey(input, aes.expandedKey, 0)
-            XCTAssertTrue(compareMatrix(expected, result), "addRoundKey failed")
+            XCTAssertTrue(compareMatrix(expected, b: result), "addRoundKey failed")
         } else {
             XCTAssert(false, "")
         }
@@ -167,9 +201,9 @@ final class AESTests: XCTestCase {
         
         if let aes = AES(key: aesKey, blockMode: .CBC) {
             let mixed = aes.mixColumns(input)
-            XCTAssertTrue(compareMatrix(expected, mixed), "mixColumns failed")
+            XCTAssertTrue(compareMatrix(expected, b: mixed), "mixColumns failed")
             let inverted = aes.invMixColumns(mixed)
-            XCTAssertTrue(compareMatrix(input, inverted), "invMixColumns failed")
+            XCTAssertTrue(compareMatrix(input, b: inverted), "invMixColumns failed")
         } else {
             XCTAssert(false, "")
         }
@@ -180,7 +214,7 @@ final class AESTests: XCTestCase {
         let iv:[UInt8] = [0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F]
         let message = [UInt8](count: 1024 * 1024, repeatedValue: 7)
         measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true, forBlock: { () -> Void in
-            let encrypted = AES(key: key, iv: iv, blockMode: .CBC)?.encrypt(message, padding: PKCS7())
+            try! AES(key: key, iv: iv, blockMode: .CBC)?.encrypt(message, padding: PKCS7())
         })
     }
     
@@ -200,14 +234,14 @@ final class AESTests: XCTestCase {
             let dataBytes     = UnsafePointer<Void>(data.bytes)
             
             let cryptData    = NSMutableData(length: Int(dataLength) + kCCBlockSizeAES128)
-            var cryptPointer = UnsafeMutablePointer<Void>(cryptData!.mutableBytes)
+            let cryptPointer = UnsafeMutablePointer<Void>(cryptData!.mutableBytes)
             let cryptLength  = cryptData!.length
             
             var numBytesEncrypted:Int = 0
             
             self.startMeasuring()
             
-            var cryptStatus = CCCrypt(
+            CCCrypt(
                 UInt32(kCCEncrypt),
                 UInt32(kCCAlgorithmAES128),
                 UInt32(kCCOptionPKCS7Padding),

+ 14 - 12
CryptoSwiftTests/ChaCha20Tests.swift

@@ -8,7 +8,7 @@
 
 import Foundation
 import XCTest
-import CryptoSwift
+@testable import CryptoSwift
 
 final class ChaCha20Tests: XCTestCase {
 
@@ -48,25 +48,27 @@ final class ChaCha20Tests: XCTestCase {
         for (var idx = 0; idx < keys.count; idx++) {
             
             let expectedHex = expectedHexes[idx]
-            let message = [UInt8](count: (count(expectedHex) / 2), repeatedValue: 0)
+            let message = [UInt8](count: (expectedHex.characters.count / 2), repeatedValue: 0)
             
             let setup = (key: keys[idx], iv: ivs[idx])
-            var encrypted = Cipher.ChaCha20(setup).encrypt(message)
-            XCTAssert(encrypted != nil, "missing")
-            if let encrypted = encrypted {
-                var decrypted = Cipher.ChaCha20(setup).decrypt(encrypted)
-                XCTAssert(decrypted != nil, "missing")
-                if let decrypted = decrypted {
-                    XCTAssertEqual(message, decrypted, "ChaCha20 decryption failed");
-                }
+            do {
+                let encrypted = try Cipher.ChaCha20(setup).encrypt(message)
+                let decrypted = try Cipher.ChaCha20(setup).decrypt(encrypted)
+                XCTAssertEqual(message, decrypted, "ChaCha20 decryption failed");
                 
                 // check extension
                 let messageData = NSData(bytes: message, length: message.count);
-                let encrypted2 = messageData.encrypt(Cipher.ChaCha20(setup))
+                let encrypted2 = try! messageData.encrypt(Cipher.ChaCha20(setup))
                 XCTAssertNotNil(encrypted2, "")
                 if let encrypted2 = encrypted2 {
                     XCTAssertEqual(NSData.withBytes(encrypted), encrypted2, "ChaCha20 extension failed")
                 }
+            } catch Cipher.Error.EncryptError {
+                XCTAssert(false, "Encryption failed")
+            } catch Cipher.Error.DecryptError {
+                XCTAssert(false, "Decryption failed")
+            } catch {
+                XCTAssert(false, "Failed")
             }
         }
     }
@@ -76,7 +78,7 @@ final class ChaCha20Tests: XCTestCase {
         let iv:[UInt8] = [0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F]
         let message = [UInt8](count: (1024 * 1024) * 1, repeatedValue: 7)
         measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true, forBlock: { () -> Void in
-            let encrypted = ChaCha20(key: key, iv: iv)?.encrypt(message)
+            let encrypted = try! ChaCha20(key: key, iv: iv)?.encrypt(message)
             self.stopMeasuring()
             XCTAssert(encrypted != nil, "not encrypted")
         })

+ 6 - 6
CryptoSwiftTests/ExtensionsTest.swift

@@ -8,7 +8,7 @@
 
 import Foundation
 import XCTest
-import CryptoSwift
+@testable import CryptoSwift
 
 final class ExtensionsTest: XCTestCase {
 
@@ -24,7 +24,7 @@ final class ExtensionsTest: XCTestCase {
         measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: false, forBlock: { () -> Void in
             let message = [UInt8](count: 1024 * 1024, repeatedValue: 7)
             self.startMeasuring()
-            let blocks = message.chunks(AES.blockSize)
+            message.chunks(AES.blockSize)
             self.stopMeasuring()
         })
     }
@@ -39,7 +39,7 @@ final class ExtensionsTest: XCTestCase {
         
         let i2:Int = 1024
         let i2Array = i2.bytes(160 / 8) // 160 bit
-        let i2recovered = Int.withBytes(i1Array)
+        let i2recovered = Int.withBytes(i2Array)
         
         XCTAssertEqual(i2, i2recovered, "Bytes conversion failed")
     }
@@ -59,20 +59,20 @@ final class ExtensionsTest: XCTestCase {
     
     func testShiftLeft() {
         // Unsigned
-        var i:UInt32 = 1
+        let i:UInt32 = 1
         XCTAssert(i &<< 1 == 2, "shift left failed")
         XCTAssert(i &<< 8 == 256, "shift left failed")
         XCTAssert(i &<< 31 == i << 31, "shift left failed")
         XCTAssert(i &<< 32 == 0, "shift left failed")
 
         // Signed
-        var ii:Int = 21
+        let ii:Int = 21
         XCTAssert(ii &<< 1 == ii << 1, "shift left failed")
         XCTAssert(ii &<< 8 == ii << 8, "shift left failed")
         XCTAssert(ii &<< ((sizeofValue(ii) * 8) - 1) == ii << ((sizeofValue(ii) * 8) - 1), "shift left failed")
         XCTAssert(ii &<< ((sizeofValue(ii) * 8)) == 0, "shift left failed")
         
-        var iii:UInt32 = 21
+        let iii:UInt32 = 21
         XCTAssert(iii &<< 1 == iii << 1, "shift left failed")
         XCTAssert(iii &<< 8 == iii << 8, "shift left failed")
         XCTAssert((iii &<< 32) == 0, "shift left failed")

+ 1 - 1
CryptoSwiftTests/HMACTests.swift

@@ -8,7 +8,7 @@
 
 import Foundation
 import XCTest
-import CryptoSwift
+@testable import CryptoSwift
 
 final class HMACTests: XCTestCase {
     

+ 11 - 11
CryptoSwiftTests/HashTests.swift

@@ -7,7 +7,7 @@
 //
 
 import XCTest
-import CryptoSwift
+@testable import CryptoSwift
 
 final class CryptoSwiftTests: XCTestCase {
     
@@ -27,8 +27,8 @@ final class CryptoSwiftTests: XCTestCase {
             XCTAssert(false, "Missing result")
         }
         
-        var string:NSString = ""
-        var data:NSData = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
+        let string:NSString = ""
+        let data:NSData = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
         if let hashData = Hash.md5(data).calculate() {
             XCTAssertEqual(hashData.toHexString(), "d41d8cd98f00b204e9800998ecf8427e", "MD5 calculation failed")
         } else {
@@ -91,9 +91,9 @@ final class CryptoSwiftTests: XCTestCase {
             let buf = UnsafeMutablePointer<UInt8>(calloc(2048, sizeof(UInt8)))
             let data = NSData(bytes: buf, length: 2048)
             self.startMeasuring()
-            var outbuf = UnsafeMutablePointer<UInt8>.alloc(Int(CC_MD5_DIGEST_LENGTH))
+            let outbuf = UnsafeMutablePointer<UInt8>.alloc(Int(CC_MD5_DIGEST_LENGTH))
             CC_MD5(data.bytes, CC_LONG(data.length), outbuf)
-            let output = NSData(bytes: outbuf, length: Int(CC_MD5_DIGEST_LENGTH));
+            //let output = NSData(bytes: outbuf, length: Int(CC_MD5_DIGEST_LENGTH));
             outbuf.dealloc(Int(CC_MD5_DIGEST_LENGTH))
             outbuf.destroy()
             self.stopMeasuring()
@@ -103,7 +103,7 @@ final class CryptoSwiftTests: XCTestCase {
     }
     
     func testSHA1() {
-        var data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as [UInt8], length: 3)
+        let data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as [UInt8], length: 3)
         if let hash = data.sha1() {
             XCTAssertEqual(hash.toHexString(), "40bd001563085fc35165329ea1ff5c5ecbdbbeef", "SHA1 calculation failed");
         }
@@ -125,14 +125,14 @@ final class CryptoSwiftTests: XCTestCase {
     }
     
     func testSHA224() {
-        var data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as [UInt8], length: 3)
+        let data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as [UInt8], length: 3)
         if let hash = data.sha224() {
             XCTAssertEqual(hash.toHexString(), "78d8045d684abd2eece923758f3cd781489df3a48e1278982466017f", "SHA224 calculation failed");
         }
     }
 
     func testSHA256() {
-        var data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as [UInt8], length: 3)
+        let data:NSData = NSData(bytes: [0x31, 0x32, 0x33] as [UInt8], length: 3)
         if let hash = data.sha256() {
             XCTAssertEqual(hash.toHexString(), "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3", "SHA256 calculation failed");
         }
@@ -150,7 +150,7 @@ final class CryptoSwiftTests: XCTestCase {
     }
 
     func testSHA384() {
-        var data:NSData = NSData(bytes: [49, 50, 51] as [UInt8], length: 3)
+        let data:NSData = NSData(bytes: [49, 50, 51] as [UInt8], length: 3)
         if let hash = data.sha384() {
             XCTAssertEqual(hash.toHexString(), "9a0a82f0c0cf31470d7affede3406cc9aa8410671520b727044eda15b4c25532a9b5cd8aaf9cec4919d76255b6bfb00f", "SHA384 calculation failed");
         }
@@ -167,7 +167,7 @@ final class CryptoSwiftTests: XCTestCase {
     }
 
     func testSHA512() {
-        var data:NSData = NSData(bytes: [49, 50, 51] as [UInt8], length: 3)
+        let data:NSData = NSData(bytes: [49, 50, 51] as [UInt8], length: 3)
         if let hash = data.sha512() {
             XCTAssertEqual(hash.toHexString(), "3c9909afec25354d551dae21590bb26e38d53f2173b8d3dc3eee4c047e7ab1c1eb8b85103e3be7ba613b31bb5c9c36214dc9f14a42fd7a2fdb84856bca5c44c2", "SHA512 calculation failed");
         }
@@ -184,7 +184,7 @@ final class CryptoSwiftTests: XCTestCase {
     }
     
     func testCRC32() {
-        var data:NSData = NSData(bytes: [49, 50, 51] as [UInt8], length: 3)
+        let data:NSData = NSData(bytes: [49, 50, 51] as [UInt8], length: 3)
         if let crc = data.crc32() {
             XCTAssertEqual(crc.toHexString(), "884863d2", "CRC32 calculation failed");
         }

+ 3 - 3
CryptoSwiftTests/Helpers.swift

@@ -9,10 +9,10 @@
 import Foundation
 
 func compareMatrix(a:[[UInt8]], b:[[UInt8]]) -> Bool {
-    for (i,arr) in enumerate(a) {
-        for (j,val) in enumerate(arr) {
+    for (i,arr) in a.enumerate() {
+        for (j,val) in arr.enumerate() {
             if (val != b[i][j]) {
-                println("Not equal: \(val) vs \(b[i][j])")
+                print("Not equal: \(val) vs \(b[i][j])") //FIXME: remove verbose
                 return false
             }
         }

+ 4 - 4
CryptoSwiftTests/PaddingTests.swift

@@ -8,7 +8,7 @@
 
 import Foundation
 import XCTest
-import CryptoSwift
+@testable import CryptoSwift
 
 final class PaddingTests: XCTestCase {
     func testPKCS7_0() {
@@ -16,7 +16,7 @@ final class PaddingTests: XCTestCase {
         let expected:[UInt8] = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16]
         let padded = PKCS7().add(input, blockSize: 16)
         XCTAssertEqual(padded, expected, "PKCS7 failed")
-        let clean = PKCS7().remove(padded)
+        let clean = PKCS7().remove(padded, blockSize: nil)
         XCTAssertEqual(clean, input, "PKCS7 failed")
     }
     
@@ -25,7 +25,7 @@ final class PaddingTests: XCTestCase {
         let expected:[UInt8] = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,1]
         let padded = PKCS7().add(input, blockSize: 16)
         XCTAssertEqual(padded, expected, "PKCS7 failed")
-        let clean = PKCS7().remove(padded)
+        let clean = PKCS7().remove(padded, blockSize: nil)
         XCTAssertEqual(clean, input, "PKCS7 failed")
     }
     
@@ -34,7 +34,7 @@ final class PaddingTests: XCTestCase {
         let expected:[UInt8] = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,2,2]
         let padded = PKCS7().add(input, blockSize: 16)
         XCTAssertEqual(padded, expected, "PKCS7 failed")
-        let clean = PKCS7().remove(padded)
+        let clean = PKCS7().remove(padded, blockSize: nil)
         XCTAssertEqual(clean, input, "PKCS7 failed")
     }
 }

+ 1 - 1
CryptoSwiftTests/Poly1305Tests.swift

@@ -8,7 +8,7 @@
 
 import Foundation
 import XCTest
-import CryptoSwift
+@testable import CryptoSwift
 
 final class Poly1305Tests: XCTestCase {
     

+ 12 - 1
README.md

@@ -32,6 +32,7 @@ Good mood
 - Electronic codebook ([ECB](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_codebook_.28ECB.29))
 - Cipher-block chaining ([CBC](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher-block_chaining_.28CBC.29))
 - Cipher feedback ([CFB](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_feedback_.28CFB.29))
+- Counter ([CTR](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29))
 
 #####Data padding
 - [PKCS#7](http://tools.ietf.org/html/rfc5652#section-6.3)
@@ -70,6 +71,16 @@ or for newest version from specified branch of code:
 ```ruby
 pod 'CryptoSwift', :git => "https://github.com/krzyzanowskim/CryptoSwift", :branch => "master"
 ```
+
+####Carthage 
+You can use [Carthage](https://github.com/Carthage/Carthage). 
+Specify in Cartfile:
+
+```ruby
+github "krzyzanowskim/CryptoSwift"
+```
+
+Then follow [build instructions](https://github.com/Carthage/Carthage#getting-started)
  
 ##Usage
 
@@ -82,7 +93,7 @@ Generally you should use `CryptoSwift.Hash`, `CryptoSwift.Cipher` enums or conve
 Hash enum usage
 ```swift
 /* Hash enum usage */
-var data:NSData = NSData(bytes: [49, 50, 51] as [Byte], length: 3)
+var data:NSData = NSData(bytes: [49, 50, 51] as [UInt8], length: 3)
 if let data = CryptoSwift.Hash.md5(data).calculate() {
     println(data.toHexString())
 }