Browse Source

More refactor work, some generics separated etc

Marcin Krzyżanowski 11 years ago
parent
commit
9ba8e31a04

+ 4 - 0
CryptoSwift.xcodeproj/project.pbxproj

@@ -24,6 +24,7 @@
 		755FB1DA199E347D00475437 /* ExtensionsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 755FB1D9199E347D00475437 /* ExtensionsTest.swift */; };
 		7563B2E819B14D4300B152CD /* Cipher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7563B2E719B14D4300B152CD /* Cipher.swift */; };
 		757EF7F519AAA82400586276 /* CRC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757EF7F419AAA82400586276 /* CRC.swift */; };
+		758C764119B61AE500653BC6 /* Generics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 758C764019B61AE500653BC6 /* Generics.swift */; };
 		758F3F761992E57D0014BBDA /* Playground in Resources */ = {isa = PBXBuildFile; fileRef = 758F3F751992E57D0014BBDA /* Playground */; };
 		758F3F781992F6CE0014BBDA /* ByteExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 758F3F771992F6CE0014BBDA /* ByteExtension.swift */; };
 		7599C9C6199EA28700A3988B /* StringExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7599C9C5199EA28700A3988B /* StringExtension.swift */; };
@@ -121,6 +122,7 @@
 		755FB1D9199E347D00475437 /* ExtensionsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ExtensionsTest.swift; sourceTree = "<group>"; };
 		7563B2E719B14D4300B152CD /* Cipher.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cipher.swift; sourceTree = "<group>"; };
 		757EF7F419AAA82400586276 /* CRC.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CRC.swift; sourceTree = "<group>"; };
+		758C764019B61AE500653BC6 /* Generics.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Generics.swift; sourceTree = "<group>"; };
 		758F3F751992E57D0014BBDA /* Playground */ = {isa = PBXFileReference; lastKnownFileType = folder; name = Playground; path = CryptoSwift/Playground; sourceTree = "<group>"; };
 		758F3F771992F6CE0014BBDA /* ByteExtension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ByteExtension.swift; sourceTree = "<group>"; };
 		7599C9C5199EA28700A3988B /* StringExtension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StringExtension.swift; sourceTree = "<group>"; };
@@ -202,6 +204,7 @@
 				754C8FEC19979F94005AD904 /* ArrayExtension.swift */,
 				7599C9C5199EA28700A3988B /* StringExtension.swift */,
 				75164E4819AD30AC00737F30 /* Utils.swift */,
+				758C764019B61AE500653BC6 /* Generics.swift */,
 				754BE45819693E190098E6F3 /* Supporting Files */,
 			);
 			path = CryptoSwift;
@@ -367,6 +370,7 @@
 				757EF7F519AAA82400586276 /* CRC.swift in Sources */,
 				75D94E2619B60C4F007CB2A4 /* UInt32Extension.swift in Sources */,
 				754DD76E19A149AF00E52288 /* CryptoHashBase.swift in Sources */,
+				758C764119B61AE500653BC6 /* Generics.swift in Sources */,
 				758F3F781992F6CE0014BBDA /* ByteExtension.swift in Sources */,
 				75153D4219AA3C7900750381 /* SHA2.swift in Sources */,
 			);

+ 2 - 9
CryptoSwift/ByteExtension.swift

