diff --git a/Sources/Crypto/Util/BoringSSL/Shared/ArbitraryPrecisionInteger_boring.swift b/Sources/Crypto/Util/BoringSSL/Shared/ArbitraryPrecisionInteger_boring.swift index 73476e64..2bdf5271 100644 --- a/Sources/Crypto/Util/BoringSSL/Shared/ArbitraryPrecisionInteger_boring.swift +++ b/Sources/Crypto/Util/BoringSSL/Shared/ArbitraryPrecisionInteger_boring.swift @@ -405,6 +405,13 @@ extension ArbitraryPrecisionInteger: SignedNumeric { // MARK: - Other arithmetic operations extension ArbitraryPrecisionInteger { + @usableFromInline + var trailingZeroBitCount: Int32 { + self.withUnsafeBignumPointer { + CCryptoBoringSSL_BN_count_low_zero_bits($0) + } + } + @usableFromInline static func gcd(_ a: ArbitraryPrecisionInteger, _ b: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger { var result = ArbitraryPrecisionInteger() @@ -443,6 +450,46 @@ extension ArbitraryPrecisionInteger { return result } + + @usableFromInline + static func >> (lhs: ArbitraryPrecisionInteger, rhs: Int32) -> ArbitraryPrecisionInteger { + var result = ArbitraryPrecisionInteger() + + let rc = result.withUnsafeMutableBignumPointer { resultPtr in + lhs.withUnsafeBignumPointer { lhsPtr in + CCryptoBoringSSL_BN_rshift(resultPtr, lhsPtr, rhs) + } + } + + precondition(rc == 1, "Unable to allocate memory for new ArbitraryPrecisionInteger") + + return result + } + + @usableFromInline + static func / (lhs: ArbitraryPrecisionInteger, rhs: ArbitraryPrecisionInteger) -> ArbitraryPrecisionInteger { + var result = ArbitraryPrecisionInteger() + + let rc = result.withUnsafeMutableBignumPointer { resultPtr in + lhs.withUnsafeBignumPointer { lhsPtr in + rhs.withUnsafeBignumPointer { rhsPtr in + ArbitraryPrecisionInteger.withUnsafeBN_CTX { bnCtx in + CCryptoBoringSSL_BN_div(resultPtr, nil, lhsPtr, rhsPtr, bnCtx) + } + } + } + } + precondition(rc == 1, "Unable to allocate memory for new ArbitraryPrecisionInteger") + + return result + } + + @usableFromInline + var isEven: Bool { + self.withUnsafeBignumPointer { + CCryptoBoringSSL_BN_is_odd($0) == 0 + } + } } // MARK: - Serializing diff --git a/Sources/_CryptoExtras/RSA/RSA+BlindSigning.swift b/Sources/_CryptoExtras/RSA/RSA+BlindSigning.swift index 9108c039..dc04c8a6 100644 --- a/Sources/_CryptoExtras/RSA/RSA+BlindSigning.swift +++ b/Sources/_CryptoExtras/RSA/RSA+BlindSigning.swift @@ -242,6 +242,34 @@ extension _RSA.BlindSigning { public var publicKey: _RSA.BlindSigning.PublicKey { _RSA.BlindSigning.PublicKey(self.backing.publicKey, self.parameters) } + + /// Construct a private key with the specified parameters. + /// + /// The use of this API is strongly discouraged for performance reasons, + /// as it requires the factorization of the modulus, which is resource-intensive. + /// It is recommended to use the other initializers to construct a private key, + /// unless you have only the modulus, public exponent, and private exponent + /// to construct the key. + /// + /// - Parameters: + /// - n: modulus of the key + /// - e: public exponent of the key + /// - d: private exponent of the key + /// - parameters: parameters used in the blind signing protocol + public static func _createFromNumbers(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, parameters: Parameters) throws -> Self { + let (p, q) = try _RSA.extractPrimeFactors( + n: try ArbitraryPrecisionInteger(bytes: n), + e: try ArbitraryPrecisionInteger(bytes: e), + d: try ArbitraryPrecisionInteger(bytes: d) + ) + + return try Self.init( + n: n, e: e, d: d, + p: try Data(bytesOf: p, paddedToSize: p.byteCount), + q: try Data(bytesOf: q, paddedToSize: q.byteCount), + parameters: parameters + ) + } } } diff --git a/Sources/_CryptoExtras/RSA/RSA.swift b/Sources/_CryptoExtras/RSA/RSA.swift index bd4bf516..6177d0c8 100644 --- a/Sources/_CryptoExtras/RSA/RSA.swift +++ b/Sources/_CryptoExtras/RSA/RSA.swift @@ -257,6 +257,32 @@ extension _RSA.Signing { public var publicKey: _RSA.Signing.PublicKey { _RSA.Signing.PublicKey(self.backing.publicKey) } + + /// Construct a private key with the specified parameters. + /// + /// The use of this API is strongly discouraged for performance reasons, + /// as it requires the factorization of the modulus, which is resource-intensive. + /// It is recommended to use the other initializers to construct a private key, + /// unless you have only the modulus, public exponent, and private exponent + /// to construct the key. + /// + /// - Parameters: + /// - n: modulus of the key + /// - e: public exponent of the key + /// - d: private exponent of the key + public static func _createFromNumbers(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes) throws -> Self { + let (p, q) = try _RSA.extractPrimeFactors( + n: try ArbitraryPrecisionInteger(bytes: n), + e: try ArbitraryPrecisionInteger(bytes: e), + d: try ArbitraryPrecisionInteger(bytes: d) + ) + + return try Self.init( + n: n, e: e, d: d, + p: try Data(bytesOf: p, paddedToSize: p.byteCount), + q: try Data(bytesOf: q, paddedToSize: q.byteCount) + ) + } } } @@ -593,6 +619,32 @@ extension _RSA.Encryption { public var pkcs8PEMRepresentation: String { self.backing.pkcs8PEMRepresentation } public var keySizeInBits: Int { self.backing.keySizeInBits } public var publicKey: _RSA.Encryption.PublicKey { .init(self.backing.publicKey) } + + /// Construct a private key with the specified parameters. + /// + /// The use of this API is strongly discouraged for performance reasons, + /// as it requires the factorization of the modulus, which is resource-intensive. + /// It is recommended to use the other initializers to construct a private key, + /// unless you have only the modulus, public exponent, and private exponent + /// to construct the key. + /// + /// - Parameters: + /// - n: modulus of the key + /// - e: public exponent of the key + /// - d: private exponent of the key + public static func _createFromNumbers(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes) throws -> Self { + let (p, q) = try _RSA.extractPrimeFactors( + n: try ArbitraryPrecisionInteger(bytes: n), + e: try ArbitraryPrecisionInteger(bytes: e), + d: try ArbitraryPrecisionInteger(bytes: d) + ) + + return try Self.init( + n: n, e: e, d: d, + p: try Data(bytesOf: p, paddedToSize: p.byteCount), + q: try Data(bytesOf: q, paddedToSize: q.byteCount) + ) + } } } @@ -669,3 +721,60 @@ extension _RSA { static let SPKIPublicKeyType = "PUBLIC KEY" } + +extension _RSA { + static func extractPrimeFactors( + n: ArbitraryPrecisionInteger, + e: ArbitraryPrecisionInteger, + d: ArbitraryPrecisionInteger + ) throws -> (p: ArbitraryPrecisionInteger, q: ArbitraryPrecisionInteger) { + // This is based on the proof of fact 1 in https://www.ams.org/notices/199902/boneh.pdf + let k = (d * e) - 1 + let t = k.trailingZeroBitCount + let r = k >> t + + guard k.isEven else { + throw CryptoKitError.incorrectParameterSize + } + + var y: ArbitraryPrecisionInteger = 0 + var i = 1 + + let context = try FiniteFieldArithmeticContext(fieldSize: n) + + while i <= 100 { + let g = try ArbitraryPrecisionInteger.random(inclusiveMin: 2, exclusiveMax: n) + y = try context.pow(g, r) + + guard y != 1, y != n - 1 else { + continue + } + + var j = 1 + var x: ArbitraryPrecisionInteger + + while j <= t &- 1 { + x = try context.pow(y, 2) + + guard x != 1, x != n - 1 else { + break + } + + y = x + j &+= 1 + } + + x = try context.pow(y, 2) + if x == 1 { + let p = try ArbitraryPrecisionInteger.gcd(y - 1, n) + let q = n / p + + return (p, q) + } + + i &+= 1 + } + + throw CryptoKitError.incorrectParameterSize + } +} diff --git a/Tests/_CryptoExtrasTests/TestRSABlindSigning.swift b/Tests/_CryptoExtrasTests/TestRSABlindSigning.swift index 5a0a2766..4ae312a6 100644 --- a/Tests/_CryptoExtrasTests/TestRSABlindSigning.swift +++ b/Tests/_CryptoExtrasTests/TestRSABlindSigning.swift @@ -203,6 +203,25 @@ final class TestRSABlindSigning: XCTestCase { ) } + func testConstructAndUseKeyFromRSANumbersWhileRecoveringPrimes() throws { + let data = Array("hello, world!".utf8) + + for testVector in RFC9474TestVector.allValues { + let key = try _RSA.BlindSigning.PrivateKey._createFromNumbers( + n: Data(hexString: testVector.n), + e: Data(hexString: testVector.e), + d: Data(hexString: testVector.d), + parameters: testVector.parameters + ) + + let preparedMessage = key.publicKey.prepare(data) + let blindedMessage = try key.publicKey.blind(preparedMessage) + let blindSignature = try key.blindSignature(for: blindedMessage.blindedMessage) + let signature = try key.publicKey.finalize(blindSignature, for: preparedMessage, blindingInverse: blindedMessage.inverse) + XCTAssert(key.publicKey.isValidSignature(signature, for: preparedMessage)) + } + } + func testGetKeyPrimitives() throws { for testVector in RFC9474TestVector.allValues { let n = try Data(hexString: testVector.n) diff --git a/Tests/_CryptoExtrasTests/TestRSAEncryption.swift b/Tests/_CryptoExtrasTests/TestRSAEncryption.swift index e5f8fe88..61c79b73 100644 --- a/Tests/_CryptoExtrasTests/TestRSAEncryption.swift +++ b/Tests/_CryptoExtrasTests/TestRSAEncryption.swift @@ -109,6 +109,23 @@ final class TestRSAEncryption: XCTestCase { ) } + func testConstructAndUseKeyFromRSANumbersWhileRecoveringPrimes() throws { + let data = Array("hello, world!".utf8) + + for testVector in RFC9474TestVector.allValues { + let key = try _RSA.Encryption.PrivateKey._createFromNumbers( + n: Data(hexString: testVector.n), + e: Data(hexString: testVector.e), + d: Data(hexString: testVector.d) + ) + + let encrypted = try key.publicKey.encrypt(data, padding: .PKCS1_OAEP_SHA256) + let decrypted = try key.decrypt(encrypted, padding: .PKCS1_OAEP_SHA256) + + XCTAssertEqual(Data(data), decrypted) + } + } + func testGetKeyPrimitives() throws { for testVector in RFC9474TestVector.allValues { let n = try Data(hexString: testVector.n) diff --git a/Tests/_CryptoExtrasTests/TestRSASigning.swift b/Tests/_CryptoExtrasTests/TestRSASigning.swift index fe47743b..505e55ac 100644 --- a/Tests/_CryptoExtrasTests/TestRSASigning.swift +++ b/Tests/_CryptoExtrasTests/TestRSASigning.swift @@ -13,8 +13,8 @@ //===----------------------------------------------------------------------===// import Foundation import XCTest -@testable import Crypto -import _CryptoExtras +import Crypto +@testable import _CryptoExtras final class TestRSASigning: XCTestCase { func test_wycheproofPKCS1Vectors() throws { @@ -73,6 +73,15 @@ final class TestRSASigning: XCTestCase { testFunction: self.testPSSGroup) } + func test_wycheproofPrimitives() throws { + try wycheproofTest( + jsonName: "rsa_oaep_2048_sha1_mgf1sha1_test", + testFunction: self.testPrimeFactors) + try wycheproofTest( + jsonName: "rsa_oaep_2048_sha256_mgf1sha256_test", + testFunction: self.testPrimeFactors) + } + func testPKCS1Signing() throws { try self.testPKCS1Signing(_RSA.Signing.PrivateKey(keySize: .bits2048)) try self.testPKCS1Signing(_RSA.Signing.PrivateKey(keySize: .bits3072)) @@ -708,6 +717,23 @@ final class TestRSASigning: XCTestCase { ) } + func testConstructAndUseKeyFromRSANumbersWhileRecoveringPrimes() throws { + let data = Array("hello, world!".utf8) + + for testVector in RFC9474TestVector.allValues { + let key = try _RSA.Signing.PrivateKey._createFromNumbers( + n: Data(hexString: testVector.n), + e: Data(hexString: testVector.e), + d: Data(hexString: testVector.d) + ) + + let signature = try key.signature(for: data) + let roundTripped = _RSA.Signing.RSASignature(rawRepresentation: signature.rawRepresentation) + XCTAssertEqual(signature.rawRepresentation, roundTripped.rawRepresentation) + XCTAssertTrue(key.publicKey.isValidSignature(roundTripped, for: data)) + } + } + func testGetKeyPrimitives() throws { for testVector in RFC9474TestVector.allValues { let n = try Data(hexString: testVector.n) @@ -801,6 +827,15 @@ final class TestRSASigning: XCTestCase { } } + private func testPrimeFactors(_ group: RSAPrimitivesTestGroup) throws { + let n = try ArbitraryPrecisionInteger(hexString: group.n) + let e = try ArbitraryPrecisionInteger(hexString: group.e) + let d = try ArbitraryPrecisionInteger(hexString: group.d) + + let (p, q) = try _RSA.extractPrimeFactors(n: n, e: e, d: d) + XCTAssertEqual(p * q, n, "The product of p and q should equal n; got \(p) * \(q) != \(n)") + } + private func pemForDERBytes(discriminator: String, derBytes: Data) -> String { let lineLength = 64 var encoded = derBytes.base64EncodedString()[...] @@ -882,3 +917,27 @@ struct RSATest: Codable { } } } + +struct RSAPrimitivesTestGroup: Codable { + let n: String + let e: String + let d: String + let privateKeyJwk: PrivateKeyJWK? + + struct PrivateKeyJWK: Codable { + let kty: String + let n: String + let e: String + let d: String + let p: String + let q: String + let dp: String + let dq: String + let qi: String + } +} + +struct RSAPrimitivesTestVectors: Codable { + let testGroups: [RSAPrimitivesTestGroup] +} +