浏览代码

Merge branch 'main'

Brandon Toms 3 年之前
父节点
当前提交
2cf072c50f
共有 9 个文件被更改,包括 104 次插入57 次删除
  1. 1 0
      .gitignore
  2. 2 1
      .mailmap
  3. 4 0
      .spi.yml
  4. 2 0
      CONTRIBUTORS.txt
  5. 7 0
      Package.swift
  6. 1 1
      README.md
  7. 15 7
      Sources/CryptoSwift/Blowfish.swift
  8. 46 25
      Sources/CryptoSwift/RSA.swift
  9. 26 23
      Tests/CryptoSwiftTests/RSATests.swift

+ 1 - 0
.gitignore

@@ -16,6 +16,7 @@ DerivedData
 *.xcuserstate
 timeline.xctimeline
 .swiftpm/xcode
+Package.resolved
 CryptoSwift.xcframework
 
 /Framework

+ 2 - 1
.mailmap

@@ -2,4 +2,5 @@ Marcin Krzyzanowski <marcin.krzyzanowski@gmail.com> <758033+krzyzanowskim@users.
 Marcin Krzyzanowski <marcin.krzyzanowski@gmail.com> <krzyzanowskim@users.noreply.github.com>
 Marcin Krzyzanowski <marcin.krzyzanowski@gmail.com> <marcin@krzyzanowskim.com>
 Marcin Krzyzanowski <marcin.krzyzanowski@gmail.com> <marcin.krzyzanowski@gmail.com>
-Luis Reisewitz <reisewitz@me.com> <zweigraf@users.noreply.github.com>
+Luis Reisewitz <reisewitz@me.com> <zweigraf@users.noreply.github.com>
+Nathan Fallet <contact@nathanfallet.me> <nathan.fallet@gmail.com>

+ 4 - 0
.spi.yml

@@ -0,0 +1,4 @@
+version: 1
+builder:
+  configs:
+    - documentation_targets: [CryptoSwift]

+ 2 - 0
CONTRIBUTORS.txt

@@ -18,6 +18,7 @@ organizations who have contributed source code to CryptoSwift.
 - Bart Cone <cone.bart@gmail.com>
 - Bing Cheung <32565605+eungch@users.noreply.github.com>
 - Bogdan Bystritskiy <q80061@gmail.com>
+- Brandon Toms <btoms.20@gmail.com>
 - Brice Cesarin <bc@dejamobile.com>
 - Bruce Geerdes <bruce@vdub.software>
 - Bryan Chen <xlchen1291@gmail.com>
@@ -32,6 +33,7 @@ organizations who have contributed source code to CryptoSwift.
 - Dave Wood <dave@cerebralgardens.com>
 - Dima Kalachov <dima.kalachov@gmail.com>
 - Dusan Klinec <dusan.klinec@gmail.com>
+- Elaine Lyons <e.lyons@fetchrewards.com>
 - Eneko Alonso <eneko.alonso@gmail.com>
 - Eugene Berdnikov <eberdnikov@outlook.com>
 - Evan Maloney <emaloney@gilt.com>

+ 7 - 0
Package.swift

@@ -20,3 +20,10 @@ let package = Package(
   ],
   swiftLanguageVersions: [.v5]
 )
+
+#if swift(>=5.6)
+  // Add the documentation compiler plugin if possible
+  package.dependencies.append(
+    .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0")
+  )
+#endif

+ 1 - 1
README.md

