فهرست منبع

Wrap BigInt in CS namepsace

Marcin Krzyzanowski 3 سال پیش
والد
کامیت
66933e0e3e
26فایلهای تغییر یافته به همراه496 افزوده شده و 464 حذف شده
  1. 7 3
      CryptoSwift.xcodeproj/project.pbxproj
  2. 0 74
      Sources/CryptoSwift/BigInt/BigInt.swift
  3. 16 16
      Sources/CryptoSwift/CS.BigInt/Addition.swift
  4. 78 0
      Sources/CryptoSwift/CS.BigInt/BigInt.swift
  5. 72 69
      Sources/CryptoSwift/CS.BigInt/BigUInt.swift
  6. 23 23
      Sources/CryptoSwift/CS.BigInt/Bitwise Ops.swift
  7. 19 0
      Sources/CryptoSwift/CS.BigInt/CS.swift
  8. 43 41
      Sources/CryptoSwift/CS.BigInt/Codable.swift
  9. 10 10
      Sources/CryptoSwift/CS.BigInt/Comparable.swift
  10. 6 6
      Sources/CryptoSwift/CS.BigInt/Data Conversion.swift
  11. 31 31
      Sources/CryptoSwift/CS.BigInt/Division.swift
  12. 14 14
      Sources/CryptoSwift/CS.BigInt/Exponentiation.swift
  13. 11 11
      Sources/CryptoSwift/CS.BigInt/Floating Point Conversion.swift
  14. 12 12
      Sources/CryptoSwift/CS.BigInt/GCD.swift
  15. 2 2
      Sources/CryptoSwift/CS.BigInt/Hashable.swift
  16. 8 8
      Sources/CryptoSwift/CS.BigInt/Integer Conversion.swift
  17. 15 15
      Sources/CryptoSwift/CS.BigInt/Multiplication.swift
  18. 11 11
      Sources/CryptoSwift/CS.BigInt/Prime Test.swift
  19. 10 10
      Sources/CryptoSwift/CS.BigInt/Random.swift
  20. 23 23
      Sources/CryptoSwift/CS.BigInt/Shifts.swift
  21. 9 9
      Sources/CryptoSwift/CS.BigInt/Square Root.swift
  22. 10 10
      Sources/CryptoSwift/CS.BigInt/Strideable.swift
  23. 24 24
      Sources/CryptoSwift/CS.BigInt/String Conversion.swift
  24. 14 14
      Sources/CryptoSwift/CS.BigInt/Subtraction.swift
  25. 12 12
      Sources/CryptoSwift/CS.BigInt/Words and Bits.swift
  26. 16 16
      Sources/CryptoSwift/RSA.swift

+ 7 - 3
CryptoSwift.xcodeproj/project.pbxproj

@@ -67,6 +67,7 @@
 		7564F0642072ED7000CA5A96 /* CryptoSwift.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 754BE45519693E190098E6F3 /* CryptoSwift.framework */; };
 		7564F0652072ED7000CA5A96 /* CryptoSwift.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 754BE45519693E190098E6F3 /* CryptoSwift.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
 		756A64C62111083B00BE8805 /* StreamEncryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 756A64C52111083B00BE8805 /* StreamEncryptor.swift */; };
+		7571938E2816BFE3001C3AC0 /* CS.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7571938D2816BFE3001C3AC0 /* CS.swift */; };
 		757DA2531A4ED0A4002BA3EF /* PaddingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757DA2521A4ED0A4002BA3EF /* PaddingTests.swift */; };
 		757DA2551A4ED408002BA3EF /* AESTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757DA2541A4ED408002BA3EF /* AESTests.swift */; };
 		757DA2591A4ED4D7002BA3EF /* ChaCha20Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 757DA2581A4ED4D7002BA3EF /* ChaCha20Tests.swift */; };