@@ -10,16 +10,9 @@ import Foundation
 
 /** Bits */
 extension Byte {
+
     init(bits: [Bit]) {
-        var bitPattern:Byte = 0
-        for (idx,b) in enumerate(bits) {
-            if (b == Bit.Zero) {
-                var bit:Byte = Byte(1) << Byte(idx)
-                bitPattern = bitPattern | bit
-            }
-        }
-        
-        self.init(bitPattern)
+        self.init(integerFromBitsArray(bits) as Byte)
     }
     
     /** array of bits */

+ 2 - 2
CryptoSwift/CRC.swift

@@ -45,14 +45,14 @@ class CRC {
     
     func crc32(message:NSData) -> NSData {
         var crc:UInt32 = 0xffffffff
-        for b in message.arrayOfBytes() {
+        for b in message.bytes() {
             var 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()
+        let bytes = NSMutableData(bytes: &crc, length: 4).bytes().reverse()
         var data = NSData(bytes: bytes, length: bytes.count)
         return data
     }

+ 2 - 2
CryptoSwift/ChaCha20.swift

@@ -33,7 +33,7 @@ class ChaCha20 {
             return nil
         }
         
-        if let output = encryptBytes(message.arrayOfBytes()) {
+        if let output = encryptBytes(message.bytes()) {
             return NSData(bytes: output, length: output.count)
         }
         
@@ -75,7 +75,7 @@ class ChaCha20 {
     }
     
     private func contextSetup(# iv:NSData, key:NSData) -> Context? {
-        return contextSetup(iv: iv.arrayOfBytes(), key: key.arrayOfBytes())
+        return contextSetup(iv: iv.bytes(), key: key.bytes())
     }
     
     private func contextSetup(# iv:[Byte], key:[Byte]) -> Context? {

+ 53 - 0
CryptoSwift/Generics.swift

@@ -0,0 +1,53 @@
+//
+//  Generics.swift
+//  CryptoSwift
+//
+//  Created by Marcin Krzyzanowski on 02/09/14.
+//  Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
+//
+
+import Foundation
+
+/** build bit pattern from array of bits */
+func integerFromBitsArray<T : UnsignedIntegerType>(bits: [Bit]) -> T {
+    var bitPattern:T = 0
+    for (idx,b) in enumerate(bits) {
+        if (b == Bit.One) {
+            var bit = (UInt(1) << UInt(idx)) as T
+            bitPattern = bitPattern | bit
+        }
+    }
+    return bitPattern
+}
+
+/** initialize integer from array of bytes */
+func integerWithBytes<T: IntegerType>(bytes: [Byte]) -> T {
+    var totalBytes = Swift.min(bytes.count, sizeof(T))
+    // get slice of Int
+    var start = Swift.max(bytes.count - sizeof(T),0)
+    var intarr = [Byte](bytes[start..<(start + totalBytes)])
+    
+    // pad size if necessary
+    while (intarr.count < sizeof(T)) {
+        intarr.insert(0 as Byte, atIndex: 0)
+    }
+    intarr = intarr.reverse()
+    
+    var i:T = 0
+    var data = NSData(bytes: intarr, length: intarr.count)
+    data.getBytes(&i, length: sizeofValue(i));
+    return i
+}
+
+/** array of bytes, little-endian representation */
+func arrayOfBytes<T>(value:T, totalBytes:Int) -> [Byte] {
+    var bytes = [Byte](count: totalBytes, repeatedValue: 0)
+    var data = NSData(bytes: [value] as [T], length: min(sizeof(T),totalBytes))
+    
+    // then convert back to bytes, byte by byte
+    for i in 0..<data.length {
+        data.getBytes(&bytes[totalBytes - 1 - i], range:NSRange(location:i, length:sizeof(Byte)))
+    }
+    
+    return bytes
+}

+ 15 - 25
CryptoSwift/IntExtension.swift

@@ -14,37 +14,23 @@
 //  - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
 //  - This notice may not be removed or altered from any source or binary distribution.
 
-/*
-Bit shifting with overflow protection using overflow operator "&".
-Approach is consistent with standard overflow operators &+, &-, &*, &/
-and introduce new overflow operators for shifting: &<<, &>>
-
-Note: Works with unsigned integers values only
-
-Usage
-
-var i = 1       // init
-var j = i &<< 2 //shift left
-j &<<= 2        //shift left and assign
-
-
-@see: https://medium.com/@krzyzanowskim/swiftly-shift-bits-and-protect-yourself-be33016ce071
-*/
-
 import Foundation
 
-/* array of bits */
-extension Int {
-    init(bits: [Bit]) {
-        var bitPattern:UInt = 0
+func buildBitPattern<T : IntegerType, UnsignedIntegerType, BitwiseOperationsType, IntegerLiteralConvertible>(bits: [Bit]) -> T {
+        var bitPattern:T = 0
         for (idx,b) in enumerate(bits) {
             if (b == Bit.Zero) {
-                var bit:UInt = UInt(1) << UInt(idx)
+                var bit = (1 << idx) as T
                 bitPattern = bitPattern | bit
             }
         }
-        
-        self.init(bitPattern: bitPattern)
+    return bitPattern
+}
+
+/* array of bits */
+extension Int {
+    init(bits: [Bit]) {
+        self.init(bitPattern: integerFromBitsArray(bits) as UInt)
     }
 }
 
@@ -52,7 +38,11 @@ extension Int {
 extension Int {
     /** Array of bytes with optional padding (little-endian) */
     public func bytes(_ totalBytes: Int = sizeof(Int)) -> [Byte] {
-        return bytesArray(self, totalBytes)
+        return arrayOfBytes(self, totalBytes)
+    }
+
+    public static func withBytes(bytes: Slice<Byte>) -> Int {
+        return Int.withBytes(Array(bytes))
     }
 
     /** Int with array bytes (little-endian) */

+ 2 - 2
CryptoSwift/NSDataExtension.swift

@@ -26,7 +26,7 @@ extension NSData {
     public func checksum() -> UInt16 {
         var s:UInt32 = 0;
         
-        var bytesArray = self.arrayOfBytes();
+        var bytesArray = self.bytes();
         
         for (var i = 0; i < bytesArray.count; i++) {
             var b = bytesArray[i]
@@ -85,7 +85,7 @@ extension NSData {
         return s;
     }
     
-    internal func arrayOfBytes() -> Array<Byte> {
+    internal func bytes() -> [Byte] {
         let count = self.length / sizeof(Byte)
         var bytesArray = [Byte](count: count, repeatedValue: 0)
         self.getBytes(&bytesArray, length:count * sizeof(Byte))

+ 16 - 0
CryptoSwift/Operators.swift

@@ -5,6 +5,22 @@
 //  Created by Marcin Krzyzanowski on 02/09/14.
 //  Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
 //
+/*
+Bit shifting with overflow protection using overflow operator "&".
+Approach is consistent with standard overflow operators &+, &-, &*, &/
+and introduce new overflow operators for shifting: &<<, &>>
+
+Note: Works with unsigned integers values only
+
+Usage
+
+var i = 1       // init
+var j = i &<< 2 //shift left
+j &<<= 2        //shift left and assign
+
+
+@see: https://medium.com/@krzyzanowskim/swiftly-shift-bits-and-protect-yourself-be33016ce071
+*/
 
 import Foundation
 

+ 0 - 20
CryptoSwift/Playground/MyPlayground.playground/section-1.swift

@@ -2,23 +2,3 @@
 
 import Foundation
 
-func withBytes<T: UnsignedIntegerType>(bytes: [Byte]) -> T {
-    var totalBytes = Swift.min(bytes.count, sizeof(T))
-    // get slice of Int
-    var start = Swift.max(bytes.count - sizeof(T),0)
-    var intarr = [Byte](bytes[start..<(start + totalBytes)])
-    
-    // pad size if necessary
-    while (intarr.count < sizeof(T)) {
-        intarr.insert(0 as Byte, atIndex: 0)
-    }
-    intarr = intarr.reverse()
-    
-    var i:T = 0
-    var data = NSData(bytes: intarr, length: intarr.count)
-    data.getBytes(&i, length: sizeofValue(i));
-    return i
-}
-
-let a:UInt32 = withBytes([0x01,0x01,0x01])
-

+ 3 - 3
CryptoSwift/Playground/MyPlayground.playground/timeline.xctimeline

@@ -3,13 +3,13 @@
    version = "3.0">
    <TimelineItems>
       <LoggerValueHistoryTimelineItem
-         documentLocation = "file:///Users/marcinkrzyzanowski/Devel/CryptoSwift/CryptoSwift/Playground/MyPlayground.playground#CharacterRangeLen=0&amp;CharacterRangeLoc=72&amp;EndingLineNumber=3&amp;StartingLineNumber=3&amp;Timestamp=431362043.187306">
+         documentLocation = "file:///Users/marcinkrzyzanowski/Devel/CryptoSwift/CryptoSwift/Playground/MyPlayground.playground#CharacterRangeLen=0&amp;CharacterRangeLoc=71&amp;EndingLineNumber=3&amp;StartingLineNumber=3&amp;Timestamp=431365313.142192">
       </LoggerValueHistoryTimelineItem>
       <LoggerValueHistoryTimelineItem
-         documentLocation = "#CharacterRangeLen=0&amp;CharacterRangeLoc=72&amp;EndingColumnNumber=7&amp;EndingLineNumber=3&amp;StartingColumnNumber=5&amp;StartingLineNumber=3&amp;Timestamp=431362043.187547">
+         documentLocation = "#CharacterRangeLen=0&amp;CharacterRangeLoc=71&amp;EndingColumnNumber=7&amp;EndingLineNumber=3&amp;StartingColumnNumber=5&amp;StartingLineNumber=3&amp;Timestamp=431365313.142423">
       </LoggerValueHistoryTimelineItem>
       <LoggerValueHistoryTimelineItem
-         documentLocation = "#CharacterRangeLen=0&amp;CharacterRangeLoc=72&amp;EndingColumnNumber=20&amp;EndingLineNumber=4&amp;StartingColumnNumber=17&amp;StartingLineNumber=4&amp;Timestamp=431362043.187763">
+         documentLocation = "#CharacterRangeLen=0&amp;CharacterRangeLoc=71&amp;EndingColumnNumber=20&amp;EndingLineNumber=3&amp;StartingColumnNumber=17&amp;StartingLineNumber=3&amp;Timestamp=431365313.142639">
       </LoggerValueHistoryTimelineItem>
    </TimelineItems>
 </Timeline>

+ 2 - 2
CryptoSwift/UInt32Extension.swift

@@ -8,10 +8,10 @@
 
 import Foundation
 
-/* array of bytes */
+/** array of bytes */
 extension UInt32 {
     public func bytes(_ totalBytes: Int = sizeof(UInt32)) -> [Byte] {
-        return bytesArray(self, totalBytes)
+        return arrayOfBytes(self, totalBytes)
     }
 
     public static func withBytes(bytes: Slice<Byte>) -> UInt32 {

+ 10 - 1
CryptoSwift/UInt64Extension.swift

@@ -11,6 +11,15 @@ import Foundation
 /** array of bytes */
 extension UInt64 {
     public func bytes(_ totalBytes: Int = sizeof(UInt64)) -> [Byte] {
-        return bytesArray(self, totalBytes)
+        return arrayOfBytes(self, totalBytes)
+    }
+
+    public static func withBytes(bytes: Slice<Byte>) -> UInt64 {
+        return UInt64.withBytes(Array(bytes))
+    }
+
+    /** Int with array bytes (little-endian) */
+    public static func withBytes(bytes: [Byte]) -> UInt64 {
+        return integerWithBytes(bytes)
     }
 }

+ 0 - 33
CryptoSwift/Utils.swift

@@ -32,37 +32,4 @@ func reverseBytes(value: UInt32) -> UInt32 {
     var tmp1 = ((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8)
     var tmp2 = ((value & 0x00FF0000) >> 8)  | ((value & 0xFF000000) >> 24)
     return tmp1 | tmp2
-}
-
-// MARK: Generics
-
-func integerWithBytes<T: IntegerType>(bytes: [Byte]) -> T {
-    var totalBytes = Swift.min(bytes.count, sizeof(T))
-    // get slice of Int
-    var start = Swift.max(bytes.count - sizeof(T),0)
-    var intarr = [Byte](bytes[start..<(start + totalBytes)])
-    
-    // pad size if necessary
-    while (intarr.count < sizeof(T)) {
-        intarr.insert(0 as Byte, atIndex: 0)
-    }
-    intarr = intarr.reverse()
-    
-    var i:T = 0
-    var data = NSData(bytes: intarr, length: intarr.count)
-    data.getBytes(&i, length: sizeofValue(i));
-    return i
-}
-
-/** array of bytes, little-endian representation */
-func bytesArray<T>(value:T, totalBytes:Int) -> [Byte] {
-    var bytes = [Byte](count: totalBytes, repeatedValue: 0)
-    var data = NSData(bytes: [value] as [T], length: min(sizeof(T),totalBytes))
-    
-    // then convert back to bytes, byte by byte
-    for i in 0..<data.length {
-        data.getBytes(&bytes[totalBytes - 1 - i], range:NSRange(location:i, length:sizeof(Byte)))
-    }
-    
-    return bytes
 }