diff --git a/Sources/_CryptoExtras/RSA/RSA.swift b/Sources/_CryptoExtras/RSA/RSA.swift index fbcec8ca..d21d77a3 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. diff --git a/Tests/_CryptoExtrasTests/TestRSAEncryption.swift b/Tests/_CryptoExtrasTests/TestRSAEncryption.swift index 84d63e57..876a1a5e 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 {