Files
swift-crypto/Tests/CryptoExtrasTests/TestRSAEncryption.swift
T
Mike SchragandMike Schrag e8ed8867ec Incorrect maximum encryption size for RSA OAEP (#423)
Incorrect maximum encryption size for RSA OAEP

### Checklist
- [X] I've run tests to see all new and existing tests pass
- [X] I've followed the code style of the rest of the project
- [X] I've read the [Contribution Guidelines](CONTRIBUTING.md)
- [X] I've updated the documentation if necessary

#### If you've made changes to `gyb` files
- [n/a] I've run `./scripts/generate_boilerplate_files_with_gyb.sh` and
included updated generated files in a commit of this pull request

### Motivation:
The `maximumEncryptSize` function is hardcoded to use 42 as the hash
offset, but the RFC actually says it's "2*hLen-2" so 42 is only valid
for SHA1. SHA256 should be 62 (2*32-2). This adds a hash length onto the
Digest enum, which can then be used in the length calculation.

In writing the tests for this, I also stumbled on the unsafe PEM
representation for RSA Public Keys don't allow 1024-bit keys as
documented, so this also fixes that.

### Modifications:
* Added a `hashBitLength` to the RSA Digest which is then used in the
`maximumEncryptSize` to properly compute the maximum length
* Corrected the minimum key size for RSA unsafe PEM public keys to 1024
from 2048

### Result:
* The `maximumEncryptSize` function will return the expected value for
RSA OAEP SHA256 keys. I don't believe anything calls this internally, so
this would be for external consumers.
* Unsafe construction of RSA public keys now allow 1024 bit keys. It was
documented as supporting them, but the check was still 2048 (probably
copy-paste error from the safe variant). This only expands the potential
uses, so it shouldn't introduce any new failures.

Co-authored-by: Mike Schrag <schrag@apple.com>
2025-10-29 10:58:46 +00:00

217 lines
8.0 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) YEARS Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import XCTest
import Crypto
import CryptoExtras
final class TestRSAEncryption: XCTestCase {
func test_wycheproofOAEPVectors() throws {
try wycheproofTest(
jsonName: "rsa_oaep_misc_test",
testFunction: self.testOAEPGroup)
try wycheproofTest(
jsonName: "rsa_oaep_2048_sha1_mgf1sha1_test",
testFunction: self.testOAEPGroup)
try wycheproofTest(
jsonName: "rsa_oaep_2048_sha256_mgf1sha256_test",
testFunction: self.testOAEPGroup)
}
private func testOAEPGroup(_ group: RSAEncryptionOAEPTestGroup) throws {
let derPrivKey: _RSA.Encryption.PrivateKey
let pemPrivKey: _RSA.Encryption.PrivateKey
if group.keysize < 2048 {
derPrivKey = try _RSA.Encryption.PrivateKey(unsafeDERRepresentation: group.privateKeyDerBytes)
pemPrivKey = try _RSA.Encryption.PrivateKey(unsafePEMRepresentation: group.privateKeyPem)
} else {
derPrivKey = try _RSA.Encryption.PrivateKey(derRepresentation: group.privateKeyDerBytes)
pemPrivKey = try _RSA.Encryption.PrivateKey(pemRepresentation: group.privateKeyPem)
}
XCTAssertEqual(derPrivKey.derRepresentation, pemPrivKey.derRepresentation)
XCTAssertEqual(derPrivKey.pemRepresentation, pemPrivKey.pemRepresentation)
let derPubKey = derPrivKey.publicKey
let padding: _RSA.Encryption.Padding
if group.sha == "SHA-1", group.mgfSha == "SHA-1" {
padding = .PKCS1_OAEP
} else if group.sha == "SHA-256", group.mgfSha == "SHA-256" {
padding = .PKCS1_OAEP_SHA256
} else {
// We currently only support SHA-1, SHA-256.
return
}
for test in group.tests {
guard test.label?.isEmpty ?? true else {
// We currently have no support for OAEP labels.
continue
}
let valid: Bool
do {
let decryptResult = try derPrivKey.decrypt(test.ciphertextBytes, padding: padding)
let encryptResult = try derPubKey.encrypt(test.messageBytes, padding: padding)
let decryptResult2 = try derPrivKey.decrypt(encryptResult, padding: padding)
valid = (test.messageBytes == decryptResult && decryptResult2 == decryptResult)
} catch {
valid = false
}
XCTAssertEqual(valid, test.expectedValidity, "test number \(test.tcId) failed, expected \(test.result) but got \(valid)")
}
}
func testConstructKeyFromRSANumbers() throws {
/// Check we can successfully construct keys from known valid values from a test vector.
for testVector in RFC9474TestVector.allValues {
_ = try _RSA.Encryption.PrivateKey(
n: Data(hexString: testVector.n),
e: Data(hexString: testVector.e),
d: Data(hexString: testVector.d),
p: Data(hexString: testVector.p),
q: Data(hexString: testVector.q)
)
_ = try _RSA.Encryption.PublicKey(
n: Data(hexString: testVector.n),
e: Data(hexString: testVector.e)
)
}
/// Also check that we can provide each argument as a different `ContiguousBytes` type.
/// NOTE: these calls use `try?` because they are guaranteed to fail; we're just checking these calls compile.
let bytesValues: [any ContiguousBytes] = [Data(), [UInt8]()]
_ = try? _RSA.Encryption.PrivateKey(
n: bytesValues.randomElement()!,
e: bytesValues.randomElement()!,
d: bytesValues.randomElement()!,
p: bytesValues.randomElement()!,
q: bytesValues.randomElement()!
)
_ = try? _RSA.Encryption.PublicKey(
n: bytesValues.randomElement()!,
e: bytesValues.randomElement()!
)
}
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)
let e = try Data(hexString: testVector.e)
let primitives = try _RSA.Encryption.PublicKey(n: n, e: e).getKeyPrimitives()
XCTAssertEqual(primitives.modulus, n)
XCTAssertEqual(primitives.publicExponent, e)
}
}
func testMaximumEncryptSize() throws {
let pemRepresentation1024 = """
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTLbu1QZhtXWKCHOjavP5NUCwJ
5DwjoMKGlEM/PQOMiY+wup8R1kCOHV6g+FvJ86laHJc0gqwFf1U51YxtQFy7cGV4
W2zJeTkqadO2fvTCjbZU+Oa78iVtTynq5h4yRWrTmveyzInhdVpi075Ql2hpGuET
H1qYVxqaDIJEHyETDQIDAQAB
-----END PUBLIC KEY-----
"""
let pubKey1024 = try _RSA.Encryption.PublicKey(unsafePEMRepresentation: pemRepresentation1024)
XCTAssertEqual(86, pubKey1024.maximumEncryptSize(with: .PKCS1_OAEP))
XCTAssertEqual(62, pubKey1024.maximumEncryptSize(with: .PKCS1_OAEP_SHA256))
let pemRepresentation2048 = """
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx8IRKcs5FrHlWye2lfwc
Hr0Pi8g5iZhGMOOwmyIVsNULAvUIGZlIw38NNqebH3eF6ZxPiSRpwPwIs6QRcH5/
IwbHkUc0KdBbUwXDrLs0w00I7Flu5RP7IEfkOZdDGEWFY1pA3H1HaogxKFc5k3mM
s7pW6oty1eP4O7aVa/Pp363Vba7EZ2nru9lz4Ta+JU8UIHbpoddMGikGEKHrQ/Ge
n9RMNzSIy/e7TgTwC39GKn8fwN6VfcdNjvIhJrFNha/ORNArpzup7FUUauGLKt3a
jgsIjrAPBp63+Sy7+aFVoGTvI7DCkZ/Wv3JCFRuTAdYOa0A1xiqhTb1pcypvrd2T
ZQIDAQAB
-----END PUBLIC KEY-----
"""
let pubKey2048 = try _RSA.Encryption.PublicKey(pemRepresentation: pemRepresentation2048)
XCTAssertEqual(214, pubKey2048.maximumEncryptSize(with: .PKCS1_OAEP))
XCTAssertEqual(190, pubKey2048.maximumEncryptSize(with: .PKCS1_OAEP_SHA256))
}
}
struct RSAEncryptionOAEPTestGroup: Codable {
var privateKeyPem: String
var privateKeyPkcs8: String
var sha: String
var tests: [RSAEncryptionTest]
var mgfSha: String
var keysize: Int
var privateKeyDerBytes: Data {
return try! Data(hexString: self.privateKeyPkcs8)
}
}
struct RSAEncryptionTest: Codable {
var tcId: Int
var comment: String
var msg: String
var ct: String
var result: String
var flags: [String]
var label: String?
var messageBytes: Data {
return try! Data(hexString: self.msg)
}
var ciphertextBytes: Data {
return try! Data(hexString: self.ct)
}
var expectedValidity: Bool {
switch self.result {
case "valid":
return true
case "invalid":
return false
case "acceptable":
return true
default:
fatalError("Unexpected validity")
}
}
}