From 8a45c0bdd794ec8adac8eed1647025a3a7672cc4 Mon Sep 17 00:00:00 2001 From: liudong Date: Sun, 26 May 2024 14:43:38 +0800 Subject: [PATCH 1/2] Fix RSA.Encryption.PublicKey unsafePEMRepresentation init func incorrect keySizeInBits check --- Sources/_CryptoExtras/RSA/RSA.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/_CryptoExtras/RSA/RSA.swift b/Sources/_CryptoExtras/RSA/RSA.swift index fbcec8ca3..d21d77a36 100644 --- a/Sources/_CryptoExtras/RSA/RSA.swift +++ b/Sources/_CryptoExtras/RSA/RSA.swift @@ -414,7 +414,7 @@ extension _RSA.Encryption { /// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons. public init(unsafePEMRepresentation pemRepresentation: String) throws { self.backing = try BackingPublicKey(pemRepresentation: pemRepresentation) - guard self.keySizeInBits >= 2048, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize } + guard self.keySizeInBits >= 1024, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize } } /// Construct an RSA public key from a DER representation. From 1d8087c36ae08ef0d3879046d4f4d4b89b478a8f Mon Sep 17 00:00:00 2001 From: liudong Date: Wed, 29 May 2024 13:48:27 +0800 Subject: [PATCH 2/2] Add unit test for unsafe key size check --- .../TestRSAEncryption.swift | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Tests/_CryptoExtrasTests/TestRSAEncryption.swift b/Tests/_CryptoExtrasTests/TestRSAEncryption.swift index 84d63e576..876a1a5ec 100644 --- a/Tests/_CryptoExtrasTests/TestRSAEncryption.swift +++ b/Tests/_CryptoExtrasTests/TestRSAEncryption.swift @@ -77,6 +77,27 @@ final class TestRSAEncryption: XCTestCase { XCTAssertEqual(valid, test.expectedValidity, "test number \(test.tcId) failed, expected \(test.result) but got \(valid)") } } + + func testUnsafeKeySize() throws { + try testUnsafeKeySize(1024) + try testUnsafeKeySize(1536) + } + + private func testUnsafeKeySize(_ keySizeInBits: Int) throws { + XCTAssert(keySizeInBits >= 1024 && keySizeInBits < 2048, "Unsafe key size must be in the range [1024, 2048)") + + let privKey = try _RSA.Encryption.PrivateKey(unsafeKeySize: .init(bitCount: keySizeInBits)) + let derPrivKey = try _RSA.Encryption.PrivateKey(unsafeDERRepresentation: privKey.derRepresentation) + XCTAssert(derPrivKey.keySizeInBits == keySizeInBits) + let pemPrivKey = try _RSA.Encryption.PrivateKey(unsafePEMRepresentation: privKey.pemRepresentation) + XCTAssert(pemPrivKey.keySizeInBits == keySizeInBits) + + let pubKey = privKey.publicKey + let derPubKey = try _RSA.Encryption.PublicKey(unsafeDERRepresentation: pubKey.derRepresentation) + XCTAssert(derPubKey.keySizeInBits == keySizeInBits) + let pemPubKey = try _RSA.Encryption.PublicKey(unsafePEMRepresentation: pubKey.pemRepresentation) + XCTAssert(pemPubKey.keySizeInBits == keySizeInBits) + } } struct RSAEncryptionOAEPTestGroup: Codable {