extras: Provide initializers for RSA keys from RSA numbers as bytes (#247)

Co-authored-by: Cory Benfield <lukasa@apple.com>
This commit is contained in:
Si BeaumontandCory Benfield authored and GitHub committed 2024-07-22 04:01:44 -07:00
1 parent e2dd5a547b
commit 8dafe0fdce
8 files changed
+251 -102

No files matched your search

@@ -83,6 +83,12 @@ extension _RSA.BlindSigning {
}
}
/// Construct a RSA public key with the specified parameters.
public init(n: some ContiguousBytes, e: some ContiguousBytes, parameters: Parameters) throws {
self.backing = try BackingPublicKey(n: n, e: e)
self.parameters = parameters
}
public var pkcs1DERRepresentation: Data {
self.backing.pkcs1DERRepresentation
}
@@ -171,6 +177,12 @@ extension _RSA.BlindSigning {
}
}
/// Construct an RSA private key with the specified parameters.
public init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes, parameters: Parameters) throws {
self.backing = try BackingPrivateKey(n: n, e: e, d: d, p: p, q: q)
self.parameters = parameters
}
/// Randomly generate a new RSA private key of a given size.
///
/// This constructor will refuse to generate keys smaller than 2048 bits. Callers that want to enforce minimum
+45
View File
@@ -98,6 +98,17 @@ extension _RSA.Signing {
}
}
/// Construct an RSA public key with the specified parameters.
///
/// Only the BoringSSL backend provides APIs to create a key from its parameters so we first create a BoringSSL
/// key, and then pass it to the platform-specific initializer that accepts a BoringSSL key.
///
/// On Darwin platforms, this will serialize it to PEM format, and then construct a platform-specific key from
/// the PEM representation.
public init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.backing = try BackingPublicKey(BoringSSLRSAPublicKey(n: n, e: e))
}
public var pkcs1DERRepresentation: Data {
self.backing.pkcs1DERRepresentation
}
@@ -178,6 +189,17 @@ extension _RSA.Signing {
}
}
/// Construct an RSA private key with the specified parameters.
///
/// Only the BoringSSL backend provides APIs to create a key from its parameters so we first create a BoringSSL
/// key, and then pass it to the platform-specific initializer that accepts a BoringSSL key.
///
/// On Darwin platforms, this will serialize it to DER format, and then construct a platform-specific key from
/// the DER representation.
public init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes) throws {
self.backing = try BackingPrivateKey(BoringSSLRSAPrivateKey(n: n, e: e, d: d, p: p, q: q))
}
/// Randomly generate a new RSA private key of a given size.
///
/// This constructor will refuse to generate keys smaller than 2048 bits. Callers that want to enforce minimum
@@ -444,6 +466,17 @@ extension _RSA.Encryption {
guard self.keySizeInBits >= 1024, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
}
/// Construct an RSA public key with the specified parameters.
///
/// Only the BoringSSL backend provides APIs to create a key from its parameters so we first create a BoringSSL
/// key, and then pass it to the platform-specific initializer that accepts a BoringSSL key.
///
/// On Darwin platforms, this will serialize it to DER format, and then construct a platform-specific key from
/// the DER representation.
public init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.backing = try BackingPublicKey(BoringSSLRSAPublicKey(n: n, e: e))
}
public var pkcs1DERRepresentation: Data { self.backing.pkcs1DERRepresentation }
public var pkcs1PEMRepresentation: String { self.backing.pkcs1PEMRepresentation }
public var derRepresentation: Data { self.backing.derRepresentation }
@@ -494,6 +527,18 @@ extension _RSA.Encryption {
guard self.keySizeInBits >= 1024, self.keySizeInBits % 8 == 0 else { throw CryptoKitError.incorrectParameterSize }
}
/// Construct an RSA private key with the specified parameters.
///
/// Only the BoringSSL backend provides APIs to create a key from its parameters so we first create a BoringSSL
/// key, and then pass it to the platform-specific initializer that accepts a BoringSSL key.
///
/// On Darwin platforms, this will serialize it to PEM format, and then construct a platform-specific key from
/// the PEM representation.
public init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes) throws {
self.backing = try BackingPrivateKey(BoringSSLRSAPrivateKey(n: n, e: e, d: d, p: p, q: q))
}
/// Randomly generate a new RSA private key of a given size.
///
/// This constructor will refuse to generate keys smaller than 2048 bits. Callers that want to enforce minimum
@@ -29,6 +29,14 @@ internal struct BoringSSLRSAPublicKey: Sendable {
self.backing = try Backing(derRepresentation: derRepresentation)
}
init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.backing = try Backing(n: n, e: e)
}
init(_ other: BoringSSLRSAPublicKey) throws {
self = other
}
var pkcs1DERRepresentation: Data {
self.backing.pkcs1DERRepresentation
}
@@ -66,6 +74,14 @@ internal struct BoringSSLRSAPrivateKey: Sendable {
self.backing = try Backing(derRepresentation: derRepresentation)
}
init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes) throws {
self.backing = try Backing(n: n, e: e, d: d, p: p, q: q)
}
init(_ other: BoringSSLRSAPrivateKey) throws {
self = other
}
init(keySize: _RSA.Signing.KeySize) throws {
self.backing = try Backing(keySize: keySize)
}
@@ -222,6 +238,20 @@ extension BoringSSLRSAPublicKey {
}
}
fileprivate init(n: some ContiguousBytes, e: some ContiguousBytes) throws {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
let n = try ArbitraryPrecisionInteger(bytes: n)
let e = try ArbitraryPrecisionInteger(bytes: e)
// Create BoringSSL RSA key.
guard let rsaPtr = n.withUnsafeBignumPointer({ n in
e.withUnsafeBignumPointer { e in
CCryptoBoringSSL_RSA_new_public_key(n, e)
}
}) else { throw CryptoKitError.internalBoringSSLError() }
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPtr)
}
fileprivate var pkcs1DERRepresentation: Data {
return BIOHelper.withWritableMemoryBIO { bio in
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
@@ -486,6 +516,43 @@ extension BoringSSLRSAPrivateKey {
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPrivateKey)
}
fileprivate init(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, p: some ContiguousBytes, q: some ContiguousBytes) throws {
self.pointer = CCryptoBoringSSL_EVP_PKEY_new()
let n = try ArbitraryPrecisionInteger(bytes: n)
let e = try ArbitraryPrecisionInteger(bytes: e)
let d = try ArbitraryPrecisionInteger(bytes: d)
let p = try ArbitraryPrecisionInteger(bytes: p)
let q = try ArbitraryPrecisionInteger(bytes: q)
// Compute the CRT params.
let dp = try FiniteFieldArithmeticContext(fieldSize: p - 1).residue(d)
let dq = try FiniteFieldArithmeticContext(fieldSize: q - 1).residue(d)
guard let qi = try FiniteFieldArithmeticContext(fieldSize: p).inverse(q) else {
throw CryptoKitError.internalBoringSSLError()
}
// Create BoringSSL RSA key.
guard let rsaPtr = n.withUnsafeBignumPointer({ n in
e.withUnsafeBignumPointer { e in
d.withUnsafeBignumPointer { d in
p.withUnsafeBignumPointer { p in
q.withUnsafeBignumPointer { q in
dp.withUnsafeBignumPointer { dp in
dq.withUnsafeBignumPointer { dq in
qi.withUnsafeBignumPointer { qi in
CCryptoBoringSSL_RSA_new_private_key(n, e, d, p, q, dp, dq, qi)
}
}
}
}
}
}
}
}) else { throw CryptoKitError.internalBoringSSLError() }
CCryptoBoringSSL_EVP_PKEY_assign_RSA(self.pointer, rsaPtr)
}
private static func pkcs8DERPrivateKey<Bytes: ContiguousBytes>(_ derRepresentation: Bytes) -> OpaquePointer? {
return derRepresentation.withUnsafeBytes { derPtr in
return BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
@@ -43,6 +43,10 @@ internal struct SecurityRSAPublicKey: @unchecked Sendable {
self.backing = unwrappedKey
}
init(_ boringSSLKey: BoringSSLRSAPublicKey) throws {
try self.init(derRepresentation: boringSSLKey.derRepresentation)
}
var pkcs1DERRepresentation: Data {
var error: Unmanaged<CFError>? = nil
let representation = SecKeyCopyExternalRepresentation(self.backing, &error)
@@ -135,6 +139,10 @@ internal struct SecurityRSAPrivateKey: @unchecked Sendable {
self.backing = unwrappedKey
}
init(_ boringSSLKey: BoringSSLRSAPrivateKey) throws {
try self.init(derRepresentation: boringSSLKey.derRepresentation)
}
var derRepresentation: Data {
var error: Unmanaged<CFError>? = nil
let representation = SecKeyCopyExternalRepresentation(self.backing, &error)
@@ -92,86 +92,3 @@ extension FixedWidthInteger {
return try block(&bn)
}
}
extension _RSA.BlindSigning.PublicKey {
/// Construct a platform-specific RSA public key with the specified parameters.
///
/// This constructor is used in tests in cases where test vectors provide the key information this way.
///
/// Only the BoringSSL backend provides APIs to create the key from its parameters so we first create a BoringSSL
/// key, serialize it to PEM format, and then construct a platform specific key from the PEM representation.
internal init(nHexString: String, eHexString: String, parameters: Parameters) throws {
let n = try ArbitraryPrecisionInteger(hexString: nHexString)
let e = try ArbitraryPrecisionInteger(hexString: eHexString)
// Create BoringSSL RSA key.
guard let rsaPtr = n.withUnsafeBignumPointer({ n in
e.withUnsafeBignumPointer { e in
CCryptoBoringSSL_RSA_new_public_key(n, e)
}
}) else { throw CryptoKitError.internalBoringSSLError() }
defer { CCryptoBoringSSL_RSA_free(rsaPtr) }
// Get PEM representation for key.
let pemRepresentation = BIOHelper.withWritableMemoryBIO { bio in
precondition(CCryptoBoringSSL_PEM_write_bio_RSAPublicKey(bio, rsaPtr) == 1)
return try! String(copyingUTF8MemoryBIO: bio)
}
// Create a key (which might be backed by Security framework) from PEM representation.
try self.init(pemRepresentation: pemRepresentation, parameters: parameters)
}
}
extension _RSA.BlindSigning.PrivateKey {
/// Construct a platform-specific RSA private key with the specified parameters.
///
/// This constructor is used in tests in cases where test vectors provide the key information this way.
///
/// Only the BoringSSL backend provides APIs to create the key from its parameters so we first create a BoringSSL
/// key, serialize it to PEM format, and then construct a platform specific key from the PEM representation.
internal init(nHexString: String, eHexString: String, dHexString: String, pHexString: String, qHexString: String, parameters: Parameters) throws {
let n = try ArbitraryPrecisionInteger(hexString: nHexString)
let e = try ArbitraryPrecisionInteger(hexString: eHexString)
let d = try ArbitraryPrecisionInteger(hexString: dHexString)
let p = try ArbitraryPrecisionInteger(hexString: pHexString)
let q = try ArbitraryPrecisionInteger(hexString: qHexString)
// Compute the CRT params.
let dp = try FiniteFieldArithmeticContext(fieldSize: p - 1).residue(d)
let dq = try FiniteFieldArithmeticContext(fieldSize: q - 1).residue(d)
guard let qi = try FiniteFieldArithmeticContext(fieldSize: p).inverse(q) else {
throw CryptoKitError.internalBoringSSLError()
}
// Create BoringSSL RSA key.
guard let rsaPtr = n.withUnsafeBignumPointer({ n in
e.withUnsafeBignumPointer { e in
d.withUnsafeBignumPointer { d in
p.withUnsafeBignumPointer { p in
q.withUnsafeBignumPointer { q in
dp.withUnsafeBignumPointer { dp in
dq.withUnsafeBignumPointer { dq in
qi.withUnsafeBignumPointer { qi in
CCryptoBoringSSL_RSA_new_private_key(n, e, d, p, q, dp, dq, qi)
}
}
}
}
}
}
}
}) else { throw CryptoKitError.internalBoringSSLError() }
defer { CCryptoBoringSSL_RSA_free(rsaPtr) }
// Get PEM representation for key.
let pemRepresentation = BIOHelper.withWritableMemoryBIO { bio in
precondition(CCryptoBoringSSL_PEM_write_bio_RSAPrivateKey(bio, rsaPtr, nil, nil, 0, nil, nil) == 1)
return try! String(copyingUTF8MemoryBIO: bio)
}
// Create a key (which might be backed by Security framework) from PEM representation.
try self.init(pemRepresentation: pemRepresentation, parameters: parameters)
}
}
@@ -15,7 +15,7 @@ import XCTest
import Crypto
@testable import _CryptoExtras
fileprivate struct TestVector: Codable {
struct RFC9474TestVector: Codable {
var name, p, q, n, e, d, msg, msg_prefix, prepared_msg, salt, inv, blinded_msg, blind_sig, sig: String
var parameters: _RSA.BlindSigning.Parameters<SHA384> {
@@ -40,19 +40,33 @@ fileprivate struct TestVector: Codable {
let decoder = JSONDecoder()
return try decoder.decode([Self].self, from: json)
}
static let allValues: [Self] = try! RFC9474TestVector.load(from: URL(
fileURLWithPath: "../_CryptoExtrasVectors/rfc9474.json",
relativeTo: URL(fileURLWithPath: #file)
))
}
final class TestRSABlindSigning: XCTestCase {
func testAgainstRFC9474TestVectors() throws {
let testVectors = try TestVector.load(from: URL(
fileURLWithPath: "../_CryptoExtrasVectors/rfc9474.json",
relativeTo: URL(fileURLWithPath: #file)
))
for testVector in testVectors {
for testVector in RFC9474TestVector.allValues {
// Load key pair
let privateKey = try _RSA.BlindSigning.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),
parameters: testVector.parameters
)
let publicKey = try _RSA.BlindSigning.PublicKey(
n: Data(hexString: testVector.n),
e: Data(hexString: testVector.e),
parameters: testVector.parameters
)
XCTAssertEqual(publicKey.derRepresentation, privateKey.publicKey.derRepresentation)
// Prepare
do {
let publicKey = try _RSA.BlindSigning.PublicKey(nHexString: testVector.n, eHexString: testVector.e, parameters: testVector.parameters)
let message = try Data(hexString: testVector.msg)
let preparedMessage = publicKey.prepare(message)
switch testVector.parameters.preparation {
@@ -65,7 +79,6 @@ final class TestRSABlindSigning: XCTestCase {
// Blind
do {
let publicKey = try _RSA.BlindSigning.PublicKey(nHexString: testVector.n, eHexString: testVector.e, parameters: testVector.parameters)
let preparedMessage = try _RSA.BlindSigning.PreparedMessage(rawRepresentation: Data(hexString: testVector.prepared_msg))
let blindingResult = try publicKey.blind(preparedMessage)
// NOTE: Sadly we can't validate the blinded message against the test vectors because BoringSSL doesn't
@@ -76,14 +89,6 @@ final class TestRSABlindSigning: XCTestCase {
// BlindSign
do {
let privateKey = try _RSA.BlindSigning.PrivateKey(
nHexString: testVector.n,
eHexString: testVector.e,
dHexString: testVector.d,
pHexString: testVector.p,
qHexString: testVector.q,
parameters: testVector.parameters
)
let blindedMessage = try Data(hexString: testVector.blinded_msg)
let blindSignature = try privateKey.blindSignature(for: blindedMessage)
XCTAssertEqual(
@@ -94,7 +99,6 @@ final class TestRSABlindSigning: XCTestCase {
// Finalize
do {
let publicKey = try _RSA.BlindSigning.PublicKey(nHexString: testVector.n, eHexString: testVector.e, parameters: testVector.parameters)
let blindSignature = try _RSA.BlindSigning.BlindSignature(rawRepresentation: Data(hexString: testVector.blind_sig))
let preparedMessage = try _RSA.BlindSigning.PreparedMessage(rawRepresentation: Data(hexString: testVector.prepared_msg))
let blindingInverse = try _RSA.BlindSigning.BlindingInverse(rawRepresentation: Data(hexString: testVector.inv))
@@ -107,7 +111,6 @@ final class TestRSABlindSigning: XCTestCase {
// Verification
do {
let publicKey = try _RSA.BlindSigning.PublicKey(nHexString: testVector.n, eHexString: testVector.e, parameters: testVector.parameters)
let signature = try _RSA.Signing.RSASignature(rawRepresentation: Data(hexString: testVector.sig))
let preparedMessage = try _RSA.BlindSigning.PreparedMessage(rawRepresentation: Data(hexString: testVector.prepared_msg))
XCTAssert(publicKey.isValidSignature(signature, for: preparedMessage))
@@ -164,4 +167,39 @@ final class TestRSABlindSigning: XCTestCase {
}
}
}
func testConstructKeyFromRSANumbers() throws {
/// Check we can successfully construct keys from known valid values from a test vector.
for testVector in RFC9474TestVector.allValues {
_ = try _RSA.BlindSigning.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),
parameters: testVector.parameters
)
_ = try _RSA.BlindSigning.PublicKey(
n: Data(hexString: testVector.n),
e: Data(hexString: testVector.e),
parameters: testVector.parameters
)
}
/// 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.BlindSigning.PrivateKey(
n: bytesValues.randomElement()!,
e: bytesValues.randomElement()!,
d: bytesValues.randomElement()!,
p: bytesValues.randomElement()!,
q: bytesValues.randomElement()!,
parameters: .RSABSSA_SHA384_PSS_Randomized
)
_ = try? _RSA.BlindSigning.PublicKey(
n: bytesValues.randomElement()!,
e: bytesValues.randomElement()!,
parameters: .RSABSSA_SHA384_PSS_Randomized
)
}
}
@@ -77,6 +77,37 @@ final class TestRSAEncryption: XCTestCase {
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()!
)
}
}
struct RSAEncryptionOAEPTestGroup: Codable {
@@ -677,6 +677,37 @@ final class TestRSASigning: XCTestCase {
XCTAssertEqual(pemKey, key.pkcs8PEMRepresentation)
}
func testConstructKeyFromRSANumbers() throws {
/// Check we can successfully construct keys from known valid values from a test vector.
for testVector in RFC9474TestVector.allValues {
_ = try _RSA.Signing.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.Signing.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.Signing.PrivateKey(
n: bytesValues.randomElement()!,
e: bytesValues.randomElement()!,
d: bytesValues.randomElement()!,
p: bytesValues.randomElement()!,
q: bytesValues.randomElement()!
)
_ = try? _RSA.Signing.PublicKey(
n: bytesValues.randomElement()!,
e: bytesValues.randomElement()!
)
}
private func testPKCS1Group(_ group: RSAPKCS1TestGroup) throws {
let derKey: _RSA.Signing.PublicKey
let pemKey: _RSA.Signing.PublicKey