mirror of
https://github.com/apple/swift-crypto
synced 2026-11-27 04:54:21 +00:00
extras: Add API to create RSA keys with random primes (#250)
This adds a _createFromNumbers API which creates an RSA key generating p and q primes based on n, e and d Motivation: There might be cases where private RSA keys have to be generated based on their raw elements (modulus n, exponent e and private exponent d) without p and q. These are random primes which are integral parts of the key but can be generated based on the former numbers, and are not always included when representing RSA keys, for example these parameters are not required in JWKs Modifications: This adds a static _createFromNumbers method which creates a new RSA key given its raw modulus, exponent and private exponent, generating the needed p and q primes without having to provide them as parameters. The algorithm to generate primes is based on a hybrid approach of the Miller Rabin primality test and the proof of Fact 1 in Dan Boneh's Twenty Years of Attacks on the RSA Cryptosystem paper. To write this algorithm, some additions had to be made to the ArbitraryPrecisionInteger Result: Private RSA keys can now be generated without providing p and q
This commit is contained in:
1 parent
55201a8f83
commit
e8f2ddd49e
6 files changed
+281
-2
No files matched your search
@@ -405,6 +405,13 @@ extension ArbitraryPrecisionInteger: SignedNumeric {
|
||||
// MARK: - Other arithmetic operations
|
||||
|
||||
extension ArbitraryPrecisionInteger {
|
||||
@usableFromInline
|
||||
var trailingZeroBitCount: Int32 {
|
||||
self.withUnsafeBignumPointer {
|
||||
CCryptoBoringSSL_BN_count_low_zero_bits($0)
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func gcd(_ a: ArbitraryPrecisionInteger, _ b: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
@@ -443,6 +450,46 @@ extension ArbitraryPrecisionInteger {
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func >> (lhs: ArbitraryPrecisionInteger, rhs: Int32) -> ArbitraryPrecisionInteger {
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
let rc = result.withUnsafeMutableBignumPointer { resultPtr in
|
||||
lhs.withUnsafeBignumPointer { lhsPtr in
|
||||
CCryptoBoringSSL_BN_rshift(resultPtr, lhsPtr, rhs)
|
||||
}
|
||||
}
|
||||
|
||||
precondition(rc == 1, "Unable to allocate memory for new ArbitraryPrecisionInteger")
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func / (lhs: ArbitraryPrecisionInteger, rhs: ArbitraryPrecisionInteger) -> ArbitraryPrecisionInteger {
|
||||
var result = ArbitraryPrecisionInteger()
|
||||
|
||||
let rc = result.withUnsafeMutableBignumPointer { resultPtr in
|
||||
lhs.withUnsafeBignumPointer { lhsPtr in
|
||||
rhs.withUnsafeBignumPointer { rhsPtr in
|
||||
ArbitraryPrecisionInteger.withUnsafeBN_CTX { bnCtx in
|
||||
CCryptoBoringSSL_BN_div(resultPtr, nil, lhsPtr, rhsPtr, bnCtx)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
precondition(rc == 1, "Unable to allocate memory for new ArbitraryPrecisionInteger")
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var isEven: Bool {
|
||||
self.withUnsafeBignumPointer {
|
||||
CCryptoBoringSSL_BN_is_odd($0) == 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Serializing
|
||||
|
||||
@@ -242,6 +242,34 @@ extension _RSA.BlindSigning {
|
||||
public var publicKey: _RSA.BlindSigning.PublicKey<H> {
|
||||
_RSA.BlindSigning.PublicKey(self.backing.publicKey, self.parameters)
|
||||
}
|
||||
|
||||
/// Construct a private key with the specified parameters.
|
||||
///
|
||||
/// The use of this API is strongly discouraged for performance reasons,
|
||||
/// as it requires the factorization of the modulus, which is resource-intensive.
|
||||
/// It is recommended to use the other initializers to construct a private key,
|
||||
/// unless you have only the modulus, public exponent, and private exponent
|
||||
/// to construct the key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - n: modulus of the key
|
||||
/// - e: public exponent of the key
|
||||
/// - d: private exponent of the key
|
||||
/// - parameters: parameters used in the blind signing protocol
|
||||
public static func _createFromNumbers(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes, parameters: Parameters) throws -> Self {
|
||||
let (p, q) = try _RSA.extractPrimeFactors(
|
||||
n: try ArbitraryPrecisionInteger(bytes: n),
|
||||
e: try ArbitraryPrecisionInteger(bytes: e),
|
||||
d: try ArbitraryPrecisionInteger(bytes: d)
|
||||
)
|
||||
|
||||
return try Self.init(
|
||||
n: n, e: e, d: d,
|
||||
p: try Data(bytesOf: p, paddedToSize: p.byteCount),
|
||||
q: try Data(bytesOf: q, paddedToSize: q.byteCount),
|
||||
parameters: parameters
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -257,6 +257,32 @@ extension _RSA.Signing {
|
||||
public var publicKey: _RSA.Signing.PublicKey {
|
||||
_RSA.Signing.PublicKey(self.backing.publicKey)
|
||||
}
|
||||
|
||||
/// Construct a private key with the specified parameters.
|
||||
///
|
||||
/// The use of this API is strongly discouraged for performance reasons,
|
||||
/// as it requires the factorization of the modulus, which is resource-intensive.
|
||||
/// It is recommended to use the other initializers to construct a private key,
|
||||
/// unless you have only the modulus, public exponent, and private exponent
|
||||
/// to construct the key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - n: modulus of the key
|
||||
/// - e: public exponent of the key
|
||||
/// - d: private exponent of the key
|
||||
public static func _createFromNumbers(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes) throws -> Self {
|
||||
let (p, q) = try _RSA.extractPrimeFactors(
|
||||
n: try ArbitraryPrecisionInteger(bytes: n),
|
||||
e: try ArbitraryPrecisionInteger(bytes: e),
|
||||
d: try ArbitraryPrecisionInteger(bytes: d)
|
||||
)
|
||||
|
||||
return try Self.init(
|
||||
n: n, e: e, d: d,
|
||||
p: try Data(bytesOf: p, paddedToSize: p.byteCount),
|
||||
q: try Data(bytesOf: q, paddedToSize: q.byteCount)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -593,6 +619,32 @@ extension _RSA.Encryption {
|
||||
public var pkcs8PEMRepresentation: String { self.backing.pkcs8PEMRepresentation }
|
||||
public var keySizeInBits: Int { self.backing.keySizeInBits }
|
||||
public var publicKey: _RSA.Encryption.PublicKey { .init(self.backing.publicKey) }
|
||||
|
||||
/// Construct a private key with the specified parameters.
|
||||
///
|
||||
/// The use of this API is strongly discouraged for performance reasons,
|
||||
/// as it requires the factorization of the modulus, which is resource-intensive.
|
||||
/// It is recommended to use the other initializers to construct a private key,
|
||||
/// unless you have only the modulus, public exponent, and private exponent
|
||||
/// to construct the key.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - n: modulus of the key
|
||||
/// - e: public exponent of the key
|
||||
/// - d: private exponent of the key
|
||||
public static func _createFromNumbers(n: some ContiguousBytes, e: some ContiguousBytes, d: some ContiguousBytes) throws -> Self {
|
||||
let (p, q) = try _RSA.extractPrimeFactors(
|
||||
n: try ArbitraryPrecisionInteger(bytes: n),
|
||||
e: try ArbitraryPrecisionInteger(bytes: e),
|
||||
d: try ArbitraryPrecisionInteger(bytes: d)
|
||||
)
|
||||
|
||||
return try Self.init(
|
||||
n: n, e: e, d: d,
|
||||
p: try Data(bytesOf: p, paddedToSize: p.byteCount),
|
||||
q: try Data(bytesOf: q, paddedToSize: q.byteCount)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -669,3 +721,60 @@ extension _RSA {
|
||||
|
||||
static let SPKIPublicKeyType = "PUBLIC KEY"
|
||||
}
|
||||
|
||||
extension _RSA {
|
||||
static func extractPrimeFactors(
|
||||
n: ArbitraryPrecisionInteger,
|
||||
e: ArbitraryPrecisionInteger,
|
||||
d: ArbitraryPrecisionInteger
|
||||
) throws -> (p: ArbitraryPrecisionInteger, q: ArbitraryPrecisionInteger) {
|
||||
// This is based on the proof of fact 1 in https://www.ams.org/notices/199902/boneh.pdf
|
||||
let k = (d * e) - 1
|
||||
let t = k.trailingZeroBitCount
|
||||
let r = k >> t
|
||||
|
||||
guard k.isEven else {
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
|
||||
var y: ArbitraryPrecisionInteger = 0
|
||||
var i = 1
|
||||
|
||||
let context = try FiniteFieldArithmeticContext(fieldSize: n)
|
||||
|
||||
while i <= 100 {
|
||||
let g = try ArbitraryPrecisionInteger.random(inclusiveMin: 2, exclusiveMax: n)
|
||||
y = try context.pow(g, r)
|
||||
|
||||
guard y != 1, y != n - 1 else {
|
||||
continue
|
||||
}
|
||||
|
||||
var j = 1
|
||||
var x: ArbitraryPrecisionInteger
|
||||
|
||||
while j <= t &- 1 {
|
||||
x = try context.pow(y, 2)
|
||||
|
||||
guard x != 1, x != n - 1 else {
|
||||
break
|
||||
}
|
||||
|
||||
y = x
|
||||
j &+= 1
|
||||
}
|
||||
|
||||
x = try context.pow(y, 2)
|
||||
if x == 1 {
|
||||
let p = try ArbitraryPrecisionInteger.gcd(y - 1, n)
|
||||
let q = n / p
|
||||
|
||||
return (p, q)
|
||||
}
|
||||
|
||||
i &+= 1
|
||||
}
|
||||
|
||||
throw CryptoKitError.incorrectParameterSize
|
||||
}
|
||||
}
|
||||
@@ -203,6 +203,25 @@ final class TestRSABlindSigning: XCTestCase {
|
||||
)
|
||||
}
|
||||
|
||||
func testConstructAndUseKeyFromRSANumbersWhileRecoveringPrimes() throws {
|
||||
let data = Array("hello, world!".utf8)
|
||||
|
||||
for testVector in RFC9474TestVector.allValues {
|
||||
let key = try _RSA.BlindSigning.PrivateKey._createFromNumbers(
|
||||
n: Data(hexString: testVector.n),
|
||||
e: Data(hexString: testVector.e),
|
||||
d: Data(hexString: testVector.d),
|
||||
parameters: testVector.parameters
|
||||
)
|
||||
|
||||
let preparedMessage = key.publicKey.prepare(data)
|
||||
let blindedMessage = try key.publicKey.blind(preparedMessage)
|
||||
let blindSignature = try key.blindSignature(for: blindedMessage.blindedMessage)
|
||||
let signature = try key.publicKey.finalize(blindSignature, for: preparedMessage, blindingInverse: blindedMessage.inverse)
|
||||
XCTAssert(key.publicKey.isValidSignature(signature, for: preparedMessage))
|
||||
}
|
||||
}
|
||||
|
||||
func testGetKeyPrimitives() throws {
|
||||
for testVector in RFC9474TestVector.allValues {
|
||||
let n = try Data(hexString: testVector.n)
|
||||
|
||||
@@ -109,6 +109,23 @@ final class TestRSAEncryption: XCTestCase {
|
||||
)
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
@@ -13,8 +13,8 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
import Foundation
|
||||
import XCTest
|
||||
@testable import Crypto
|
||||
import _CryptoExtras
|
||||
import Crypto
|
||||
@testable import _CryptoExtras
|
||||
|
||||
final class TestRSASigning: XCTestCase {
|
||||
func test_wycheproofPKCS1Vectors() throws {
|
||||
@@ -73,6 +73,15 @@ final class TestRSASigning: XCTestCase {
|
||||
testFunction: self.testPSSGroup)
|
||||
}
|
||||
|
||||
func test_wycheproofPrimitives() throws {
|
||||
try wycheproofTest(
|
||||
jsonName: "rsa_oaep_2048_sha1_mgf1sha1_test",
|
||||
testFunction: self.testPrimeFactors)
|
||||
try wycheproofTest(
|
||||
jsonName: "rsa_oaep_2048_sha256_mgf1sha256_test",
|
||||
testFunction: self.testPrimeFactors)
|
||||
}
|
||||
|
||||
func testPKCS1Signing() throws {
|
||||
try self.testPKCS1Signing(_RSA.Signing.PrivateKey(keySize: .bits2048))
|
||||
try self.testPKCS1Signing(_RSA.Signing.PrivateKey(keySize: .bits3072))
|
||||
@@ -708,6 +717,23 @@ final class TestRSASigning: XCTestCase {
|
||||
)
|
||||
}
|
||||
|
||||
func testConstructAndUseKeyFromRSANumbersWhileRecoveringPrimes() throws {
|
||||
let data = Array("hello, world!".utf8)
|
||||
|
||||
for testVector in RFC9474TestVector.allValues {
|
||||
let key = try _RSA.Signing.PrivateKey._createFromNumbers(
|
||||
n: Data(hexString: testVector.n),
|
||||
e: Data(hexString: testVector.e),
|
||||
d: Data(hexString: testVector.d)
|
||||
)
|
||||
|
||||
let signature = try key.signature(for: data)
|
||||
let roundTripped = _RSA.Signing.RSASignature(rawRepresentation: signature.rawRepresentation)
|
||||
XCTAssertEqual(signature.rawRepresentation, roundTripped.rawRepresentation)
|
||||
XCTAssertTrue(key.publicKey.isValidSignature(roundTripped, for: data))
|
||||
}
|
||||
}
|
||||
|
||||
func testGetKeyPrimitives() throws {
|
||||
for testVector in RFC9474TestVector.allValues {
|
||||
let n = try Data(hexString: testVector.n)
|
||||
@@ -801,6 +827,15 @@ final class TestRSASigning: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
private func testPrimeFactors(_ group: RSAPrimitivesTestGroup) throws {
|
||||
let n = try ArbitraryPrecisionInteger(hexString: group.n)
|
||||
let e = try ArbitraryPrecisionInteger(hexString: group.e)
|
||||
let d = try ArbitraryPrecisionInteger(hexString: group.d)
|
||||
|
||||
let (p, q) = try _RSA.extractPrimeFactors(n: n, e: e, d: d)
|
||||
XCTAssertEqual(p * q, n, "The product of p and q should equal n; got \(p) * \(q) != \(n)")
|
||||
}
|
||||
|
||||
private func pemForDERBytes(discriminator: String, derBytes: Data) -> String {
|
||||
let lineLength = 64
|
||||
var encoded = derBytes.base64EncodedString()[...]
|
||||
@@ -882,3 +917,27 @@ struct RSATest: Codable {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RSAPrimitivesTestGroup: Codable {
|
||||
let n: String
|
||||
let e: String
|
||||
let d: String
|
||||
let privateKeyJwk: PrivateKeyJWK?
|
||||
|
||||
struct PrivateKeyJWK: Codable {
|
||||
let kty: String
|
||||
let n: String
|
||||
let e: String
|
||||
let d: String
|
||||
let p: String
|
||||
let q: String
|
||||
let dp: String
|
||||
let dq: String
|
||||
let qi: String
|
||||
}
|
||||
}
|
||||
|
||||
struct RSAPrimitivesTestVectors: Codable {
|
||||
let testGroups: [RSAPrimitivesTestGroup]
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user