@@ -546,7 +546,7 @@ do {
 RSA key generation
 
 ```swift
-let rsa = RSA(keySize: 2048) // This generates a modulus, public exponent and private exponent with the given size
+let rsa = try RSA(keySize: 2048) // This generates a modulus, public exponent and private exponent with the given size
 ```
 
 ## Author

+ 15 - 7
Sources/CryptoSwift/Blowfish.swift

@@ -329,12 +329,20 @@ public final class Blowfish {
   }
 
   private func setupBlockModeWorkers() throws {
-    self.encryptWorker = try self.blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: self.encrypt, encryptionOperation: self.encrypt)
+    let decryptBlock = { [weak self] (block: ArraySlice<UInt8>) -> Array<UInt8>? in
+      self?.decrypt(block: block)
+    }
+
+    let encryptBlock = { [weak self] (block: ArraySlice<UInt8>) -> Array<UInt8>? in
+      self?.encrypt(block: block)
+    }
+
+    self.encryptWorker = try self.blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: encryptBlock, encryptionOperation: encryptBlock)
 
     if self.blockMode.options.contains(.useEncryptToDecrypt) {
-      self.decryptWorker = try self.blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: self.encrypt, encryptionOperation: self.encrypt)
+      self.decryptWorker = try self.blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: encryptBlock, encryptionOperation: encryptBlock)
     } else {
-      self.decryptWorker = try self.blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: self.decrypt, encryptionOperation: self.encrypt)
+      self.decryptWorker = try self.blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: decryptBlock, encryptionOperation: encryptBlock)
     }
   }
 
@@ -376,13 +384,13 @@ public final class Blowfish {
     }
   }
 
