Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix RSA.Encryption.PublicKey unsafePEMRepresentation incorrect keySizeInBits #234

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Sources/_CryptoExtras/RSA/RSA.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
21 changes: 21 additions & 0 deletions Tests/_CryptoExtrasTests/TestRSAEncryption.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down