@@ -287,6 +288,7 @@
 		7564F0602072EAEB00CA5A96 /* TestsPerformance-iOS.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "TestsPerformance-iOS.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
 		756A64C52111083B00BE8805 /* StreamEncryptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StreamEncryptor.swift; sourceTree = "<group>"; };
 		756BFDCA1A82B87300B9D9A4 /* Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Bridging.h; sourceTree = "<group>"; };
+		7571938D2816BFE3001C3AC0 /* CS.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CS.swift; sourceTree = "<group>"; };
 		7576F64C20725BD5006688F8 /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = "<group>"; };
 		7576F6EB20726319006688F8 /* DigestTestsPerf.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DigestTestsPerf.swift; sourceTree = "<group>"; };
 		7576F6EE20726422006688F8 /* AESTestsPerf.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AESTestsPerf.swift; sourceTree = "<group>"; };
@@ -427,7 +429,7 @@
 			name = Frameworks;
 			sourceTree = "<group>";
 		};
-		6AC893DF26DB94F700F7E787 /* BigInt */ = {
+		6AC893DF26DB94F700F7E787 /* CS.BigInt */ = {
 			isa = PBXGroup;
 			children = (
 				6AC893E026DB950C00F7E787 /* Addition.swift */,
@@ -452,8 +454,9 @@
 				6AC893F326DB950E00F7E787 /* String Conversion.swift */,
 				6AC893EA26DB950D00F7E787 /* Subtraction.swift */,
 				6AC893E926DB950D00F7E787 /* Words and Bits.swift */,
+				7571938D2816BFE3001C3AC0 /* CS.swift */,
 			);
-			path = BigInt;
+			path = CS.BigInt;
 			sourceTree = "<group>";
 		};
 		75211F93207249D8004E41F8 /* CryptoSwift-TestHostApp */ = {
@@ -595,7 +598,7 @@
 				75EC52391EE8B6CA0048EB3B /* Array+Extension.swift */,
 				75EC523A1EE8B6CA0048EB3B /* Authenticator.swift */,
 				75EC523B1EE8B6CA0048EB3B /* BatchedCollection.swift */,
-				6AC893DF26DB94F700F7E787 /* BigInt */,
+				6AC893DF26DB94F700F7E787 /* CS.BigInt */,
 				75EC523C1EE8B6CA0048EB3B /* Bit.swift */,
 				75EC523D1EE8B6CA0048EB3B /* BlockCipher.swift */,
 				75EC523E1EE8B6CA0048EB3B /* BlockMode */,
@@ -994,6 +997,7 @@
 				751EE9781F93996100161FFC /* AES.Cryptors.swift in Sources */,
 				75EC527D1EE8B8130048EB3B /* Array+Extension.swift in Sources */,
 				75D7AF38208BFB1600D22BEB /* UInt128.swift in Sources */,
+				7571938E2816BFE3001C3AC0 /* CS.swift in Sources */,
 				75EC52B31EE8B83D0048EB3B /* UInt16+Extension.swift in Sources */,
 				75EC52A81EE8B8390048EB3B /* PKCS5.swift in Sources */,
 				1467460F2017BB3600DF04ED /* AEAD.swift in Sources */,

+ 0 - 74
Sources/CryptoSwift/BigInt/BigInt.swift

@@ -1,74 +0,0 @@
-//
-//  BigInt.swift
-//  BigInt
-//
-//  Created by Károly Lőrentey on 2015-12-27.
-//  Copyright © 2016-2017 Károly Lőrentey.
-//
-
-//MARK: BigInt
-
-/// An arbitary precision signed integer type, also known as a "big integer".
-///
-/// Operations on big integers never overflow, but they might take a long time to execute.
-/// The amount of memory (and address space) available is the only constraint to the magnitude of these numbers.
-///
-/// This particular big integer type uses base-2^64 digits to represent integers.
-///
-/// `BigInt` is essentially a tiny wrapper that extends `BigUInt` with a sign bit and provides signed integer
-/// operations. Both the underlying absolute value and the negative/positive flag are available as read-write 
-/// properties.
-///
-/// Not all algorithms of `BigUInt` are available for `BigInt` values; for example, there is no square root or
-/// primality test for signed integers. When you need to call one of these, just extract the absolute value:
-///
-/// ```Swift
-/// BigInt(255).abs.isPrime()   // Returns false
-/// ```
-///
-public struct BigInt: SignedInteger {
-    public enum Sign {
-        case plus
-        case minus
-    }
-
-    public typealias Magnitude = BigUInt
-
-    /// The type representing a digit in `BigInt`'s underlying number system.
-    public typealias Word = BigUInt.Word
-    
-    public static var isSigned: Bool {
-        return true
-    }
-
-    /// The absolute value of this integer.
-    public var magnitude: BigUInt
-
-    /// True iff the value of this integer is negative.
-    public var sign: Sign
-
-    /// Initializes a new big integer with the provided absolute number and sign flag.
-    public init(sign: Sign, magnitude: BigUInt) {
-        self.sign = (magnitude.isZero ? .plus : sign)
-        self.magnitude = magnitude
-    }
-
-    /// Return true iff this integer is zero.
-    ///
-    /// - Complexity: O(1)
-    public var isZero: Bool {
-        return magnitude.isZero
-    }
-
-    /// Returns `-1` if this value is negative and `1` if it’s positive; otherwise, `0`.
-    ///
-    /// - Returns: The sign of this number, expressed as an integer of the same type.
-    public func signum() -> BigInt {
-        switch sign {
-        case .plus:
-            return isZero ? 0 : 1
-        case .minus:
-            return -1
-        }
-    }
-}

+ 16 - 16
Sources/CryptoSwift/BigInt/Addition.swift → Sources/CryptoSwift/CS.BigInt/Addition.swift

@@ -1,12 +1,12 @@
 //
 //  Addition.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2016-01-03.
 //  Copyright © 2016-2017 Károly Lőrentey.
 //
 
-extension BigUInt {
+extension CS.BigUInt {
     //MARK: Addition
     
     /// Add `word` to this integer in place.
@@ -29,7 +29,7 @@ extension BigUInt {
     /// `d` is shifted `shift` words to the left before being added.
     ///
     /// - Complexity: O(max(count, shift))
-    internal func addingWord(_ word: Word, shiftedBy shift: Int = 0) -> BigUInt {
+    internal func addingWord(_ word: Word, shiftedBy shift: Int = 0) -> CS.BigUInt {
         var r = self
         r.addWord(word, shiftedBy: shift)
         return r
@@ -39,7 +39,7 @@ extension BigUInt {
     /// `b` is shifted `shift` words to the left before being added.
     ///
     /// - Complexity: O(max(count, b.count + shift))
-    internal mutating func add(_ b: BigUInt, shiftedBy shift: Int = 0) {
+    internal mutating func add(_ b: CS.BigUInt, shiftedBy shift: Int = 0) {
         precondition(shift >= 0)
         var carry = false
         var bi = 0
@@ -64,7 +64,7 @@ extension BigUInt {
     /// `b` is shifted `shift` words to the left before being added.
     ///
     /// - Complexity: O(max(count, b.count + shift))
-    internal func adding(_ b: BigUInt, shiftedBy shift: Int = 0) -> BigUInt {
+    internal func adding(_ b: CS.BigUInt, shiftedBy shift: Int = 0) -> CS.BigUInt {
         var r = self
         r.add(b, shiftedBy: shift)
         return r
@@ -81,45 +81,45 @@ extension BigUInt {
     /// Add `a` and `b` together and return the result.
     ///
     /// - Complexity: O(max(a.count, b.count))
-    public static func +(a: BigUInt, b: BigUInt) -> BigUInt {
+    public static func +(a: CS.BigUInt, b: CS.BigUInt) -> CS.BigUInt {
         return a.adding(b)
     }
 
     /// Add `a` and `b` together, and store the sum in `a`.
     ///
     /// - Complexity: O(max(a.count, b.count))
-    public static func +=(a: inout BigUInt, b: BigUInt) {
+    public static func +=(a: inout CS.BigUInt, b: CS.BigUInt) {
         a.add(b, shiftedBy: 0)
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     /// Add `a` to `b` and return the result.
-    public static func +(a: BigInt, b: BigInt) -> BigInt {
+    public static func +(a: CS.BigInt, b: CS.BigInt) -> CS.BigInt {
         switch (a.sign, b.sign) {
         case (.plus, .plus):
-            return BigInt(sign: .plus, magnitude: a.magnitude + b.magnitude)
+            return CS.BigInt(sign: .plus, magnitude: a.magnitude + b.magnitude)
         case (.minus, .minus):
-            return BigInt(sign: .minus, magnitude: a.magnitude + b.magnitude)
+            return CS.BigInt(sign: .minus, magnitude: a.magnitude + b.magnitude)
         case (.plus, .minus):
             if a.magnitude >= b.magnitude {
-                return BigInt(sign: .plus, magnitude: a.magnitude - b.magnitude)
+                return CS.BigInt(sign: .plus, magnitude: a.magnitude - b.magnitude)
             }
             else {
-                return BigInt(sign: .minus, magnitude: b.magnitude - a.magnitude)
+                return CS.BigInt(sign: .minus, magnitude: b.magnitude - a.magnitude)
             }
         case (.minus, .plus):
             if b.magnitude >= a.magnitude {
-                return BigInt(sign: .plus, magnitude: b.magnitude - a.magnitude)
+                return CS.BigInt(sign: .plus, magnitude: b.magnitude - a.magnitude)
             }
             else {
-                return BigInt(sign: .minus, magnitude: a.magnitude - b.magnitude)
+                return CS.BigInt(sign: .minus, magnitude: a.magnitude - b.magnitude)
             }
         }
     }
 
     /// Add `b` to `a` in place.
-    public static func +=(a: inout BigInt, b: BigInt) {
+    public static func +=(a: inout CS.BigInt, b: CS.BigInt) {
         a = a + b
     }
 }

+ 78 - 0
Sources/CryptoSwift/CS.BigInt/BigInt.swift

@@ -0,0 +1,78 @@
+//
+//  CS.BigInt.swift
+//  CS.BigInt
+//
+//  Created by Károly Lőrentey on 2015-12-27.
+//  Copyright © 2016-2017 Károly Lőrentey.
+//
+
+//MARK: CS.BigInt
+
+extension CS {
+
+  /// An arbitary precision signed integer type, also known as a "big integer".
+  ///
+  /// Operations on big integers never overflow, but they might take a long time to execute.
+  /// The amount of memory (and address space) available is the only constraint to the magnitude of these numbers.
+  ///
+  /// This particular big integer type uses base-2^64 digits to represent integers.
+  ///
+  /// `BigInt` is essentially a tiny wrapper that extends `BigUInt` with a sign bit and provides signed integer
+  /// operations. Both the underlying absolute value and the negative/positive flag are available as read-write
+  /// properties.
+  ///
+  /// Not all algorithms of `BigUInt` are available for `BigInt` values; for example, there is no square root or
+  /// primality test for signed integers. When you need to call one of these, just extract the absolute value:
+  ///
+  /// ```Swift
+  /// CS.BigInt(255).abs.isPrime()   // Returns false
+  /// ```
+  ///
+  public struct BigInt: SignedInteger {
+      public enum Sign {
+          case plus
+          case minus
+      }
+
+      public typealias Magnitude = BigUInt
+
+      /// The type representing a digit in `BigInt`'s underlying number system.
+      public typealias Word = BigUInt.Word
+
+      public static var isSigned: Bool {
+          return true
+      }
+
+      /// The absolute value of this integer.
+      public var magnitude: BigUInt
+
+      /// True iff the value of this integer is negative.
+      public var sign: Sign
+
+      /// Initializes a new big integer with the provided absolute number and sign flag.
+      public init(sign: Sign, magnitude: BigUInt) {
+          self.sign = (magnitude.isZero ? .plus : sign)
+          self.magnitude = magnitude
+      }
+
+      /// Return true iff this integer is zero.
+      ///
+      /// - Complexity: O(1)
+      public var isZero: Bool {
+          return magnitude.isZero
+      }
+
+      /// Returns `-1` if this value is negative and `1` if it’s positive; otherwise, `0`.
+      ///
+      /// - Returns: The sign of this number, expressed as an integer of the same type.
+      public func signum() -> CS.BigInt {
+          switch sign {
+          case .plus:
+              return isZero ? 0 : 1
+          case .minus:
+              return -1
+          }
+      }
+  }
+
+}

+ 72 - 69
Sources/CryptoSwift/BigInt/BigUInt.swift → Sources/CryptoSwift/CS.BigInt/BigUInt.swift

@@ -6,61 +6,65 @@
 //  Copyright © 2016-2017 Károly Lőrentey.
 //
 
-/// An arbitary precision unsigned integer type, also known as a "big integer".
-///
-/// Operations on big integers never overflow, but they may take a long time to execute.
-/// The amount of memory (and address space) available is the only constraint to the magnitude of these numbers.
-///
-/// This particular big integer type uses base-2^64 digits to represent integers; you can think of it as a wrapper
-/// around `Array<UInt64>`. (In fact, `BigUInt` only uses an array if there are more than two digits.)
-public struct BigUInt: UnsignedInteger {
-    /// The type representing a digit in `BigUInt`'s underlying number system.
-    public typealias Word = UInt
-
-    /// The storage variants of a `BigUInt`.
-    enum Kind {
-        /// Value consists of the two specified words (low and high). Either or both words may be zero.
-        case inline(Word, Word)
-        /// Words are stored in a slice of the storage array.
-        case slice(from: Int, to: Int)
-        /// Words are stored in the storage array.
-        case array
-    }
+extension CS {
 
-    internal fileprivate (set) var kind: Kind // Internal for testing only
-    internal fileprivate (set) var storage: [Word] // Internal for testing only; stored separately to prevent COW copies
+  /// An arbitary precision unsigned integer type, also known as a "big integer".
+  ///
+  /// Operations on big integers never overflow, but they may take a long time to execute.
+  /// The amount of memory (and address space) available is the only constraint to the magnitude of these numbers.
+  ///
+  /// This particular big integer type uses base-2^64 digits to represent integers; you can think of it as a wrapper
+  /// around `Array<UInt64>`. (In fact, `BigUInt` only uses an array if there are more than two digits.)
+  public struct BigUInt: UnsignedInteger {
+      /// The type representing a digit in `BigUInt`'s underlying number system.
+      public typealias Word = UInt
 
-    /// Initializes a new BigUInt with value 0.
-    public init() {
-        self.kind = .inline(0, 0)
-        self.storage = []
-    }
+      /// The storage variants of a `BigUInt`.
+      enum Kind {
+          /// Value consists of the two specified words (low and high). Either or both words may be zero.
+          case inline(Word, Word)
+          /// Words are stored in a slice of the storage array.
+          case slice(from: Int, to: Int)
+          /// Words are stored in the storage array.
+          case array
+      }
 
-    internal init(word: Word) {
-        self.kind = .inline(word, 0)
-        self.storage = []
-    }
+      internal fileprivate (set) var kind: Kind // Internal for testing only
+      internal fileprivate (set) var storage: [Word] // Internal for testing only; stored separately to prevent COW copies
 
-    internal init(low: Word, high: Word) {
-        self.kind = .inline(low, high)
-        self.storage = []
-    }
+      /// Initializes a new BigUInt with value 0.
+      public init() {
+          self.kind = .inline(0, 0)
+          self.storage = []
+      }
 
-    /// Initializes a new BigUInt with the specified digits. The digits are ordered from least to most significant.
-    public init(words: [Word]) {
-        self.kind = .array
-        self.storage = words
-        normalize()
-    }
+      internal init(word: Word) {
+          self.kind = .inline(word, 0)
+          self.storage = []
+      }
+
+      internal init(low: Word, high: Word) {
+          self.kind = .inline(low, high)
+          self.storage = []
+      }
+
+      /// Initializes a new BigUInt with the specified digits. The digits are ordered from least to most significant.
+      public init(words: [Word]) {
+          self.kind = .array
+          self.storage = words
+          normalize()
+      }
+
+      internal init(words: [Word], from startIndex: Int, to endIndex: Int) {
+          self.kind = .slice(from: startIndex, to: endIndex)
+          self.storage = words
+          normalize()
+      }
+  }
 
-    internal init(words: [Word], from startIndex: Int, to endIndex: Int) {
-        self.kind = .slice(from: startIndex, to: endIndex)
-        self.storage = words
-        normalize()
-    }
 }
 
-extension BigUInt {
+extension CS.BigUInt {
     public static var isSigned: Bool {
         return false
     }
@@ -80,12 +84,12 @@ extension BigUInt {
     /// Returns `1` if this value is, positive; otherwise, `0`.
     ///
     /// - Returns: The sign of this number, expressed as an integer of the same type.
-    public func signum() -> BigUInt {
+    public func signum() -> CS.BigUInt {
         return isZero ? 0 : 1
     }
 }
 
-extension BigUInt {
+extension CS.BigUInt {
     mutating func ensureArray() {
         switch kind {
         case let .inline(w0, w1):
@@ -168,7 +172,7 @@ extension BigUInt {
     }
 
     /// Set this integer to `value` by copying its digits without releasing allocated storage capacity (if any).
-    mutating func load(_ value: BigUInt) {
+    mutating func load(_ value: CS.BigUInt) {
         switch kind {
         case .inline, .slice:
             self = value
@@ -179,7 +183,7 @@ extension BigUInt {
     }
 }
 
-extension BigUInt {
+extension CS.BigUInt {
     //MARK: Collection-like members
 
     /// The number of digits in this integer, excluding leading zero digits.
@@ -255,38 +259,38 @@ extension BigUInt {
     }
 
     /// Returns an integer built from the digits of this integer in the given range.
-    internal func extract(_ bounds: Range<Int>) -> BigUInt {
+    internal func extract(_ bounds: Range<Int>) -> CS.BigUInt {
         switch kind {
         case let .inline(w0, w1):
             let bounds = bounds.clamped(to: 0 ..< 2)
             if bounds == 0 ..< 2 {
-                return BigUInt(low: w0, high: w1)
+                return CS.BigUInt(low: w0, high: w1)
             }
             else if bounds == 0 ..< 1 {
-                return BigUInt(word: w0)
+                return CS.BigUInt(word: w0)
             }
             else if bounds == 1 ..< 2 {
-                return BigUInt(word: w1)
+                return CS.BigUInt(word: w1)
             }
             else {
-                return BigUInt()
+                return CS.BigUInt()
             }
         case let .slice(from: start, to: end):
             let s = Swift.min(end, start + Swift.max(bounds.lowerBound, 0))
             let e = Swift.max(s, (bounds.upperBound > end - start ? end : start + bounds.upperBound))
-            return BigUInt(words: storage, from: s, to: e)
+            return CS.BigUInt(words: storage, from: s, to: e)
         case .array:
             let b = bounds.clamped(to: storage.startIndex ..< storage.endIndex)
-            return BigUInt(words: storage, from: b.lowerBound, to: b.upperBound)
+            return CS.BigUInt(words: storage, from: b.lowerBound, to: b.upperBound)
         }
     }
 
-    internal func extract<Bounds: RangeExpression>(_ bounds: Bounds) -> BigUInt where Bounds.Bound == Int {
+    internal func extract<Bounds: RangeExpression>(_ bounds: Bounds) -> CS.BigUInt where Bounds.Bound == Int {
         return self.extract(bounds.relative(to: 0 ..< Int.max))
     }
 }
 
-extension BigUInt {
+extension CS.BigUInt {
     internal mutating func shiftRight(byWords amount: Int) {
         assert(amount >= 0)
         guard amount > 0 else { return }
@@ -343,18 +347,18 @@ extension BigUInt {
     }
 }
 
-extension BigUInt {
+extension CS.BigUInt {
     //MARK: Low and High
-    
+
     /// Split this integer into a high-order and a low-order part.
     ///
     /// - Requires: count > 1
-    /// - Returns: `(low, high)` such that 
+    /// - Returns: `(low, high)` such that
     ///   - `self == low.add(high, shiftedBy: middleIndex)`
     ///   - `high.width <= floor(width / 2)`
     ///   - `low.width <= ceil(width / 2)`
     /// - Complexity: Typically O(1), but O(count) in the worst case, because high-order zero digits need to be removed after the split.
-    internal var split: (high: BigUInt, low: BigUInt) {
+    internal var split: (high: CS.BigUInt, low: CS.BigUInt) {
         precondition(count > 1)
         let mid = middleIndex
         return (self.extract(mid...), self.extract(..<mid))
@@ -367,20 +371,19 @@ extension BigUInt {
         return (count + 1) / 2
     }
 
-    /// The low-order half of this BigUInt.
+    /// The low-order half of this CS.BigUInt.
     ///
     /// - Returns: `self[0 ..< middleIndex]`
     /// - Requires: count > 1
-    internal var low: BigUInt {
+    internal var low: CS.BigUInt {
         return self.extract(0 ..< middleIndex)
     }
 
-    /// The high-order half of this BigUInt.
+    /// The high-order half of this CS.BigUInt.
     ///
     /// - Returns: `self[middleIndex ..< count]`
     /// - Requires: count > 1
-    internal var high: BigUInt {
+    internal var high: CS.BigUInt {
         return self.extract(middleIndex ..< count)
     }
 }
-

+ 23 - 23
Sources/CryptoSwift/BigInt/Bitwise Ops.swift → Sources/CryptoSwift/CS.BigInt/Bitwise Ops.swift

@@ -1,6 +1,6 @@
 //
 //  Bitwise Ops.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2016-01-03.
 //  Copyright © 2016-2017 Károly Lőrentey.
@@ -8,18 +8,18 @@
 
 //MARK: Bitwise Operations
 
-extension BigUInt {
+extension CS.BigUInt {
     /// Return the ones' complement of `a`.
     ///
     /// - Complexity: O(a.count)
-    public static prefix func ~(a: BigUInt) -> BigUInt {
-        return BigUInt(words: a.words.map { ~$0 })
+    public static prefix func ~(a: CS.BigUInt) -> CS.BigUInt {
+        return CS.BigUInt(words: a.words.map { ~$0 })
     }
 
     /// Calculate the bitwise OR of `a` and `b`, and store the result in `a`.
     ///
     /// - Complexity: O(max(a.count, b.count))
-    public static func |= (a: inout BigUInt, b: BigUInt) {
+    public static func |= (a: inout CS.BigUInt, b: CS.BigUInt) {
         a.reserveCapacity(b.count)
         for i in 0 ..< b.count {
             a[i] |= b[i]
@@ -29,7 +29,7 @@ extension BigUInt {
     /// Calculate the bitwise AND of `a` and `b` and return the result.
     ///
     /// - Complexity: O(max(a.count, b.count))
-    public static func &= (a: inout BigUInt, b: BigUInt) {
+    public static func &= (a: inout CS.BigUInt, b: CS.BigUInt) {
         for i in 0 ..< Swift.max(a.count, b.count) {
             a[i] &= b[i]
         }
@@ -38,7 +38,7 @@ extension BigUInt {
     /// Calculate the bitwise XOR of `a` and `b` and return the result.
     ///
     /// - Complexity: O(max(a.count, b.count))
-    public static func ^= (a: inout BigUInt, b: BigUInt) {
+    public static func ^= (a: inout CS.BigUInt, b: CS.BigUInt) {
         a.reserveCapacity(b.count)
         for i in 0 ..< b.count {
             a[i] ^= b[i]
@@ -46,17 +46,17 @@ extension BigUInt {
     }
 }
 
-extension BigInt {
-    public static prefix func ~(x: BigInt) -> BigInt {
+extension CS.BigInt {
+    public static prefix func ~(x: CS.BigInt) -> CS.BigInt {
         switch x.sign {
         case .plus:
-            return BigInt(sign: .minus, magnitude: x.magnitude + 1)
+            return CS.BigInt(sign: .minus, magnitude: x.magnitude + 1)
         case .minus:
-            return BigInt(sign: .plus, magnitude: x.magnitude - 1)
+            return CS.BigInt(sign: .plus, magnitude: x.magnitude - 1)
         }
     }
     
-    public static func &(lhs: inout BigInt, rhs: BigInt) -> BigInt {
+    public static func &(lhs: inout CS.BigInt, rhs: CS.BigInt) -> CS.BigInt {
         let left = lhs.words
         let right = rhs.words
         // Note we aren't using left.count/right.count here; we account for the sign bit separately later.
@@ -68,12 +68,12 @@ extension BigInt {
         }
         if lhs.sign == .minus && rhs.sign == .minus {
             words.twosComplement()
-            return BigInt(sign: .minus, magnitude: BigUInt(words: words))
+            return CS.BigInt(sign: .minus, magnitude: CS.BigUInt(words: words))
         }
-        return BigInt(sign: .plus, magnitude: BigUInt(words: words))
+        return CS.BigInt(sign: .plus, magnitude: CS.BigUInt(words: words))
     }
     
-    public static func |(lhs: inout BigInt, rhs: BigInt) -> BigInt {
+    public static func |(lhs: inout CS.BigInt, rhs: CS.BigInt) -> CS.BigInt {
         let left = lhs.words
         let right = rhs.words
         // Note we aren't using left.count/right.count here; we account for the sign bit separately later.
@@ -85,12 +85,12 @@ extension BigInt {
         }
         if lhs.sign == .minus || rhs.sign == .minus {
             words.twosComplement()
-            return BigInt(sign: .minus, magnitude: BigUInt(words: words))
+            return CS.BigInt(sign: .minus, magnitude: CS.BigUInt(words: words))
         }
-        return BigInt(sign: .plus, magnitude: BigUInt(words: words))
+        return CS.BigInt(sign: .plus, magnitude: CS.BigUInt(words: words))
     }
     
-    public static func ^(lhs: inout BigInt, rhs: BigInt) -> BigInt {
+    public static func ^(lhs: inout CS.BigInt, rhs: CS.BigInt) -> CS.BigInt {
         let left = lhs.words
         let right = rhs.words
         // Note we aren't using left.count/right.count here; we account for the sign bit separately later.
@@ -102,20 +102,20 @@ extension BigInt {
         }
         if (lhs.sign == .minus) != (rhs.sign == .minus) {
             words.twosComplement()
-            return BigInt(sign: .minus, magnitude: BigUInt(words: words))
+            return CS.BigInt(sign: .minus, magnitude: CS.BigUInt(words: words))
         }
-        return BigInt(sign: .plus, magnitude: BigUInt(words: words))
+        return CS.BigInt(sign: .plus, magnitude: CS.BigUInt(words: words))
     }
     
-    public static func &=(lhs: inout BigInt, rhs: BigInt) {
+    public static func &=(lhs: inout CS.BigInt, rhs: CS.BigInt) {
         lhs = lhs & rhs
     }
     
-    public static func |=(lhs: inout BigInt, rhs: BigInt) {
+    public static func |=(lhs: inout CS.BigInt, rhs: CS.BigInt) {
         lhs = lhs | rhs
     }
     
-    public static func ^=(lhs: inout BigInt, rhs: BigInt) {
+    public static func ^=(lhs: inout CS.BigInt, rhs: CS.BigInt) {
         lhs = lhs ^ rhs
     }
 }

+ 19 - 0
Sources/CryptoSwift/CS.BigInt/CS.swift

@@ -0,0 +1,19 @@
+//  CryptoSwift
+//
+//  Copyright (C) 2014-2022 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
+//  This software is provided 'as-is', without any express or implied warranty.
+//
+//  In no event will the authors be held liable for any damages arising from the use of this software.
+//
+//  Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
+//
+//  - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
+//  - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
+//  - This notice may not be removed or altered from any source or binary distribution.
+//
+
+import Foundation
+
+public enum CS {
+  // namespace
+}

+ 43 - 41
Sources/CryptoSwift/BigInt/Codable.swift → Sources/CryptoSwift/CS.BigInt/Codable.swift

@@ -1,45 +1,47 @@
 //
 //  Codable.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2017-8-11.
 //  Copyright © 2016-2017 Károly Lőrentey.
 //
 
+extension CS {
 
-// Little-endian to big-endian
-struct Units<Unit: FixedWidthInteger, Words: RandomAccessCollection>: RandomAccessCollection
-where Words.Element: FixedWidthInteger, Words.Index == Int {
-    typealias Word = Words.Element
-    let words: Words
-    init(of type: Unit.Type, _ words: Words) {
-        precondition(Word.bitWidth % Unit.bitWidth == 0 || Unit.bitWidth % Word.bitWidth == 0)
-        self.words = words
-    }
-    var count: Int { return (words.count * Word.bitWidth + Unit.bitWidth - 1) / Unit.bitWidth }
-    var startIndex: Int { return 0 }
-    var endIndex: Int { return count }
-    subscript(_ index: Int) -> Unit {
-        let index = count - 1 - index
-        if Unit.bitWidth == Word.bitWidth {
-            return Unit(words[index])
-        }
-        else if Unit.bitWidth > Word.bitWidth {
-            let c = Unit.bitWidth / Word.bitWidth
-            var unit: Unit = 0
-            var j = 0
-            for i in (c * index) ..< Swift.min(c * (index + 1), words.endIndex) {
-                unit |= Unit(words[i]) << j
-                j += Word.bitWidth
-            }
-            return unit
-        }
-        // Unit.bitWidth < Word.bitWidth
-        let c = Word.bitWidth / Unit.bitWidth
-        let i = index / c
-        let j = index % c
-        return Unit(truncatingIfNeeded: words[i] >> (j * Unit.bitWidth))
-    }
+  // Little-endian to big-endian
+  struct Units<Unit: FixedWidthInteger, Words: RandomAccessCollection>: RandomAccessCollection
+  where Words.Element: FixedWidthInteger, Words.Index == Int {
+      typealias Word = Words.Element
+      let words: Words
+      init(of type: Unit.Type, _ words: Words) {
+          precondition(Word.bitWidth % Unit.bitWidth == 0 || Unit.bitWidth % Word.bitWidth == 0)
+          self.words = words
+      }
+      var count: Int { return (words.count * Word.bitWidth + Unit.bitWidth - 1) / Unit.bitWidth }
+      var startIndex: Int { return 0 }
+      var endIndex: Int { return count }
+      subscript(_ index: Int) -> Unit {
+          let index = count - 1 - index
+          if Unit.bitWidth == Word.bitWidth {
+              return Unit(words[index])
+          }
+          else if Unit.bitWidth > Word.bitWidth {
+              let c = Unit.bitWidth / Word.bitWidth
+              var unit: Unit = 0
+              var j = 0
+              for i in (c * index) ..< Swift.min(c * (index + 1), words.endIndex) {
+                  unit |= Unit(words[i]) << j
+                  j += Word.bitWidth
+              }
+              return unit
+          }
+          // Unit.bitWidth < Word.bitWidth
+          let c = Word.bitWidth / Unit.bitWidth
+          let i = index / c
+          let j = index % c
+          return Unit(truncatingIfNeeded: words[i] >> (j * Unit.bitWidth))
+      }
+  }
 }
 
 extension Array where Element: FixedWidthInteger {
@@ -100,12 +102,12 @@ extension Array where Element: FixedWidthInteger {
     }
 }
 
-extension BigInt: Codable {
+extension CS.BigInt: Codable {
     public init(from decoder: Decoder) throws {
         var container = try decoder.unkeyedContainer()
 
         // Decode sign
-        let sign: BigInt.Sign
+        let sign: CS.BigInt.Sign
         switch try container.decode(String.self) {
         case "+":
             sign = .plus
@@ -121,7 +123,7 @@ extension BigInt: Codable {
             guard !container.isAtEnd else { return nil }
             return try container.decode(UInt64.self)
         }
-        let magnitude = BigUInt(words: words)
+        let magnitude = CS.BigUInt(words: words)
 
         self.init(sign: sign, magnitude: magnitude)
     }
@@ -129,7 +131,7 @@ extension BigInt: Codable {
     public func encode(to encoder: Encoder) throws {
         var container = encoder.unkeyedContainer()
         try container.encode(sign == .plus ? "+" : "-")
-        let units = Units(of: UInt64.self, self.magnitude.words)
+        let units = CS.Units(of: UInt64.self, self.magnitude.words)
         if units.isEmpty {
             try container.encode(0 as UInt64)
         }
@@ -139,9 +141,9 @@ extension BigInt: Codable {
     }
 }
 
-extension BigUInt: Codable {
+extension CS.BigUInt: Codable {
     public init(from decoder: Decoder) throws {
-        let value = try BigInt(from: decoder)
+        let value = try CS.BigInt(from: decoder)
         guard value.sign == .plus else {
             throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath,
                                                     debugDescription: "BigUInt cannot hold a negative value"))
@@ -150,6 +152,6 @@ extension BigUInt: Codable {
     }
 
     public func encode(to encoder: Encoder) throws {
-        try BigInt(sign: .plus, magnitude: self).encode(to: encoder)
+        try CS.BigInt(sign: .plus, magnitude: self).encode(to: encoder)
     }
 }

+ 10 - 10
Sources/CryptoSwift/BigInt/Comparable.swift → Sources/CryptoSwift/CS.BigInt/Comparable.swift

@@ -1,6 +1,6 @@
 //
 //  Comparable.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2016-01-03.
 //  Copyright © 2016-2017 Károly Lőrentey.
@@ -8,13 +8,13 @@
 
 import Foundation
 
-extension BigUInt: Comparable {
+extension CS.BigUInt: Comparable {
     //MARK: Comparison
     
     /// Compare `a` to `b` and return an `NSComparisonResult` indicating their order.
     ///
     /// - Complexity: O(count)
-    public static func compare(_ a: BigUInt, _ b: BigUInt) -> ComparisonResult {
+    public static func compare(_ a: CS.BigUInt, _ b: CS.BigUInt) -> ComparisonResult {
         if a.count != b.count { return a.count > b.count ? .orderedDescending : .orderedAscending }
         for i in (0 ..< a.count).reversed() {
             let ad = a[i]
@@ -27,26 +27,26 @@ extension BigUInt: Comparable {
     /// Return true iff `a` is equal to `b`.
     ///
     /// - Complexity: O(count)
-    public static func ==(a: BigUInt, b: BigUInt) -> Bool {
-        return BigUInt.compare(a, b) == .orderedSame
+    public static func ==(a: CS.BigUInt, b: CS.BigUInt) -> Bool {
+        return CS.BigUInt.compare(a, b) == .orderedSame
     }
 
     /// Return true iff `a` is less than `b`.
     ///
     /// - Complexity: O(count)
-    public static func <(a: BigUInt, b: BigUInt) -> Bool {
-        return BigUInt.compare(a, b) == .orderedAscending
+    public static func <(a: CS.BigUInt, b: CS.BigUInt) -> Bool {
+        return CS.BigUInt.compare(a, b) == .orderedAscending
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     /// Return true iff `a` is equal to `b`.
-    public static func ==(a: BigInt, b: BigInt) -> Bool {
+    public static func ==(a: CS.BigInt, b: CS.BigInt) -> Bool {
         return a.sign == b.sign && a.magnitude == b.magnitude
     }
 
     /// Return true iff `a` is less than `b`.
-    public static func <(a: BigInt, b: BigInt) -> Bool {
+    public static func <(a: CS.BigInt, b: CS.BigInt) -> Bool {
         switch (a.sign, b.sign) {
         case (.plus, .plus):
             return a.magnitude < b.magnitude

+ 6 - 6
Sources/CryptoSwift/BigInt/Data Conversion.swift → Sources/CryptoSwift/CS.BigInt/Data Conversion.swift

@@ -8,7 +8,7 @@
 
 import Foundation
 
-extension BigUInt {
+extension CS.BigUInt {
     //MARK: NSData Conversion
 
     /// Initialize a BigInt from bytes accessed from an UnsafeRawBufferPointer
@@ -109,7 +109,7 @@ extension BigUInt {
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     
     /// Initialize a BigInt from bytes accessed from an UnsafeRawBufferPointer,
     /// where the first byte indicates sign (0 for positive, 1 for negative)
@@ -131,7 +131,7 @@ extension BigInt {
         // to this byte in the future.
         self.sign = firstByte & 0b1 == 0 ? .plus : .minus
 
-        self.magnitude = BigUInt(UnsafeRawBufferPointer(rebasing: buffer.dropFirst(1)))
+        self.magnitude = CS.BigUInt(UnsafeRawBufferPointer(rebasing: buffer.dropFirst(1)))
     }
     
     /// Initializes an integer from the bits stored inside a piece of `Data`.
@@ -139,7 +139,7 @@ extension BigInt {
     /// byte to represent the sign (0 for positive, 1 for negative)
     public init(_ data: Data) {
         // This assumes Word is binary.
-        // This is the same assumption made when initializing BigUInt from Data
+        // This is the same assumption made when initializing CS.BigUInt from Data
         precondition(Word.bitWidth % 8 == 0)
 
         self.init()
@@ -155,7 +155,7 @@ extension BigInt {
         self.sign = firstByte & 0b1 == 0 ? .plus : .minus
         
         // The remaining bytes are read and stored as the magnitude
-        self.magnitude = BigUInt(data.dropFirst(1))
+        self.magnitude = CS.BigUInt(data.dropFirst(1))
     }
     
     /// Return a `Data` value that contains the base-256 representation of this integer, in network (big-endian) byte order and a prepended byte to indicate the sign (0 for positive, 1 for negative)
@@ -163,7 +163,7 @@ extension BigInt {
         // Create a data object for the magnitude portion of the BigInt
         let magnitudeData = self.magnitude.serialize()
         
-        // Similar to BigUInt, a value of 0 should return an initialized, empty Data struct
+        // Similar to CS.BigUInt, a value of 0 should return an initialized, empty Data struct
         guard magnitudeData.count > 0 else { return magnitudeData }
         
         // Create a new Data struct for the signed BigInt value

+ 31 - 31
Sources/CryptoSwift/BigInt/Division.swift → Sources/CryptoSwift/CS.BigInt/Division.swift

@@ -1,6 +1,6 @@
 //
 //  Division.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2016-01-03.
 //  Copyright © 2016-2017 Károly Lőrentey.
@@ -139,7 +139,7 @@ extension FixedWidthInteger {
     }
 }
 
-extension BigUInt {
+extension CS.BigUInt {
     //MARK: Division
 
     /// Divide this integer by the word `y`, leaving the quotient in its place and returning the remainder.
@@ -163,7 +163,7 @@ extension BigUInt {
     /// - Requires: y > 0
     /// - Returns: (quotient, remainder) where quotient = floor(x/y), remainder = x - quotient * y
     /// - Complexity: O(x.count)
-    internal func quotientAndRemainder(dividingByWord y: Word) -> (quotient: BigUInt, remainder: Word) {
+    internal func quotientAndRemainder(dividingByWord y: Word) -> (quotient:  CS.BigUInt, remainder: Word) {
         var div = self
         let mod = div.divide(byWord: y)
         return (div, mod)
@@ -171,7 +171,7 @@ extension BigUInt {
 
     /// Divide `x` by `y`, putting the quotient in `x` and the remainder in `y`.
     /// Reusing integers like this reduces the number of allocations during the calculation.
-    static func divide(_ x: inout BigUInt, by y: inout BigUInt) {
+    static func divide(_ x: inout  CS.BigUInt, by y: inout  CS.BigUInt) {
         // This is a Swift adaptation of "divmnu" from Hacker's Delight, which is in
         // turn a C adaptation of Knuth's Algorithm D (TAOCP vol 2, 4.3.1).
 
@@ -184,7 +184,7 @@ extension BigUInt {
         }
         if y.count == 1 {
             // The single-word case reduces to a simpler loop.
-            y = BigUInt(x.divide(byWord: y[0]))
+            y =  CS.BigUInt(x.divide(byWord: y[0]))
             return
         }
 
@@ -214,14 +214,14 @@ extension BigUInt {
         let z = y.leadingZeroBitCount
         y <<= z
         x <<= z // We'll calculate the remainder in the normalized dividend.
-        var quotient = BigUInt()
+        var quotient =  CS.BigUInt()
         assert(y.leadingZeroBitCount == 0)
 
         // We're ready to start the long division!
         let dc = y.count
         let d1 = y[dc - 1]
         let d0 = y[dc - 2]
-        var product: BigUInt = 0
+        var product:  CS.BigUInt = 0
         for j in (dc ... x.count).reversed() {
             // Approximate dividing the top dc+1 words of `remainder` using the topmost 3/2 words.
             let r2 = x[j]
@@ -253,12 +253,12 @@ extension BigUInt {
     }
 
     /// Divide `x` by `y`, putting the remainder in `x`.
-    mutating func formRemainder(dividingBy y: BigUInt, normalizedBy shift: Int) {
+    mutating func formRemainder(dividingBy y:  CS.BigUInt, normalizedBy shift: Int) {
         precondition(!y.isZero)
         assert(y.leadingZeroBitCount == 0)
         if y.count == 1 {
             let remainder = self.divide(byWord: y[0] >> shift)
-            self.load(BigUInt(remainder))
+            self.load(CS.BigUInt(remainder))
             return
         }
         self <<= shift
@@ -266,7 +266,7 @@ extension BigUInt {
             let dc = y.count
             let d1 = y[dc - 1]
             let d0 = y[dc - 2]
-            var product: BigUInt = 0
+            var product:  CS.BigUInt = 0
             for j in (dc ... self.count).reversed() {
                 let r2 = self[j]
                 let r1 = self[j - 1]
@@ -292,24 +292,24 @@ extension BigUInt {
     /// - Requires: `y > 0`
     /// - Returns: `(quotient, remainder)` where `quotient = floor(self/y)`, `remainder = self - quotient * y`
     /// - Complexity: O(count^2)
-    public func quotientAndRemainder(dividingBy y: BigUInt) -> (quotient: BigUInt, remainder: BigUInt) {
+    public func quotientAndRemainder(dividingBy y:  CS.BigUInt) -> (quotient:  CS.BigUInt, remainder:  CS.BigUInt) {
         var x = self
         var y = y
-        BigUInt.divide(&x, by: &y)
+         CS.BigUInt.divide(&x, by: &y)
         return (x, y)
     }
 
     /// Divide `x` by `y` and return the quotient.
     ///
     /// - Note: Use `divided(by:)` if you also need the remainder.
-    public static func /(x: BigUInt, y: BigUInt) -> BigUInt {
+    public static func /(x: CS.BigUInt, y: CS.BigUInt) -> CS.BigUInt {
         return x.quotientAndRemainder(dividingBy: y).quotient
     }
 
     /// Divide `x` by `y` and return the remainder.
     ///
     /// - Note: Use `divided(by:)` if you also need the remainder.
-    public static func %(x: BigUInt, y: BigUInt) -> BigUInt {
+    public static func %(x: CS.BigUInt, y: CS.BigUInt) -> CS.BigUInt {
         var x = x
         let shift = y.leadingZeroBitCount
         x.formRemainder(dividingBy: y << shift, normalizedBy: shift)
@@ -319,57 +319,57 @@ extension BigUInt {
     /// Divide `x` by `y` and store the quotient in `x`.
     ///
     /// - Note: Use `divided(by:)` if you also need the remainder.
-    public static func /=(x: inout BigUInt, y: BigUInt) {
+    public static func /=(x: inout  CS.BigUInt, y:  CS.BigUInt) {
         var y = y
-        BigUInt.divide(&x, by: &y)
+         CS.BigUInt.divide(&x, by: &y)
     }
 
     /// Divide `x` by `y` and store the remainder in `x`.
     ///
     /// - Note: Use `divided(by:)` if you also need the remainder.
-    public static func %=(x: inout BigUInt, y: BigUInt) {
+    public static func %=(x: inout CS.BigUInt, y: CS.BigUInt) {
         let shift = y.leadingZeroBitCount
         x.formRemainder(dividingBy: y << shift, normalizedBy: shift)
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     /// Divide this integer by `y` and return the resulting quotient and remainder.
     ///
     /// - Requires: `y > 0`
     /// - Returns: `(quotient, remainder)` where `quotient = floor(self/y)`, `remainder = self - quotient * y`
     /// - Complexity: O(count^2)
-    public func quotientAndRemainder(dividingBy y: BigInt) -> (quotient: BigInt, remainder: BigInt) {
+    public func quotientAndRemainder(dividingBy y: CS.BigInt) -> (quotient: CS.BigInt, remainder: CS.BigInt) {
         var a = self.magnitude
         var b = y.magnitude
-        BigUInt.divide(&a, by: &b)
-        return (BigInt(sign: self.sign == y.sign ? .plus : .minus, magnitude: a),
-                BigInt(sign: self.sign, magnitude: b))
+         CS.BigUInt.divide(&a, by: &b)
+        return ( CS.BigInt(sign: self.sign == y.sign ? .plus : .minus, magnitude: a),
+                CS.BigInt(sign: self.sign, magnitude: b))
     }
 
     /// Divide `a` by `b` and return the quotient. Traps if `b` is zero.
-    public static func /(a: BigInt, b: BigInt) -> BigInt {
-        return BigInt(sign: a.sign == b.sign ? .plus : .minus, magnitude: a.magnitude / b.magnitude)
+    public static func /(a: CS.BigInt, b: CS.BigInt) -> CS.BigInt {
+        return CS.BigInt(sign: a.sign == b.sign ? .plus : .minus, magnitude: a.magnitude / b.magnitude)
     }
 
     /// Divide `a` by `b` and return the remainder. The result has the same sign as `a`.
-    public static func %(a: BigInt, b: BigInt) -> BigInt {
-        return BigInt(sign: a.sign, magnitude: a.magnitude % b.magnitude)
+    public static func %(a: CS.BigInt, b: CS.BigInt) -> CS.BigInt {
+        return CS.BigInt(sign: a.sign, magnitude: a.magnitude % b.magnitude)
     }
 
     /// Return the result of `a` mod `b`. The result is always a nonnegative integer that is less than the absolute value of `b`.
-    public func modulus(_ mod: BigInt) -> BigInt {
+    public func modulus(_ mod: CS.BigInt) -> CS.BigInt {
         let remainder = self.magnitude % mod.magnitude
-        return BigInt(
+        return CS.BigInt(
             self.sign == .minus && !remainder.isZero
                 ? mod.magnitude - remainder
                 : remainder)
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     /// Divide `a` by `b` storing the quotient in `a`.
-    public static func /=(a: inout BigInt, b: BigInt) { a = a / b }
+    public static func /=(a: inout CS.BigInt, b: CS.BigInt) { a = a / b }
     /// Divide `a` by `b` storing the remainder in `a`.
-    public static func %=(a: inout BigInt, b: BigInt) { a = a % b }
+    public static func %=(a: inout CS.BigInt, b: CS.BigInt) { a = a % b }
 }

+ 14 - 14
Sources/CryptoSwift/BigInt/Exponentiation.swift → Sources/CryptoSwift/CS.BigInt/Exponentiation.swift

@@ -1,12 +1,12 @@
 //
 //  Exponentiation.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2016-01-03.
 //  Copyright © 2016-2017 Károly Lőrentey.
 //
 
-extension BigUInt {
+extension CS.BigUInt {
     //MARK: Exponentiation
 
     /// Returns this integer raised to the power `exponent`.
@@ -21,7 +21,7 @@ extension BigUInt {
     /// - Returns: 1 if `exponent == 0`, otherwise `self` raised to `exponent`. (This implies that `0.power(0) == 1`.)
     /// - SeeAlso: `BigUInt.power(_:, modulus:)`
     /// - Complexity: O((exponent * self.count)^log2(3)) or somesuch. The result may require a large amount of memory, too.
-    public func power(_ exponent: Int) -> BigUInt {
+    public func power(_ exponent: Int) -> CS.BigUInt {
         if exponent == 0 { return 1 }
         if exponent == 1 { return self }
         if exponent < 0 {
@@ -29,7 +29,7 @@ extension BigUInt {
             return self == 1 ? 1 : 0
         }
         if self <= 1 { return self }
-        var result = BigUInt(1)
+        var result = CS.BigUInt(1)
         var b = self
         var e = exponent
         while e > 0 {
@@ -49,12 +49,12 @@ extension BigUInt {
     /// [rtlb]: https://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method
     ///
     /// - Complexity: O(exponent.count * modulus.count^log2(3)) or somesuch
-    public func power(_ exponent: BigUInt, modulus: BigUInt) -> BigUInt {
+    public func power(_ exponent: CS.BigUInt, modulus: CS.BigUInt) -> CS.BigUInt {
         precondition(!modulus.isZero)
-        if modulus == (1 as BigUInt) { return 0 }
+        if modulus == (1 as CS.BigUInt) { return 0 }
         let shift = modulus.leadingZeroBitCount
         let normalizedModulus = modulus << shift
-        var result = BigUInt(1)
+        var result = CS.BigUInt(1)
         var b = self
         b.formRemainder(dividingBy: normalizedModulus, normalizedBy: shift)
         for var e in exponent.words {
@@ -72,7 +72,7 @@ extension BigUInt {
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     /// Returns this integer raised to the power `exponent`.
     ///
     /// This function calculates the result by [successively squaring the base while halving the exponent][expsqr].
@@ -85,8 +85,8 @@ extension BigInt {
     /// - Returns: 1 if `exponent == 0`, otherwise `self` raised to `exponent`. (This implies that `0.power(0) == 1`.)
     /// - SeeAlso: `BigUInt.power(_:, modulus:)`
     /// - Complexity: O((exponent * self.count)^log2(3)) or somesuch. The result may require a large amount of memory, too.
-    public func power(_ exponent: Int) -> BigInt {
-        return BigInt(sign: self.sign == .minus && exponent & 1 != 0 ? .minus : .plus,
+    public func power(_ exponent: Int) -> CS.BigInt {
+        return CS.BigInt(sign: self.sign == .minus && exponent & 1 != 0 ? .minus : .plus,
                       magnitude: self.magnitude.power(exponent))
     }
 
@@ -97,7 +97,7 @@ extension BigInt {
     /// [rtlb]: https://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method
     ///
     /// - Complexity: O(exponent.count * modulus.count^log2(3)) or somesuch
-    public func power(_ exponent: BigInt, modulus: BigInt) -> BigInt {
+    public func power(_ exponent: CS.BigInt, modulus: CS.BigInt) -> CS.BigInt {
         precondition(!modulus.isZero)
         if modulus.magnitude == 1 { return 0 }
         if exponent.isZero { return 1 }
@@ -107,13 +107,13 @@ extension BigInt {
             guard magnitude == 1 else { return 0 }
             guard sign == .minus else { return 1 }
             guard exponent.magnitude[0] & 1 != 0 else { return 1 }
-            return BigInt(modulus.magnitude - 1)
+            return CS.BigInt(modulus.magnitude - 1)
         }
         let power = self.magnitude.power(exponent.magnitude,
                                          modulus: modulus.magnitude)
         if self.sign == .plus || exponent.magnitude[0] & 1 == 0 || power.isZero {
-            return BigInt(power)
+            return CS.BigInt(power)
         }
-        return BigInt(modulus.magnitude - power)
+        return CS.BigInt(modulus.magnitude - power)
     }
 }

+ 11 - 11
Sources/CryptoSwift/BigInt/Floating Point Conversion.swift → Sources/CryptoSwift/CS.BigInt/Floating Point Conversion.swift

@@ -1,12 +1,12 @@
 //
 //  Floating Point Conversion.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2017-08-11.
 //  Copyright © 2016-2017 Károly Lőrentey.
 //
 
-extension BigUInt {
+extension CS.BigUInt {
     public init?<T: BinaryFloatingPoint>(exactly source: T) {
         guard source.isFinite else { return nil }
         guard !source.isZero else { self = 0; return }
@@ -16,7 +16,7 @@ extension BigUInt {
         assert(value.floatingPointClass == .positiveNormal)
         assert(value.exponent >= 0)
         let significand = value.significandBitPattern
-        self = (BigUInt(1) << value.exponent) + BigUInt(significand) >> (T.significandBitCount - Int(value.exponent))
+        self = (CS.BigUInt(1) << value.exponent) + CS.BigUInt(significand) >> (T.significandBitCount - Int(value.exponent))
     }
 
     public init<T: BinaryFloatingPoint>(_ source: T) {
@@ -24,15 +24,15 @@ extension BigUInt {
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     public init?<T: BinaryFloatingPoint>(exactly source: T) {
         switch source.sign{
         case .plus:
-            guard let magnitude = BigUInt(exactly: source) else { return nil }
-            self = BigInt(sign: .plus, magnitude: magnitude)
+            guard let magnitude = CS.BigUInt(exactly: source) else { return nil }
+            self = CS.BigInt(sign: .plus, magnitude: magnitude)
         case .minus:
-            guard let magnitude = BigUInt(exactly: -source) else { return nil }
-            self = BigInt(sign: .minus, magnitude: magnitude)
+            guard let magnitude = CS.BigUInt(exactly: -source) else { return nil }
+            self = CS.BigInt(sign: .minus, magnitude: magnitude)
         }
     }
 
@@ -42,7 +42,7 @@ extension BigInt {
 }
 
 extension BinaryFloatingPoint where RawExponent: FixedWidthInteger, RawSignificand: FixedWidthInteger {
-    public init(_ value: BigInt) {
+    public init(_ value: CS.BigInt) {
         guard !value.isZero else { self = 0; return }
         let v = value.magnitude
         let bitWidth = v.bitWidth
@@ -67,7 +67,7 @@ extension BinaryFloatingPoint where RawExponent: FixedWidthInteger, RawSignifica
                          significandBitPattern: RawSignificand(significand))
     }
 
-    public init(_ value: BigUInt) {
-        self.init(BigInt(sign: .plus, magnitude: value))
+    public init(_ value: CS.BigUInt) {
+        self.init(CS.BigInt(sign: .plus, magnitude: value))
     }
 }

+ 12 - 12
Sources/CryptoSwift/BigInt/GCD.swift → Sources/CryptoSwift/CS.BigInt/GCD.swift

@@ -1,18 +1,18 @@
 //
 //  GCD.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2016-01-03.
 //  Copyright © 2016-2017 Károly Lőrentey.
 //
 
-extension BigUInt {
+extension CS.BigUInt {
     //MARK: Greatest Common Divisor
     
     /// Returns the greatest common divisor of `self` and `b`.
     ///
     /// - Complexity: O(count^2) where count = max(self.count, b.count)
-    public func greatestCommonDivisor(with b: BigUInt) -> BigUInt {
+    public func greatestCommonDivisor(with b: CS.BigUInt) -> CS.BigUInt {
         // This is Stein's algorithm: https://en.wikipedia.org/wiki/Binary_GCD_algorithm
         if self.isZero { return b }
         if b.isZero { return self }
@@ -40,15 +40,15 @@ extension BigUInt {
     /// - Returns: If `gcd(self, modulus) == 1`, the value returned is an integer `a < modulus` such that `(a * self) % modulus == 1`. If `self` and `modulus` aren't coprime, the return value is `nil`.
     /// - Requires: modulus > 1
     /// - Complexity: O(count^3)
-    public func inverse(_ modulus: BigUInt) -> BigUInt? {
+    public func inverse(_ modulus: CS.BigUInt) -> CS.BigUInt? {
         precondition(modulus > 1)
-        var t1 = BigInt(0)
-        var t2 = BigInt(1)
+        var t1 = CS.BigInt(0)
+        var t2 = CS.BigInt(1)
         var r1 = modulus
         var r2 = self
         while !r2.isZero {
             let quotient = r1 / r2
-            (t1, t2) = (t2, t1 - BigInt(quotient) * t2)
+            (t1, t2) = (t2, t1 - CS.BigInt(quotient) * t2)
             (r1, r2) = (r2, r1 - quotient * r2)
         }
         if r1 > 1 { return nil }
@@ -57,12 +57,12 @@ extension BigUInt {
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     /// Returns the greatest common divisor of `a` and `b`.
     ///
     /// - Complexity: O(count^2) where count = max(a.count, b.count)
-    public func greatestCommonDivisor(with b: BigInt) -> BigInt {
-        return BigInt(self.magnitude.greatestCommonDivisor(with: b.magnitude))
+    public func greatestCommonDivisor(with b: CS.BigInt) -> CS.BigInt {
+        return CS.BigInt(self.magnitude.greatestCommonDivisor(with: b.magnitude))
     }
 
     /// Returns the [multiplicative inverse of this integer in modulo `modulus` arithmetic][inverse],
@@ -73,8 +73,8 @@ extension BigInt {
     /// - Returns: If `gcd(self, modulus) == 1`, the value returned is an integer `a < modulus` such that `(a * self) % modulus == 1`. If `self` and `modulus` aren't coprime, the return value is `nil`.
     /// - Requires: modulus.magnitude > 1
     /// - Complexity: O(count^3)
-    public func inverse(_ modulus: BigInt) -> BigInt? {
+    public func inverse(_ modulus: CS.BigInt) -> CS.BigInt? {
         guard let inv = self.magnitude.inverse(modulus.magnitude) else { return nil }
-        return BigInt(self.sign == .plus || inv.isZero ? inv : modulus.magnitude - inv)
+        return CS.BigInt(self.sign == .plus || inv.isZero ? inv : modulus.magnitude - inv)
     }
 }

+ 2 - 2
Sources/CryptoSwift/BigInt/Hashable.swift → Sources/CryptoSwift/CS.BigInt/Hashable.swift

@@ -6,7 +6,7 @@
 //  Copyright © 2016-2017 Károly Lőrentey.
 //
 
-extension BigUInt: Hashable {
+extension CS.BigUInt: Hashable {
     //MARK: Hashing
 
     /// Append this `BigUInt` to the specified hasher.
@@ -17,7 +17,7 @@ extension BigUInt: Hashable {
     }
 }
 
-extension BigInt: Hashable {
+extension CS.BigInt: Hashable {
     /// Append this `BigInt` to the specified hasher.
     public func hash(into hasher: inout Hasher) {
         hasher.combine(sign)

+ 8 - 8
Sources/CryptoSwift/BigInt/Integer Conversion.swift → Sources/CryptoSwift/CS.BigInt/Integer Conversion.swift

@@ -1,12 +1,12 @@
 //
 //  Integer Conversion.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2017-08-11.
 //  Copyright © 2016-2017 Károly Lőrentey.
 //
 
-extension BigUInt {
+extension CS.BigUInt {
     public init?<T: BinaryInteger>(exactly source: T) {
         guard source >= (0 as T) else { return nil }
         if source.bitWidth <= 2 * Word.bitWidth {
@@ -38,25 +38,25 @@ extension BigUInt {
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     public init() {
         self.init(sign: .plus, magnitude: 0)
     }
 
     /// Initializes a new signed big integer with the same value as the specified unsigned big integer.
-    public init(_ integer: BigUInt) {
+    public init(_ integer: CS.BigUInt) {
         self.magnitude = integer
         self.sign = .plus
     }
 
     public init<T>(_ source: T) where T : BinaryInteger {
         if source >= (0 as T) {
-            self.init(sign: .plus, magnitude: BigUInt(source))
+            self.init(sign: .plus, magnitude: CS.BigUInt(source))
         }
         else {
             var words = Array(source.words)
             words.twosComplement()
-            self.init(sign: .minus, magnitude: BigUInt(words: words))
+            self.init(sign: .minus, magnitude: CS.BigUInt(words: words))
         }
     }
 
@@ -73,14 +73,14 @@ extension BigInt {
     }
 }
 
-extension BigUInt: ExpressibleByIntegerLiteral {
+extension CS.BigUInt: ExpressibleByIntegerLiteral {
     /// Initialize a new big integer from an integer literal.
     public init(integerLiteral value: UInt64) {
         self.init(value)
     }
 }
 
-extension BigInt: ExpressibleByIntegerLiteral {
+extension CS.BigInt: ExpressibleByIntegerLiteral {
     /// Initialize a new big integer from an integer literal.
     public init(integerLiteral value: Int64) {
         self.init(value)

+ 15 - 15
Sources/CryptoSwift/BigInt/Multiplication.swift → Sources/CryptoSwift/CS.BigInt/Multiplication.swift

@@ -1,12 +1,12 @@
 //
 //  Multiplication.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2016-01-03.
 //  Copyright © 2016-2017 Károly Lőrentey.
 //
 
-extension BigUInt {
+extension CS.BigUInt {
 
     //MARK: Multiplication
 
@@ -30,7 +30,7 @@ extension BigUInt {
     /// Multiply this big integer by a single Word, and return the result.
     ///
     /// - Complexity: O(count)
-    public func multiplied(byWord y: Word) -> BigUInt {
+    public func multiplied(byWord y: Word) -> CS.BigUInt {
         var r = self
         r.multiply(byWord: y)
         return r
@@ -42,7 +42,7 @@ extension BigUInt {
     ///   individually. (The fused operation doesn't need to allocate space for temporary big integers.)
     /// - Returns: `self` is set to `self + (x * y) << (shift * 2^Word.bitWidth)`
     /// - Complexity: O(count)
-    public mutating func multiplyAndAdd(_ x: BigUInt, _ y: Word, shiftedBy shift: Int = 0) {
+    public mutating func multiplyAndAdd(_ x: CS.BigUInt, _ y: Word, shiftedBy shift: Int = 0) {
         precondition(shift >= 0)
         guard y != 0 && x.count > 0 else { return }
         guard y != 1 else { self.add(x, shiftedBy: shift); return }
@@ -75,7 +75,7 @@ extension BigUInt {
     /// - Note: This uses the naive O(n^2) multiplication algorithm unless both arguments have more than
     ///   `BigUInt.directMultiplicationLimit` words.
     /// - Complexity: O(n^log2(3))
-    public func multiplied(by y: BigUInt) -> BigUInt {
+    public func multiplied(by y: CS.BigUInt) -> CS.BigUInt {
         // This method is mostly defined for symmetry with the rest of the arithmetic operations.
         return self * y
     }
@@ -88,19 +88,19 @@ extension BigUInt {
     /// - Note: This uses the naive O(n^2) multiplication algorithm unless both arguments have more than
     ///   `BigUInt.directMultiplicationLimit` words.
     /// - Complexity: O(n^log2(3))
-    public static func *(x: BigUInt, y: BigUInt) -> BigUInt {
+    public static func *(x: CS.BigUInt, y: CS.BigUInt) -> CS.BigUInt {
         let xc = x.count
         let yc = y.count
-        if xc == 0 { return BigUInt() }
-        if yc == 0 { return BigUInt() }
+        if xc == 0 { return CS.BigUInt() }
+        if yc == 0 { return CS.BigUInt() }
         if yc == 1 { return x.multiplied(byWord: y[0]) }
         if xc == 1 { return y.multiplied(byWord: x[0]) }
 
-        if Swift.min(xc, yc) <= BigUInt.directMultiplicationLimit {
+        if Swift.min(xc, yc) <= CS.BigUInt.directMultiplicationLimit {
             // Long multiplication.
             let left = (xc < yc ? y : x)
             let right = (xc < yc ? x : y)
-            var result = BigUInt()
+            var result = CS.BigUInt()
             for i in (0 ..< right.count).reversed() {
                 result.multiplyAndAdd(left, right[i], shiftedBy: i)
             }
@@ -149,17 +149,17 @@ extension BigUInt {
     }
 
     /// Multiply `a` by `b` and store the result in `a`.
-    public static func *=(a: inout BigUInt, b: BigUInt) {
+    public static func *=(a: inout CS.BigUInt, b: CS.BigUInt) {
         a = a * b
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     /// Multiply `a` with `b` and return the result.
-    public static func *(a: BigInt, b: BigInt) -> BigInt {
-        return BigInt(sign: a.sign == b.sign ? .plus : .minus, magnitude: a.magnitude * b.magnitude)
+    public static func *(a: CS.BigInt, b: CS.BigInt) -> CS.BigInt {
+        return CS.BigInt(sign: a.sign == b.sign ? .plus : .minus, magnitude: a.magnitude * b.magnitude)
     }
 
     /// Multiply `a` with `b` in place.
-    public static func *=(a: inout BigInt, b: BigInt) { a = a * b }
+    public static func *=(a: inout CS.BigInt, b: CS.BigInt) { a = a * b }
 }

+ 11 - 11
Sources/CryptoSwift/BigInt/Prime Test.swift → Sources/CryptoSwift/CS.BigInt/Prime Test.swift

@@ -1,6 +1,6 @@
 //
 //  Prime Test.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2016-01-04.
 //  Copyright © 2016-2017 Károly Lőrentey.
@@ -9,13 +9,13 @@
 /// The first several [prime numbers][primes]. 
 ///
 /// [primes]: https://oeis.org/A000040
-let primes: [BigUInt.Word] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
+let primes: [CS.BigUInt.Word] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
 
 /// The ith element in this sequence is the smallest composite number that passes the strong probable prime test
 /// for all of the first (i+1) primes.
 ///
 /// This is sequence [A014233](http://oeis.org/A014233) on the [Online Encyclopaedia of Integer Sequences](http://oeis.org).
-let pseudoPrimes: [BigUInt] = [
+let pseudoPrimes: [CS.BigUInt] = [
     /*  2 */ 2_047,
     /*  3 */ 1_373_653,
     /*  5 */ 25_326_001,
@@ -31,15 +31,15 @@ let pseudoPrimes: [BigUInt] = [
     /* 41 */ "3317044064679887385961981",
 ]
 
-extension BigUInt {
+extension CS.BigUInt {
     //MARK: Primality Testing
 
     /// Returns true iff this integer passes the [strong probable prime test][sppt] for the specified base.
     ///
     /// [sppt]: https://en.wikipedia.org/wiki/Probable_prime
-    public func isStrongProbablePrime(_ base: BigUInt) -> Bool {
-        precondition(base > (1 as BigUInt))
-        precondition(self > (0 as BigUInt))
+    public func isStrongProbablePrime(_ base: CS.BigUInt) -> Bool {
+        precondition(base > (1 as CS.BigUInt))
+        precondition(self > (0 as CS.BigUInt))
         let dec = self - 1
 
         let r = dec.trailingZeroBitCount
@@ -97,7 +97,7 @@ extension BigUInt {
         /// Give an exact answer when we can.
         if self < pseudoPrimes.last! {
             for i in 0 ..< pseudoPrimes.count {
-                guard isStrongProbablePrime(BigUInt(primes[i])) else {
+                guard isStrongProbablePrime(CS.BigUInt(primes[i])) else {
                     break
                 }
                 if self < pseudoPrimes[i] {
@@ -110,7 +110,7 @@ extension BigUInt {
 
         /// Otherwise do as many rounds of random SPPT as required.
         for _ in 0 ..< rounds {
-            let random = BigUInt.randomInteger(lessThan: self - 2) + 2
+            let random = CS.BigUInt.randomInteger(lessThan: self - 2) + 2
             guard isStrongProbablePrime(random) else {
                 return false
             }
@@ -121,13 +121,13 @@ extension BigUInt {
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     //MARK: Primality Testing
 
     /// Returns true iff this integer passes the [strong probable prime test][sppt] for the specified base.
     ///
     /// [sppt]: https://en.wikipedia.org/wiki/Probable_prime
-    public func isStrongProbablePrime(_ base: BigInt) -> Bool {
+    public func isStrongProbablePrime(_ base: CS.BigInt) -> Bool {
         precondition(base.sign == .plus)
         if self.sign == .minus { return false }
         return self.magnitude.isStrongProbablePrime(base.magnitude)

+ 10 - 10
Sources/CryptoSwift/BigInt/Random.swift → Sources/CryptoSwift/CS.BigInt/Random.swift

@@ -1,19 +1,19 @@
 //
 //  Random.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2016-01-04.
 //  Copyright © 2016-2017 Károly Lőrentey.
 //
 
-extension BigUInt {
+extension CS.BigUInt {
     /// Create a big unsigned integer consisting of `width` uniformly distributed random bits.
     ///
     /// - Parameter width: The maximum number of one bits in the result.
     /// - Parameter generator: The source of randomness.
     /// - Returns: A big unsigned integer less than `1 << width`.
-    public static func randomInteger<RNG: RandomNumberGenerator>(withMaximumWidth width: Int, using generator: inout RNG) -> BigUInt {
-        var result = BigUInt.zero
+    public static func randomInteger<RNG: RandomNumberGenerator>(withMaximumWidth width: Int, using generator: inout RNG) -> CS.BigUInt {
+        var result = CS.BigUInt.zero
         var bitsLeft = width
         var i = 0
         let wordsNeeded = (width + Word.bitWidth - 1) / Word.bitWidth
@@ -38,7 +38,7 @@ extension BigUInt {
     ///
     /// - Parameter width: The maximum number of one bits in the result.
     /// - Returns: A big unsigned integer less than `1 << width`.
-    public static func randomInteger(withMaximumWidth width: Int) -> BigUInt {
+    public static func randomInteger(withMaximumWidth width: Int) -> CS.BigUInt {
         var rng = SystemRandomNumberGenerator()
         return randomInteger(withMaximumWidth: width, using: &rng)
     }
@@ -50,10 +50,10 @@ extension BigUInt {
     /// - Parameter width: The number of bits required to represent the answer.
     /// - Parameter generator: The source of randomness.
     /// - Returns: A random big unsigned integer whose width is `width`.
-    public static func randomInteger<RNG: RandomNumberGenerator>(withExactWidth width: Int, using generator: inout RNG) -> BigUInt {
+    public static func randomInteger<RNG: RandomNumberGenerator>(withExactWidth width: Int, using generator: inout RNG) -> CS.BigUInt {
         // width == 0 -> return 0 because there is no room for a one bit.
         // width == 1 -> return 1 because there is no room for any random bits.
-        guard width > 1 else { return BigUInt(width) }
+        guard width > 1 else { return CS.BigUInt(width) }
         var result = randomInteger(withMaximumWidth: width - 1, using: &generator)
         result[(width - 1) / Word.bitWidth] |= 1 << Word((width - 1) % Word.bitWidth)
         return result
@@ -65,7 +65,7 @@ extension BigUInt {
     /// - Note: I use a `SystemRandomGeneratorGenerator` as the source of randomness.
     ///
     /// - Returns: A random big unsigned integer whose width is `width`.
-    public static func randomInteger(withExactWidth width: Int) -> BigUInt {
+    public static func randomInteger(withExactWidth width: Int) -> CS.BigUInt {
         var rng = SystemRandomNumberGenerator()
         return randomInteger(withExactWidth: width, using: &rng)
     }
@@ -77,7 +77,7 @@ extension BigUInt {
     /// - Parameter limit: The upper bound on the result.
     /// - Parameter generator: The source of randomness.
     /// - Returns: A random big unsigned integer that is less than `limit`.
-    public static func randomInteger<RNG: RandomNumberGenerator>(lessThan limit: BigUInt, using generator: inout RNG) -> BigUInt {
+    public static func randomInteger<RNG: RandomNumberGenerator>(lessThan limit: CS.BigUInt, using generator: inout RNG) -> CS.BigUInt {
         precondition(limit > 0, "\(#function): 0 is not a valid limit")
         let width = limit.bitWidth
         var random = randomInteger(withMaximumWidth: width, using: &generator)
@@ -94,7 +94,7 @@ extension BigUInt {
     ///
     /// - Parameter limit: The upper bound on the result.
     /// - Returns: A random big unsigned integer that is less than `limit`.
-    public static func randomInteger(lessThan limit: BigUInt) -> BigUInt {
+    public static func randomInteger(lessThan limit: CS.BigUInt) -> CS.BigUInt {
         var rng = SystemRandomNumberGenerator()
         return randomInteger(lessThan: limit, using: &rng)
     }

+ 23 - 23
Sources/CryptoSwift/BigInt/Shifts.swift → Sources/CryptoSwift/CS.BigInt/Shifts.swift

@@ -1,23 +1,23 @@
 //
 //  Shifts.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2016-01-03.
 //  Copyright © 2016-2017 Károly Lőrentey.
 //
 
-extension BigUInt {
+extension CS.BigUInt {
 
     //MARK: Shift Operators
     
-    internal func shiftedLeft(by amount: Word) -> BigUInt {
+    internal func shiftedLeft(by amount: Word) -> CS.BigUInt {
         guard amount > 0 else { return self }
         
         let ext = Int(amount / Word(Word.bitWidth)) // External shift amount (new words)
         let up = Word(amount % Word(Word.bitWidth)) // Internal shift amount (subword shift)
         let down = Word(Word.bitWidth) - up
         
-        var result = BigUInt()
+        var result = CS.BigUInt()
         if up > 0 {
             var i = 0
             var lowbits: Word = 0
@@ -58,7 +58,7 @@ extension BigUInt {
         }
     }
     
-    internal func shiftedRight(by amount: Word) -> BigUInt {
+    internal func shiftedRight(by amount: Word) -> CS.BigUInt {
         guard amount > 0 else { return self }
         guard amount < self.bitWidth else { return 0 }
         
@@ -66,7 +66,7 @@ extension BigUInt {
         let down = Word(amount % Word(Word.bitWidth)) // Internal shift amount (subword shift)
         let up = Word(Word.bitWidth) - down
         
-        var result = BigUInt()
+        var result = CS.BigUInt()
         if down > 0 {
             var highbits: Word = 0
             for i in (ext ..< self.count).reversed() {
@@ -106,7 +106,7 @@ extension BigUInt {
         }
     }
     
-    public static func >>=<Other: BinaryInteger>(lhs: inout BigUInt, rhs: Other) {
+    public static func >>=<Other: BinaryInteger>(lhs: inout CS.BigUInt, rhs: Other) {
         if rhs < (0 as Other) {
             lhs <<= (0 - rhs)
         }
@@ -118,7 +118,7 @@ extension BigUInt {
         }
     }
     
-    public static func <<=<Other: BinaryInteger>(lhs: inout BigUInt, rhs: Other) {
+    public static func <<=<Other: BinaryInteger>(lhs: inout CS.BigUInt, rhs: Other) {
         if rhs < (0 as Other) {
             lhs >>= (0 - rhs)
             return
@@ -126,7 +126,7 @@ extension BigUInt {
         lhs.shiftLeft(by: Word(exactly: rhs)!)
     }
 
-    public static func >><Other: BinaryInteger>(lhs: BigUInt, rhs: Other) -> BigUInt {
+    public static func >><Other: BinaryInteger>(lhs: CS.BigUInt, rhs: Other) -> CS.BigUInt {
         if rhs < (0 as Other) {
             return lhs << (0 - rhs)
         }
@@ -136,7 +136,7 @@ extension BigUInt {
         return lhs.shiftedRight(by: UInt(rhs))
     }
 
-    public static func <<<Other: BinaryInteger>(lhs: BigUInt, rhs: Other) -> BigUInt {
+    public static func <<<Other: BinaryInteger>(lhs: CS.BigUInt, rhs: Other) -> CS.BigUInt {
         if rhs < (0 as Other) {
             return lhs >> (0 - rhs)
         }
@@ -144,18 +144,18 @@ extension BigUInt {
     }
 }
 
-extension BigInt {
-    func shiftedLeft(by amount: Word) -> BigInt {
-        return BigInt(sign: self.sign, magnitude: self.magnitude.shiftedLeft(by: amount))
+extension CS.BigInt {
+    func shiftedLeft(by amount: Word) -> CS.BigInt {
+        return CS.BigInt(sign: self.sign, magnitude: self.magnitude.shiftedLeft(by: amount))
     }
     
     mutating func shiftLeft(by amount: Word) {
         self.magnitude.shiftLeft(by: amount)
     }
     
-    func shiftedRight(by amount: Word) -> BigInt {
+    func shiftedRight(by amount: Word) -> CS.BigInt {
         let m = self.magnitude.shiftedRight(by: amount)
-        return BigInt(sign: self.sign, magnitude: self.sign == .minus && m.isZero ? 1 : m)
+        return CS.BigInt(sign: self.sign, magnitude: self.sign == .minus && m.isZero ? 1 : m)
     }
     
     mutating func shiftRight(by amount: Word) {
@@ -165,28 +165,28 @@ extension BigInt {
         }
     }
     
-    public static func &<<(left: BigInt, right: BigInt) -> BigInt {
+    public static func &<<(left: CS.BigInt, right: CS.BigInt) -> CS.BigInt {
         return left.shiftedLeft(by: right.words[0])
     }
     
-    public static func &<<=(left: inout BigInt, right: BigInt) {
+    public static func &<<=(left: inout CS.BigInt, right: CS.BigInt) {
         left.shiftLeft(by: right.words[0])
     }
     
-    public static func &>>(left: BigInt, right: BigInt) -> BigInt {
+    public static func &>>(left: CS.BigInt, right: CS.BigInt) -> CS.BigInt {
         return left.shiftedRight(by: right.words[0])
     }
     
-    public static func &>>=(left: inout BigInt, right: BigInt) {
+    public static func &>>=(left: inout CS.BigInt, right: CS.BigInt) {
         left.shiftRight(by: right.words[0])
     }
     
-    public static func <<<Other: BinaryInteger>(lhs: BigInt, rhs: Other) -> BigInt {
+    public static func <<<Other: BinaryInteger>(lhs: CS.BigInt, rhs: Other) -> CS.BigInt {
         guard rhs >= (0 as Other) else { return lhs >> (0 - rhs) }
         return lhs.shiftedLeft(by: Word(rhs))
     }
     
-    public static func <<=<Other: BinaryInteger>(lhs: inout BigInt, rhs: Other) {
+    public static func <<=<Other: BinaryInteger>(lhs: inout CS.BigInt, rhs: Other) {
         if rhs < (0 as Other) {
             lhs >>= (0 - rhs)
         }
@@ -195,12 +195,12 @@ extension BigInt {
         }
     }
     
-    public static func >><Other: BinaryInteger>(lhs: BigInt, rhs: Other) -> BigInt {
+    public static func >><Other: BinaryInteger>(lhs: CS.BigInt, rhs: Other) -> CS.BigInt {
         guard rhs >= (0 as Other) else { return lhs << (0 - rhs) }
         return lhs.shiftedRight(by: Word(rhs))
     }
     
-    public static func >>=<Other: BinaryInteger>(lhs: inout BigInt, rhs: Other) {
+    public static func >>=<Other: BinaryInteger>(lhs: inout CS.BigInt, rhs: Other) {
         if rhs < (0 as Other) {
             lhs <<= (0 - rhs)
         }

+ 9 - 9
Sources/CryptoSwift/BigInt/Square Root.swift → Sources/CryptoSwift/CS.BigInt/Square Root.swift

@@ -1,6 +1,6 @@
 //
 //  Square Root.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2016-01-03.
 //  Copyright © 2016-2017 Károly Lőrentey.
@@ -8,15 +8,15 @@
 
 //MARK: Square Root
 
-extension BigUInt {
+extension CS.BigUInt {
     /// Returns the integer square root of a big integer; i.e., the largest integer whose square isn't greater than `value`.
     ///
     /// - Returns: floor(sqrt(self))
-    public func squareRoot() -> BigUInt {
+    public func squareRoot() -> CS.BigUInt {
         // This implementation uses Newton's method.
-        guard !self.isZero else { return BigUInt() }
-        var x = BigUInt(1) << ((self.bitWidth + 1) / 2)
-        var y: BigUInt = 0
+        guard !self.isZero else { return CS.BigUInt() }
+        var x = CS.BigUInt(1) << ((self.bitWidth + 1) / 2)
+        var y: CS.BigUInt = 0
         while true {
             y.load(self)
             y /= x
@@ -29,13 +29,13 @@ extension BigUInt {
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     /// Returns the integer square root of a big integer; i.e., the largest integer whose square isn't greater than `value`.
     ///
     /// - Requires: self >= 0
     /// - Returns: floor(sqrt(self))
-    public func squareRoot() -> BigInt {
+    public func squareRoot() -> CS.BigInt {
         precondition(self.sign == .plus)
-        return BigInt(sign: .plus, magnitude: self.magnitude.squareRoot())
+        return CS.BigInt(sign: .plus, magnitude: self.magnitude.squareRoot())
     }
 }

+ 10 - 10
Sources/CryptoSwift/BigInt/Strideable.swift → Sources/CryptoSwift/CS.BigInt/Strideable.swift

@@ -1,36 +1,36 @@
 //
 //  Strideable.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2017-08-11.
 //  Copyright © 2016-2017 Károly Lőrentey.
 //
 
-extension BigUInt: Strideable {
+extension CS.BigUInt: Strideable {
     /// A type that can represent the distance between two values ofa `BigUInt`.
-    public typealias Stride = BigInt
+    public typealias Stride = CS.BigInt
 
     /// Adds `n` to `self` and returns the result. Traps if the result would be less than zero.
-    public func advanced(by n: BigInt) -> BigUInt {
+    public func advanced(by n: CS.BigInt) -> CS.BigUInt {
         return n.sign == .minus ? self - n.magnitude : self + n.magnitude
     }
 
     /// Returns the (potentially negative) difference between `self` and `other` as a `BigInt`. Never traps.
-    public func distance(to other: BigUInt) -> BigInt {
-        return BigInt(other) - BigInt(self)
+    public func distance(to other: CS.BigUInt) -> CS.BigInt {
+        return CS.BigInt(other) - CS.BigInt(self)
     }
 }
 
-extension BigInt: Strideable {
-    public typealias Stride = BigInt
+extension CS.BigInt: Strideable {
+    public typealias Stride = CS.BigInt
 
     /// Returns `self + n`.
-    public func advanced(by n: Stride) -> BigInt {
+    public func advanced(by n: Stride) -> CS.BigInt {
         return self + n
     }
 
     /// Returns `other - self`.
-    public func distance(to other: BigInt) -> Stride {
+    public func distance(to other: CS.BigInt) -> Stride {
         return other - self
     }
 }

+ 24 - 24
Sources/CryptoSwift/BigInt/String Conversion.swift → Sources/CryptoSwift/CS.BigInt/String Conversion.swift

@@ -1,12 +1,12 @@
 //
 //  String Conversion.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2016-01-03.
 //  Copyright © 2016-2017 Károly Lőrentey.
 //
 
-extension BigUInt {
+extension CS.BigUInt {
 
     //MARK: String Conversion
 
@@ -38,7 +38,7 @@ extension BigUInt {
     /// - Returns: The integer represented by `text`, or nil if `text` contains a character that does not represent a numeral in `radix`.
     public init?<S: StringProtocol>(_ text: S, radix: Int = 10) {
         precondition(radix > 1)
-        let (charsPerWord, power) = BigUInt.charsPerWord(forRadix: radix)
+        let (charsPerWord, power) = CS.BigUInt.charsPerWord(forRadix: radix)
 
         var words: [Word] = []
         var end = text.endIndex
@@ -72,7 +72,7 @@ extension BigUInt {
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     /// Initialize a big integer from an ASCII representation in a given radix. Numerals above `9` are represented by
     /// letters from the English alphabet.
     ///
@@ -81,19 +81,19 @@ extension BigInt {
     /// - Parameter `radix`: The base of the number system to use, or 10 if unspecified.
     /// - Returns: The integer represented by `text`, or nil if `text` contains a character that does not represent a numeral in `radix`.
     public init?<S: StringProtocol>(_ text: S, radix: Int = 10) {
-        var magnitude: BigUInt?
+        var magnitude: CS.BigUInt?
         var sign: Sign = .plus
         if text.first == "-" {
             sign = .minus
             let text = text.dropFirst()
-            magnitude = BigUInt(text, radix: radix)
+            magnitude = CS.BigUInt(text, radix: radix)
         }
         else if text.first == "+" {
             let text = text.dropFirst()
-            magnitude = BigUInt(text, radix: radix)
+            magnitude = CS.BigUInt(text, radix: radix)
         }
         else {
-            magnitude = BigUInt(text, radix: radix)
+            magnitude = CS.BigUInt(text, radix: radix)
         }
         guard let m = magnitude else { return nil }
         self.magnitude = m
@@ -105,7 +105,7 @@ extension String {
     /// Initialize a new string with the base-10 representation of an unsigned big integer.
     ///
     /// - Complexity: O(v.count^2)
-    public init(_ v: BigUInt) { self.init(v, radix: 10, uppercase: false) }
+    public init(_ v: CS.BigUInt) { self.init(v, radix: 10, uppercase: false) }
 
     /// Initialize a new string representing an unsigned big integer in the given radix (base).
     ///
@@ -114,9 +114,9 @@ extension String {
     ///
     /// - Requires: radix > 1 && radix <= 36
     /// - Complexity: O(count) when radix is a power of two; otherwise O(count^2).
-    public init(_ v: BigUInt, radix: Int, uppercase: Bool = false) {
+    public init(_ v: CS.BigUInt, radix: Int, uppercase: Bool = false) {
         precondition(radix > 1)
-        let (charsPerWord, power) = BigUInt.charsPerWord(forRadix: radix)
+        let (charsPerWord, power) = CS.BigUInt.charsPerWord(forRadix: radix)
 
         guard !v.isZero else { self = "0"; return }
 
@@ -155,7 +155,7 @@ extension String {
     ///
     /// - Requires: radix > 1 && radix <= 36
     /// - Complexity: O(count) when radix is a power of two; otherwise O(count^2).
-    public init(_ value: BigInt, radix: Int = 10, uppercase: Bool = false) {
+    public init(_ value: CS.BigInt, radix: Int = 10, uppercase: Bool = false) {
         self = String(value.magnitude, radix: radix, uppercase: uppercase)
         if value.sign == .minus {
             self = "-" + self
@@ -163,61 +163,61 @@ extension String {
     }
 }
 
-extension BigUInt: ExpressibleByStringLiteral {
+extension CS.BigUInt: ExpressibleByStringLiteral {
     /// Initialize a new big integer from a Unicode scalar.
     /// The scalar must represent a decimal digit.
     public init(unicodeScalarLiteral value: UnicodeScalar) {
-        self = BigUInt(String(value), radix: 10)!
+        self = CS.BigUInt(String(value), radix: 10)!
     }
 
     /// Initialize a new big integer from an extended grapheme cluster.
     /// The cluster must consist of a decimal digit.
     public init(extendedGraphemeClusterLiteral value: String) {
-        self = BigUInt(value, radix: 10)!
+        self = CS.BigUInt(value, radix: 10)!
     }
 
     /// Initialize a new big integer from a decimal number represented by a string literal of arbitrary length.
     /// The string must contain only decimal digits.
     public init(stringLiteral value: StringLiteralType) {
-        self = BigUInt(value, radix: 10)!
+        self = CS.BigUInt(value, radix: 10)!
     }
 }
 
-extension BigInt: ExpressibleByStringLiteral {
+extension CS.BigInt: ExpressibleByStringLiteral {
     /// Initialize a new big integer from a Unicode scalar.
     /// The scalar must represent a decimal digit.
     public init(unicodeScalarLiteral value: UnicodeScalar) {
-        self = BigInt(String(value), radix: 10)!
+        self = CS.BigInt(String(value), radix: 10)!
     }
 
     /// Initialize a new big integer from an extended grapheme cluster.
     /// The cluster must consist of a decimal digit.
     public init(extendedGraphemeClusterLiteral value: String) {
-        self = BigInt(value, radix: 10)!
+        self = CS.BigInt(value, radix: 10)!
     }
 
     /// Initialize a new big integer from a decimal number represented by a string literal of arbitrary length.
     /// The string must contain only decimal digits.
     public init(stringLiteral value: StringLiteralType) {
-        self = BigInt(value, radix: 10)!
+        self = CS.BigInt(value, radix: 10)!
     }
 }
 
-extension BigUInt: CustomStringConvertible {
+extension CS.BigUInt: CustomStringConvertible {
     /// Return the decimal representation of this integer.
     public var description: String {
         return String(self, radix: 10)
     }
 }
 
-extension BigInt: CustomStringConvertible {
+extension CS.BigInt: CustomStringConvertible {
     /// Return the decimal representation of this integer.
     public var description: String {
         return String(self, radix: 10)
     }
 }
 
-extension BigUInt: CustomPlaygroundDisplayConvertible {
+extension CS.BigUInt: CustomPlaygroundDisplayConvertible {
 
     /// Return the playground quick look representation of this integer.
     public var playgroundDescription: Any {
@@ -226,7 +226,7 @@ extension BigUInt: CustomPlaygroundDisplayConvertible {
     }
 }
 
-extension BigInt: CustomPlaygroundDisplayConvertible {
+extension CS.BigInt: CustomPlaygroundDisplayConvertible {
 
     /// Return the playground quick look representation of this integer.
     public var playgroundDescription: Any {

+ 14 - 14
Sources/CryptoSwift/BigInt/Subtraction.swift → Sources/CryptoSwift/CS.BigInt/Subtraction.swift

@@ -1,12 +1,12 @@
 //
 //  Subtraction.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2016-01-03.
 //  Copyright © 2016-2017 Károly Lőrentey.
 //
 
-extension BigUInt {
+extension CS.BigUInt {
     //MARK: Subtraction
 
     /// Subtract `word` from this integer in place, returning a flag indicating if the operation
@@ -33,7 +33,7 @@ extension BigUInt {
     ///
     /// - Note: If `overflow` is true, then the returned value is the two's complement of the absolute difference.
     /// - Complexity: O(count)
-    internal func subtractingWordReportingOverflow(_ word: Word, shiftedBy shift: Int = 0) -> (partialValue: BigUInt, overflow: Bool) {
+    internal func subtractingWordReportingOverflow(_ word: Word, shiftedBy shift: Int = 0) -> (partialValue: CS.BigUInt, overflow: Bool) {
         var result = self
         let overflow = result.subtractWordReportingOverflow(word, shiftedBy: shift)
         return (result, overflow)
@@ -54,7 +54,7 @@ extension BigUInt {
     ///
     /// - Requires: self >= d * 2^shift
     /// - Complexity: O(count)
-    internal func subtractingWord(_ word: Word, shiftedBy shift: Int = 0) -> BigUInt {
+    internal func subtractingWord(_ word: Word, shiftedBy shift: Int = 0) -> CS.BigUInt {
         var result = self
         result.subtractWord(word, shiftedBy: shift)
         return result
@@ -65,7 +65,7 @@ extension BigUInt {
     ///
     /// - Note: If the result indicates an overflow, then `self` becomes the twos' complement of the absolute difference.
     /// - Complexity: O(count)
-    public mutating func subtractReportingOverflow(_ b: BigUInt, shiftedBy shift: Int = 0) -> Bool {
+    public mutating func subtractReportingOverflow(_ b: CS.BigUInt, shiftedBy shift: Int = 0) -> Bool {
         precondition(shift >= 0)
         var carry = false
         var bi = 0
@@ -93,7 +93,7 @@ extension BigUInt {
     ///
     /// - Note: If `overflow` is true, then the result value is the twos' complement of the absolute value of the difference.
     /// - Complexity: O(count)
-    public func subtractingReportingOverflow(_ other: BigUInt, shiftedBy shift: Int) -> (partialValue: BigUInt, overflow: Bool) {
+    public func subtractingReportingOverflow(_ other: CS.BigUInt, shiftedBy shift: Int) -> (partialValue: CS.BigUInt, overflow: Bool) {
         var result = self
         let overflow = result.subtractReportingOverflow(other, shiftedBy: shift)
         return (result, overflow)
@@ -103,7 +103,7 @@ extension BigUInt {
     ///
     /// - Note: When the operation overflows, then `partialValue` is the twos' complement of the absolute value of the difference.
     /// - Complexity: O(count)
-    public func subtractingReportingOverflow(_ other: BigUInt) -> (partialValue: BigUInt, overflow: Bool) {
+    public func subtractingReportingOverflow(_ other: CS.BigUInt) -> (partialValue: CS.BigUInt, overflow: Bool) {
         return self.subtractingReportingOverflow(other, shiftedBy: 0)
     }
     
@@ -112,7 +112,7 @@ extension BigUInt {
     ///
     /// - Requires: self >= other * 2^shift
     /// - Complexity: O(count)
-    public mutating func subtract(_ other: BigUInt, shiftedBy shift: Int = 0) {
+    public mutating func subtract(_ other: CS.BigUInt, shiftedBy shift: Int = 0) {
         let overflow = subtractReportingOverflow(other, shiftedBy: shift)
         precondition(!overflow)
     }
@@ -122,7 +122,7 @@ extension BigUInt {
     ///
     /// - Requires: self >= b * 2^shift
     /// - Complexity: O(count)
-    public func subtracting(_ other: BigUInt, shiftedBy shift: Int = 0) -> BigUInt {
+    public func subtracting(_ other: CS.BigUInt, shiftedBy shift: Int = 0) -> CS.BigUInt {
         var result = self
         result.subtract(other, shiftedBy: shift)
         return result
@@ -140,7 +140,7 @@ extension BigUInt {
     ///
     /// - Requires: a >= b
     /// - Complexity: O(a.count)
-    public static func -(a: BigUInt, b: BigUInt) -> BigUInt {
+    public static func -(a: CS.BigUInt, b: CS.BigUInt) -> CS.BigUInt {
         return a.subtracting(b)
     }
 
@@ -148,22 +148,22 @@ extension BigUInt {
     ///
     /// - Requires: a >= b
     /// - Complexity: O(a.count)
-    public static func -=(a: inout BigUInt, b: BigUInt) {
+    public static func -=(a: inout CS.BigUInt, b: CS.BigUInt) {
         a.subtract(b)
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     public mutating func negate() {
         guard !magnitude.isZero else { return }
         self.sign = self.sign == .plus ? .minus : .plus
     }
 
     /// Subtract `b` from `a` and return the result.
-    public static func -(a: BigInt, b: BigInt) -> BigInt {
+    public static func -(a: CS.BigInt, b: CS.BigInt) -> CS.BigInt {
         return a + -b
     }
 
     /// Subtract `b` from `a` in place.
-    public static func -=(a: inout BigInt, b: BigInt) { a = a - b }
+    public static func -=(a: inout CS.BigInt, b: CS.BigInt) { a = a - b }
 }

+ 12 - 12
Sources/CryptoSwift/BigInt/Words and Bits.swift → Sources/CryptoSwift/CS.BigInt/Words and Bits.swift

@@ -1,6 +1,6 @@
 //
 //  Words and Bits.swift
-//  BigInt
+//  CS.BigInt
 //
 //  Created by Károly Lőrentey on 2017-08-11.
 //  Copyright © 2016-2017 Károly Lőrentey.
@@ -20,7 +20,7 @@ extension Array where Element == UInt {
     }
 }
 
-extension BigUInt {
+extension CS.BigUInt {
     public subscript(bitAt index: Int) -> Bool {
         get {
             precondition(index >= 0)
@@ -40,7 +40,7 @@ extension BigUInt {
     }
 }
 
-extension BigUInt {
+extension CS.BigUInt {
     /// The minimum number of bits required to represent this integer in binary.
     ///
     /// - Returns: floor(log2(2 * self + 1))
@@ -74,7 +74,7 @@ extension BigUInt {
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     public var bitWidth: Int {
         guard !magnitude.isZero else { return 0 }
         return magnitude.bitWidth + 1
@@ -86,11 +86,11 @@ extension BigInt {
     }
 }
 
-extension BigUInt {
+extension CS.BigUInt {
     public struct Words: RandomAccessCollection {
-        private let value: BigUInt
+        private let value: CS.BigUInt
 
-        fileprivate init(_ value: BigUInt) { self.value = value }
+        fileprivate init(_ value: CS.BigUInt) { self.value = value }
 
         public var startIndex: Int { return 0 }
         public var endIndex: Int { return value.count }
@@ -135,14 +135,14 @@ extension BigUInt {
     }
 }
 
-extension BigInt {
+extension CS.BigInt {
     public struct Words: RandomAccessCollection {
         public typealias Indices = CountableRange<Int>
 
-        private let value: BigInt
+        private let value: CS.BigInt
         private let decrementLimit: Int
 
-        fileprivate init(_ value: BigInt) {
+        fileprivate init(_ value: CS.BigInt) {
             self.value = value
             switch value.sign {
             case .plus:
@@ -192,11 +192,11 @@ extension BigInt {
     public init<S: Sequence>(words: S) where S.Element == Word {
         var words = Array(words)
         if (words.last ?? 0) >> (Word.bitWidth - 1) == 0 {
-            self.init(sign: .plus, magnitude: BigUInt(words: words))
+            self.init(sign: .plus, magnitude: CS.BigUInt(words: words))
         }
         else {
             words.twosComplement()
-            self.init(sign: .minus, magnitude: BigUInt(words: words))
+            self.init(sign: .minus, magnitude: CS.BigUInt(words: words))
         }
     }
 }

+ 16 - 16
Sources/CryptoSwift/RSA.swift

@@ -28,13 +28,13 @@ public final class RSA {
   }
   
   /// RSA Modulus
-  public let n: BigUInt
+  public let n: CS.BigUInt
   
   /// RSA Public Exponent
-  public let e: BigUInt
+  public let e: CS.BigUInt
   
   /// RSA Private Exponent
-  public let d: BigUInt?
+  public let d: CS.BigUInt?
   
   /// The size of the modulus, in bits
   public let keySize: Int
@@ -44,7 +44,7 @@ public final class RSA {
   ///   - n: The RSA Modulus
   ///   - e: The RSA Public Exponent
   ///   - d: The RSA Private Exponent (or nil if unknown, e.g. if only public key is known)
-  public init(n: BigUInt, e: BigUInt, d: BigUInt? = nil) {
+  public init(n: CS.BigUInt, e: CS.BigUInt, d: CS.BigUInt? = nil) {
     self.n = n
     self.e = e
     self.d = d
@@ -59,9 +59,9 @@ public final class RSA {
   ///   - d: The RSA Private Exponent (or nil if unknown, e.g. if only public key is known)
   public convenience init(n: Array<UInt8>, e: Array<UInt8>, d: Array<UInt8>? = nil) {
     if let d = d {
-      self.init(n: BigUInt(Data(n)), e: BigUInt(Data(e)), d: BigUInt(Data(d)))
+      self.init(n: CS.BigUInt(Data(n)), e: CS.BigUInt(Data(e)), d: CS.BigUInt(Data(d)))
     } else {
-      self.init(n: BigUInt(Data(n)), e: BigUInt(Data(e)))
+      self.init(n: CS.BigUInt(Data(n)), e: CS.BigUInt(Data(e)))
     }
   }
   
@@ -69,14 +69,14 @@ public final class RSA {
   /// - Parameter keySize: The size of the modulus
   public convenience init(keySize: Int) {
     // Generate prime numbers
-    let p = BigUInt.generatePrime(keySize / 2)
-    let q = BigUInt.generatePrime(keySize / 2)
+    let p = CS.BigUInt.generatePrime(keySize / 2)
+    let q = CS.BigUInt.generatePrime(keySize / 2)
     
     // Calculate modulus
     let n = p * q
     
     // Calculate public and private exponent
-    let e: BigUInt = 65537
+    let e: CS.BigUInt = 65537
     let phi = (p - 1) * (q - 1)
     let d = e.inverse(phi)
     
@@ -97,7 +97,7 @@ extension RSA: Cipher {
   @inlinable
   public func encrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8> {
     // Calculate encrypted data
-    return BigUInt(Data(bytes)).power(e, modulus: n).serialize().bytes
+    return CS.BigUInt(Data(bytes)).power(e, modulus: n).serialize().bytes
   }
 
   @inlinable
@@ -108,20 +108,20 @@ extension RSA: Cipher {
     }
     
     // Calculate decrypted data
-    return BigUInt(Data(bytes)).power(d, modulus: n).serialize().bytes
+    return CS.BigUInt(Data(bytes)).power(d, modulus: n).serialize().bytes
   }
   
 }
 
-// MARK: BigUInt extension
+// MARK: CS.BigUInt extension
 
-extension BigUInt {
+extension CS.BigUInt {
   
-  public static func generatePrime(_ width: Int) -> BigUInt {
+  public static func generatePrime(_ width: Int) -> CS.BigUInt {
     // Note: Need to find a better way to generate prime numbers
     while true {
-      var random = BigUInt.randomInteger(withExactWidth: width)
-      random |= BigUInt(1)
+      var random = CS.BigUInt.randomInteger(withExactWidth: width)
+      random |= CS.BigUInt(1)
       if random.isPrime() {
         return random
       }