-  fileprivate func encrypt(block: ArraySlice<UInt8>) -> Array<UInt8>? {
+  private func encrypt(block: ArraySlice<UInt8>) -> Array<UInt8>? {
     var result = Array<UInt8>()
 
     var l = UInt32(bytes: block[block.startIndex..<block.startIndex.advanced(by: 4)])
     var r = UInt32(bytes: block[block.startIndex.advanced(by: 4)..<block.startIndex.advanced(by: 8)])
 
-    encryptBlowfishBlock(l: &l, r: &r)
+    self.encryptBlowfishBlock(l: &l, r: &r)
 
     // because everything is too complex to be solved in reasonable time o_O
     result += [
@@ -405,13 +413,13 @@ public final class Blowfish {
     return result
   }
 
-  fileprivate func decrypt(block: ArraySlice<UInt8>) -> Array<UInt8>? {
+  private func decrypt(block: ArraySlice<UInt8>) -> Array<UInt8>? {
     var result = Array<UInt8>()
 
     var l = UInt32(bytes: block[block.startIndex..<block.startIndex.advanced(by: 4)])
     var r = UInt32(bytes: block[block.startIndex.advanced(by: 4)..<block.startIndex.advanced(by: 8)])
 
-    decryptBlowfishBlock(l: &l, r: &r)
+    self.decryptBlowfishBlock(l: &l, r: &r)
 
     // because everything is too complex to be solved in reasonable time o_O
     result += [

+ 46 - 25
Sources/CryptoSwift/RSA.swift

@@ -21,24 +21,29 @@ import Foundation
 // It allows fast calculation for RSA big numbers
 
 public final class RSA {
-  
+
   public enum Error: Swift.Error {
     /// No private key specified
     case noPrivateKey
+    /// Failed to calculate the inverse e and phi
+    case invalidInverseNotCoprimes
   }
-  
+
   /// RSA Modulus
   public let n: BigUInteger
-  
+
   /// RSA Public Exponent
   public let e: BigUInteger
-  
+
   /// RSA Private Exponent
   public let d: BigUInteger?
-  
+
   /// The size of the modulus, in bits
   public let keySize: Int
-  
+
+  /// The underlying primes used to generate the Private Exponent
+  private let primes: (p: BigUInteger, q: BigUInteger)?
+
   /// Initialize with RSA parameters
   /// - Parameters:
   ///   - n: The RSA Modulus
@@ -48,10 +53,11 @@ public final class RSA {
     self.n = n
     self.e = e
     self.d = d
-    
+    self.primes = nil
+
     self.keySize = n.bitWidth
   }
-  
+
   /// Initialize with RSA parameters
   /// - Parameters:
   ///   - n: The RSA Modulus
@@ -64,40 +70,57 @@ public final class RSA {
       self.init(n: BigUInteger(Data(n)), e: BigUInteger(Data(e)))
     }
   }
-  
+
   /// Initialize with a generated key pair
   /// - Parameter keySize: The size of the modulus
-  public convenience init(keySize: Int) {
+  public convenience init(keySize: Int) throws {
     // Generate prime numbers
     let p = BigUInteger.generatePrime(keySize / 2)
     let q = BigUInteger.generatePrime(keySize / 2)
-    
+
     // Calculate modulus
     let n = p * q
-    
+
     // Calculate public and private exponent
     let e: BigUInteger = 65537
     let phi = (p - 1) * (q - 1)
-    let d = e.inverse(phi)
-    
+    guard let d = e.inverse(phi) else {
+      throw RSA.Error.invalidInverseNotCoprimes
+    }
+
     // Initialize
-    self.init(n: n, e: e, d: d)
+    self.init(n: n, e: e, d: d, p: p, q: q)
+  }
+
+  /// Initialize with RSA parameters
+  /// - Parameters:
+  ///   - n: The RSA Modulus
+  ///   - e: The RSA Public Exponent
+  ///   - d: The RSA Private Exponent
+  ///   - p: The 1st Prime used to generate the Private Exponent
+  ///   - q: The 2nd Prime used to generate the Private Exponent
+  private init(n: BigUInteger, e: BigUInteger, d: BigUInteger, p: BigUInteger, q: BigUInteger) {
+    self.n = n
+    self.e = e
+    self.d = d
+    self.primes = (p, q)
+
+    self.keySize = n.bitWidth
   }
-  
+
   // TODO: Add initializer from PEM (ASN.1 with DER header) (See #892)
-  
+
   // TODO: Add export to PEM (ASN.1 with DER header) (See #892)
-  
 }
 
 // MARK: Cipher
 
 extension RSA: Cipher {
-  
+
   @inlinable
   public func encrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8> {
     // Calculate encrypted data
-    return BigUInteger(Data(bytes)).power(e, modulus: n).serialize().bytes
+    return BigUInteger(Data(bytes)).power(self.e, modulus: self.n).serialize().bytes
   }
 
   @inlinable
@@ -106,17 +129,16 @@ extension RSA: Cipher {
     guard let d = d else {
       throw RSA.Error.noPrivateKey
     }
-    
+
     // Calculate decrypted data
-    return BigUInteger(Data(bytes)).power(d, modulus: n).serialize().bytes
+    return BigUInteger(Data(bytes)).power(d, modulus: self.n).serialize().bytes
   }
-  
 }
 
 // MARK: CS.BigUInt extension
 
 extension BigUInteger {
-  
+
   public static func generatePrime(_ width: Int) -> BigUInteger {
     // Note: Need to find a better way to generate prime numbers
     while true {
@@ -127,5 +149,4 @@ extension BigUInteger {
       }
     }
   }
-  
 }

+ 26 - 23
Tests/CryptoSwiftTests/RSATests.swift

@@ -18,26 +18,26 @@ import XCTest
 @testable import CryptoSwift
 
 final class RSATests: XCTestCase {
-  
+
   func testSmallRSA() {
     /*
      * Example taken from the book "Understanding Cryptography"
      *
      * p = 3; q = 11; n = pq = 33; e = 3; d = 7
      */
-    
+
     let n: Array<UInt8> = [33]
     let e: Array<UInt8> = [3]
     let d: Array<UInt8> = [7]
     let message: Array<UInt8> = [4]
     let expected: Array<UInt8> = [31]
-    
+
     let rsa = RSA(n: n, e: e, d: d)
     XCTAssertEqual(rsa.keySize, 6, "key size is not correct")
-    
+
     let encrypted = try! rsa.encrypt(message)
     XCTAssertEqual(encrypted, expected, "small encrypt failed")
-    
+
     let decrypted = try! rsa.decrypt(encrypted)
     XCTAssertEqual(decrypted, message, "small decrypt failed")
   }
@@ -48,7 +48,7 @@ final class RSATests: XCTestCase {
      *
      * 1. 1024-bit RSA bare exponentiation
      */
-    
+
     let n: Array<UInt8> = [
       0xF0, 0xC4, 0x2D, 0xB8, 0x48, 0x6F, 0xEB, 0x95, 0x95, 0xD8, 0xC7, 0x8F, 0x90, 0x8D, 0x04, 0xA9,
       0xB6, 0xC8, 0xC7, 0x7A, 0x36, 0x10, 0x5B, 0x1B, 0xF2, 0x75, 0x53, 0x77, 0xA6, 0x89, 0x3D, 0xC4,
@@ -85,24 +85,24 @@ final class RSATests: XCTestCase {
       0x06, 0x1C, 0xB0, 0xA2, 0x1C, 0xA3, 0xA5, 0x24, 0xB4, 0x07, 0xE9, 0xFF, 0xBA, 0x87, 0xFC, 0x96,
       0x6B, 0x3B, 0xA9, 0x45, 0x90, 0x84, 0x9A, 0xEB, 0x90, 0x8A, 0xAF, 0xF4, 0xC7, 0x19, 0xC2, 0xE4
     ]
-    
+
     let rsa = RSA(n: n, e: e, d: d)
     XCTAssertEqual(rsa.keySize, 1024, "key size is not correct")
-    
+
     let encrypted = try! rsa.encrypt(message)
     XCTAssertEqual(encrypted, expected, "encrypt failed")
-    
+
     let decrypted = try! rsa.decrypt(encrypted)
     XCTAssertEqual(decrypted, message, "decrypt failed")
   }
-  
+
   func testRSA2() {
     /*
      * Taken from http://cryptomanager.com/tv.html
      *
      * 2. 2048-bit PKCS V. 1.5 enciphering.
      */
-    
+
     let n: Array<UInt8> = [
       0xF7, 0x48, 0xD8, 0xD9, 0x8E, 0xD0, 0x57, 0xCF, 0x39, 0x8C, 0x43, 0x7F, 0xEF, 0xC6, 0x15, 0xD7,
       0x57, 0xD3, 0xF8, 0xEC, 0xE6, 0xF2, 0xC5, 0x80, 0xAE, 0x07, 0x80, 0x76, 0x8F, 0x9E, 0xC8, 0x3A,
@@ -163,17 +163,17 @@ final class RSATests: XCTestCase {
       0x15, 0x59, 0x23, 0x5E, 0x99, 0xC3, 0x2A, 0xBE, 0xF3, 0x3D, 0x95, 0xE2, 0x8E, 0x18, 0xCC, 0xA3,
       0x44, 0x2E, 0x6E, 0x3A, 0x43, 0x2F, 0xFF, 0xEA, 0x10, 0x10, 0x4A, 0x8E, 0xEE, 0x94, 0xC3, 0x62
     ]
-    
+
     let rsa = RSA(n: n, e: e, d: d)
     XCTAssertEqual(rsa.keySize, 2048, "key size is not correct")
-    
+
     let encrypted = try! rsa.encrypt(message)
     XCTAssertEqual(encrypted, expected, "encrypt failed")
-    
+
     let decrypted = try! rsa.decrypt(encrypted)
     XCTAssertEqual(decrypted, message, "decrypt failed")
   }
-  
+
   func testGenerateKeyPair() {
     /*
      * To test key generation and its validity
@@ -181,15 +181,18 @@ final class RSATests: XCTestCase {
     let message: Array<UInt8> = [
       0x11, 0x22, 0x33, 0x44
     ]
-    
-    let rsa = RSA(keySize: 2048)
-    // Sometimes the modulus size is 2047 bits, but it's okay (with two 1024 bits primes)
-    //XCTAssertEqual(rsa.keySize, 2048, "key size is not correct")
-    
-    let decrypted = try! rsa.decrypt(try! rsa.encrypt(message))
-    XCTAssertEqual(decrypted, message, "encrypt+decrypt failed")
-  }
 
+    do {
+      let rsa = try RSA(keySize: 2048)
+      // Sometimes the modulus size is 2047 bits, but it's okay (with two 1024 bits primes)
+      //XCTAssertEqual(rsa.keySize, 2048, "key size is not correct")
+
+      let decrypted = try rsa.decrypt(rsa.encrypt(message))
+      XCTAssertEqual(decrypted, message, "encrypt+decrypt failed")
+    } catch {
+      XCTFail(error.localizedDescription)
+    }
+  }
 }
 
 extension RSATests {