extras: Add APIs for RSA Blind Signatures (#232)

* API for RSA blind signing and verification from RFC 9474

* Add blind signing backend for Security framework

* Hide PSSZERO variants from public API for now

* Update CMakeLists.txt

* Verify signature produced within SecurityRSAPrivateKey.blindSignature(_:)

* Update API: bake params  into key, use wrappers for intermidiate values

* Throw specific error when message too large for key modulus

* Drop Security framework backend and support all variants

* Factor out withNewBignumContext helper

* Align parameter names and labels in internal functions with public API

* Fix typo in doc comments: public -> private

* Implement client operations for RSA Blind Signatures

* Remove the BlindedMessage type

* Move prepare function to public key method

* Throw (internal) errors defined in the RFC

* Fix test function names for Linux test discovery

* Factor saltLength into a computed property on Parameters

* Improve allocations for temporary bytes

* Fixup documentation typos

* Parameters are Sendable, regardless of H type parameter

* PublicKey and PrivateKey are also Sendable, regardless of H

* Wrap internal errors in most appropriate CryptoKitError

* Factor code differently

* Tweak API to return BlindingResult nominal type instead of tuple

* Prefer withUnsafeTemporaryAllocation(of:capacity:_:) to Array.init(unsafeUnitializedCapacity:_:)

* Move unsafe temporary allocations into BlindSigningHelpers methods

* Replace hand-rolled BN ops with ArbitraryPrecisionInteger and FFAC

* Fixup placement of paren in guards with closures

* Replace closure invocation let binding with looped var

* Use ERR_peek_last_error, not ERR_get_error
This commit is contained in:
Si Beaumont authored and GitHub committed 2024-06-26 13:20:43 +01:00
1 parent a3866d45d9
commit fdfdc11707
17 files changed
+1512 -42

No files matched your search

@@ -101,6 +101,8 @@ BIGNUM *CCryptoBoringSSLShims_BN_bin2bn(const void *in, size_t len, BIGNUM *ret)
size_t CCryptoBoringSSLShims_BN_bn2bin(const BIGNUM *in, void *out);
int CCryptoBoringSSLShims_BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int CCryptoBoringSSLShims_RSA_verify(int hash_nid, const void *msg, size_t msg_len,
const void *sig, size_t sig_len, RSA *rsa);
+4
View File
@@ -118,6 +118,10 @@ size_t CCryptoBoringSSLShims_BN_bn2bin(const BIGNUM *in, void *out) {
return CCryptoBoringSSL_BN_bn2bin(in, out);
}
int CCryptoBoringSSLShims_BN_mod(BIGNUM *rem, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) {
return BN_mod(rem, a, m, ctx);
}
int CCryptoBoringSSLShims_RSA_verify(int hash_nid, const void *msg, size_t msg_len,
const void *sig, size_t sig_len, RSA *rsa) {
return CCryptoBoringSSL_RSA_verify(hash_nid, msg, msg_len, sig, sig_len, rsa);
@@ -98,6 +98,14 @@ extension ArbitraryPrecisionInteger {
public init<Bytes: ContiguousBytes>(bytes: Bytes) throws {
self._backing = try BackingStorage(bytes: bytes)
}
/// Create an `ArbitraryPrecisionInteger` from a hex string.
///
/// - Parameter hexString: Hex byte string (big-endian, no `0x` prefix, may start with `-` for a negative number).
@inlinable
public init(hexString: String) throws {
self._backing = try BackingStorage(hexString: hexString)
}
}
extension ArbitraryPrecisionInteger.BackingStorage {
@@ -112,8 +120,27 @@ extension ArbitraryPrecisionInteger.BackingStorage {
throw CryptoBoringWrapperError.internalBoringSSLError()
}
}
@inlinable
convenience init(hexString: String) throws {
self.init()
try hexString.withCString { hexStringPtr in
/// `BN_hex2bin` takes a `BIGNUM **` so we need a double WUMP dance.
try withUnsafeMutablePointer(to: &self._backing) { backingPtr in
var backingPtr: UnsafeMutablePointer<BIGNUM>? = backingPtr
try withUnsafeMutablePointer(to: &backingPtr) { backingPtrPtr in
/// `BN_hex2bin` returns the number of bytes of `in` processed or zero on error.
guard CCryptoBoringSSL_BN_hex2bn(backingPtrPtr, hexStringPtr) == hexString.count else {
throw CryptoBoringWrapperError.incorrectParameterSize
}
}
}
}
}
}
// MARK: - Pointer helpers
extension ArbitraryPrecisionInteger {
@@ -381,6 +408,49 @@ extension ArbitraryPrecisionInteger: SignedNumeric {
}
}
// MARK: - Other arithmetic operations
extension ArbitraryPrecisionInteger {
@inlinable
public static func gcd(_ a: ArbitraryPrecisionInteger, _ b: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
var result = ArbitraryPrecisionInteger()
guard result.withUnsafeMutableBignumPointer({ resultPtr in
a.withUnsafeBignumPointer { aPtr in
b.withUnsafeBignumPointer { bPtr in
ArbitraryPrecisionInteger.withUnsafeBN_CTX { bnCtx in
CCryptoBoringSSL_BN_gcd(resultPtr, aPtr, bPtr, bnCtx)
}
}
}
}) == 1 else {
throw CryptoBoringWrapperError.internalBoringSSLError()
}
return result
}
@inlinable
public func isCoprime(with other: ArbitraryPrecisionInteger) throws -> Bool {
try Self.gcd(self, other) == 1
}
@inlinable
public static func random(inclusiveMin: UInt64, exclusiveMax: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
var result = ArbitraryPrecisionInteger()
guard result.withUnsafeMutableBignumPointer({ resultPtr in
exclusiveMax.withUnsafeBignumPointer { exclusiveMaxPtr in
CCryptoBoringSSL_BN_rand_range_ex(resultPtr, inclusiveMin, exclusiveMaxPtr)
}
}) == 1 else {
throw CryptoBoringWrapperError.internalBoringSSLError()
}
return result
}
}
// MARK: - Serializing
extension Data {
@@ -408,6 +478,12 @@ extension Data {
assert(written == byteCount)
}
@inlinable
public init(bytesOf integer: ArbitraryPrecisionInteger, paddedToSize paddingSize: Int) throws {
self.init(capacity: paddingSize)
try self.append(bytesOf: integer, paddedToSize: paddingSize)
}
}
// MARK: - Printing
@@ -48,6 +48,24 @@ public final class FiniteFieldArithmeticContext {
// MARK: - Arithmetic operations
extension FiniteFieldArithmeticContext {
@inlinable
public func residue(_ x: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
var result = ArbitraryPrecisionInteger()
guard x.withUnsafeBignumPointer({ xPtr in
self.fieldSize.withUnsafeBignumPointer { modPtr in
result.withUnsafeMutableBignumPointer { resultPtr in
CCryptoBoringSSL_BN_nnmod(resultPtr, xPtr, modPtr, self.bnCtx)
}
}
}) == 1 else {
throw CryptoBoringWrapperError.internalBoringSSLError()
}
return result
}
@inlinable
public func square(_ input: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
var output = ArbitraryPrecisionInteger()
@@ -151,4 +169,78 @@ extension FiniteFieldArithmeticContext {
return try ArbitraryPrecisionInteger(copying: actualOutputPointer)
}
@inlinable
public func inverse(_ x: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger? {
var result = ArbitraryPrecisionInteger()
guard result.withUnsafeMutableBignumPointer({ resultPtr in
x.withUnsafeBignumPointer { xPtr in
self.fieldSize.withUnsafeBignumPointer { modPtr in
CCryptoBoringSSL_BN_mod_inverse(resultPtr, xPtr , modPtr, self.bnCtx)
}
}
}) != nil else { return nil }
return result
}
@inlinable
public func pow(_ x: ArbitraryPrecisionInteger, _ p: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
try self.pow(x, p) { r, x, p, m, ctx, _ in CCryptoBoringSSL_BN_mod_exp(r, x, p, m, ctx) }
}
@inlinable
public func pow(secret x: ArbitraryPrecisionInteger, _ p: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
guard x < self.fieldSize else { throw CryptoBoringWrapperError.incorrectParameterSize }
return try self.pow(x, p, using: CCryptoBoringSSL_BN_mod_exp_mont)
}
@inlinable
public func pow(secret x: ArbitraryPrecisionInteger, secret p: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger {
guard x < self.fieldSize else { throw CryptoBoringWrapperError.incorrectParameterSize }
return try self.pow(x, p, using: CCryptoBoringSSL_BN_mod_exp_mont_consttime)
}
/* private but @usableFromInline */ @usableFromInline func pow(
_ a: ArbitraryPrecisionInteger,
_ b: ArbitraryPrecisionInteger,
using method: (
_ rr: UnsafeMutablePointer<BIGNUM>?,
_ a: UnsafePointer<BIGNUM>?,
_ p: UnsafePointer<BIGNUM>?,
_ m: UnsafePointer<BIGNUM>?,
_ ctx: OpaquePointer?,
_ mont: UnsafePointer<BN_MONT_CTX>?
) -> Int32
) throws -> ArbitraryPrecisionInteger {
var result = ArbitraryPrecisionInteger()
guard result.withUnsafeMutableBignumPointer({ resultPtr in
a.withUnsafeBignumPointer { aPtr in
b.withUnsafeBignumPointer { bPtr in
self.fieldSize.withUnsafeBignumPointer { modPtr in
self.withUnsafeBN_MONT_CTX { montCtxPtr in
method(resultPtr, aPtr, bPtr, modPtr, self.bnCtx, montCtxPtr)
}
}
}
}
}) == 1 else {
throw CryptoBoringWrapperError.internalBoringSSLError()
}
return result
}
/// Some functions require a `BN_MONT_CTX` parameter: this obtains one for the field modulus with a scoped lifetime.
/* private but @usableFromInline */ @usableFromInline func withUnsafeBN_MONT_CTX<T>(_ body: (UnsafePointer<BN_MONT_CTX>) throws -> T) rethrows -> T {
try self.fieldSize.withUnsafeBignumPointer { modPtr in
// We force unwrap here because this call can only fail if the allocator is broken, and if
// the allocator fails we don't have long to live anyway.
let montCtx = CCryptoBoringSSL_BN_MONT_CTX_new_for_modulus(modPtr, self.bnCtx)!
defer { CCryptoBoringSSL_BN_MONT_CTX_free(montCtx) }
return try body(montCtx)
}
}
}
+1
View File
@@ -15,6 +15,7 @@
add_library(_CryptoExtras
"ChaCha20CTR/BoringSSL/ChaCha20CTR_boring.swift"
"ChaCha20CTR/ChaCha20CTR.swift"
"RSA/RSA+BlindSigning.swift"
"RSA/RSA.swift"
"RSA/RSA_boring.swift"
"RSA/RSA_security.swift"
@@ -0,0 +1,456 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2024 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import Crypto
// NOTE: RSABSSA API is implemented using BoringSSL on all platforms.
fileprivate typealias BackingPublicKey = BoringSSLRSAPublicKey
fileprivate typealias BackingPrivateKey = BoringSSLRSAPrivateKey
extension _RSA {
public enum BlindSigning {}
}
extension _RSA.BlindSigning {
public struct PublicKey<H: HashFunction>: Sendable {
public typealias Parameters = _RSA.BlindSigning.Parameters<H>
private var backing: BackingPublicKey
private let parameters: Parameters
/// Construct an RSA public key from a PEM representation.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(pemRepresentation: String, parameters: Parameters = .RSABSSA_SHA384_PSS_Randomized) throws {
self.backing = try BackingPublicKey(pemRepresentation: pemRepresentation)
self.parameters = parameters
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Construct an RSA public key from a PEM representation.
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init(unsafePEMRepresentation pemRepresentation: String, parameters: Parameters = .RSABSSA_SHA384_PSS_Randomized) throws {
self.backing = try BackingPublicKey(pemRepresentation: pemRepresentation)
self.parameters = parameters
guard self.keySizeInBits >= 1024 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Construct an RSA public key from a DER representation.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init<Bytes: DataProtocol>(derRepresentation: Bytes, parameters: Parameters = .RSABSSA_SHA384_PSS_Randomized) throws {
self.backing = try BackingPublicKey(derRepresentation: derRepresentation)
self.parameters = parameters
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Construct an RSA public key from a DER representation.
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init<Bytes: DataProtocol>(unsafeDERRepresentation derRepresentation: Bytes, parameters: Parameters = .RSABSSA_SHA384_PSS_Randomized) throws {
self.backing = try BackingPublicKey(derRepresentation: derRepresentation)
self.parameters = parameters
guard self.keySizeInBits >= 1024 else {
throw CryptoKitError.incorrectParameterSize
}
}
public var pkcs1DERRepresentation: Data {
self.backing.pkcs1DERRepresentation
}
public var pkcs1PEMRepresentation: String {
self.backing.pkcs1PEMRepresentation
}
public var derRepresentation: Data {
self.backing.derRepresentation
}
public var pemRepresentation: String {
self.backing.pemRepresentation
}
public var keySizeInBits: Int {
self.backing.keySizeInBits
}
fileprivate init(_ backing: BackingPublicKey, _ parameters: Parameters) {
self.backing = backing
self.parameters = parameters
}
}
}
extension _RSA.BlindSigning {
public struct PrivateKey<H: HashFunction>: Sendable {
public typealias Parameters = _RSA.BlindSigning.Parameters<H>
private var backing: BackingPrivateKey
private let parameters: Parameters
/// Construct an RSA private key from a PEM representation.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init(pemRepresentation: String, parameters: Parameters = .RSABSSA_SHA384_PSS_Randomized) throws {
self.backing = try BackingPrivateKey(pemRepresentation: pemRepresentation)
self.parameters = parameters
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Construct an RSA private key from a PEM representation.
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init(unsafePEMRepresentation pemRepresentation: String, parameters: Parameters = .RSABSSA_SHA384_PSS_Randomized) throws {
self.backing = try BackingPrivateKey(pemRepresentation: pemRepresentation)
self.parameters = parameters
guard self.keySizeInBits >= 1024 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Construct an RSA private key from a DER representation.
///
/// This constructor supports key sizes of 2048 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
public init<Bytes: DataProtocol>(derRepresentation: Bytes, parameters: Parameters = .RSABSSA_SHA384_PSS_Randomized) throws {
self.backing = try BackingPrivateKey(derRepresentation: derRepresentation)
self.parameters = parameters
guard self.keySizeInBits >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// Construct an RSA private key from a DER representation.
///
/// This constructor supports key sizes of 1024 bits or more. Users should validate that key sizes are appropriate
/// for their use-case.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init<Bytes: DataProtocol>(unsafeDERRepresentation derRepresentation: Bytes, parameters: Parameters = .RSABSSA_SHA384_PSS_Randomized) throws {
self.backing = try BackingPrivateKey(derRepresentation: derRepresentation)
self.parameters = parameters
guard self.keySizeInBits >= 1024 else {
throw CryptoKitError.incorrectParameterSize
}
}
/// 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
/// key size requirements should validate `keySize` before use.
public init(keySize: _RSA.Signing.KeySize, parameters: Parameters = .RSABSSA_SHA384_PSS_Randomized) throws {
guard keySize.bitCount >= 2048 else {
throw CryptoKitError.incorrectParameterSize
}
self.backing = try BackingPrivateKey(keySize: keySize)
self.parameters = parameters
}
/// Randomly generate a new RSA private key of a given size.
///
/// This constructor will refuse to generate keys smaller than 1024 bits. Callers that want to enforce minimum
/// key size requirements should validate `unsafekeySize` before use.
/// - Warning: Key sizes less than 2048 are not recommended and should only be used for compatibility reasons.
public init(unsafeKeySize keySize: _RSA.Signing.KeySize, parameters: Parameters = .RSABSSA_SHA384_PSS_Randomized) throws {
guard keySize.bitCount >= 1024 else {
throw CryptoKitError.incorrectParameterSize
}
self.backing = try BackingPrivateKey(keySize: keySize)
self.parameters = parameters
}
public var derRepresentation: Data {
self.backing.derRepresentation
}
public var pemRepresentation: String {
self.backing.pemRepresentation
}
public var pkcs8PEMRepresentation: String {
self.backing.pkcs8PEMRepresentation
}
public var keySizeInBits: Int {
self.backing.keySizeInBits
}
public var publicKey: _RSA.BlindSigning.PublicKey<H> {
_RSA.BlindSigning.PublicKey(self.backing.publicKey, self.parameters)
}
}
}
extension _RSA.BlindSigning {
public struct BlindSignature: Sendable, ContiguousBytes {
public var rawRepresentation: Data
public init<D: DataProtocol>(rawRepresentation: D) {
self.rawRepresentation = Data(rawRepresentation)
}
internal init(signatureBytes: [UInt8]) {
self.rawRepresentation = Data(signatureBytes)
}
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
try self.rawRepresentation.withUnsafeBytes(body)
}
}
}
extension _RSA.BlindSigning {
/// Parameters used in the blind signing protocol.
///
/// Users cannot create parameters manually and should use one of the static properties for
/// a standard RSABSSA variant.
///
/// The RECOMMENDED variants are RSABSSA-SHA384-PSS-Randomized or RSABSSA-SHA384-PSSZERO-Randomized.
///
/// - Seealso: [RFC 9474: RSABSSA Variants](https://www.rfc-editor.org/rfc/rfc9474.html#name-rsabssa-variants).
public struct Parameters<H: HashFunction>: Sendable {
enum Padding { case PSS, PSSZERO }
var padding: Padding
enum Preparation { case identity, randomized }
var preparation: Preparation
var saltLength: Int32 {
switch self.padding {
case .PSS: return Int32(H.Digest.byteCount)
case .PSSZERO: return 0
}
}
}
}
extension _RSA.BlindSigning.Parameters where H == SHA384 {
/// RSABSSA-SHA384-PSS-Randomized
///
/// This named variant uses SHA-384 as the EMSA-PSS Hash option, MGF1 with SHA-384 as the EMSA-PSS MGF option,
/// and 48 as the EMSA-PSS sLen option (48-byte salt length); it also uses the randomized preparation function.
///
/// - Seealso: [RFC 9474: RSABSSA Variants](https://www.rfc-editor.org/rfc/rfc9474.html#name-rsabssa-variants).
public static let RSABSSA_SHA384_PSS_Randomized = Self<SHA384>(padding: .PSS, preparation: .randomized)
/// RSABSSA-SHA384-PSSZERO-Randomized
///
/// This named variant uses SHA-384 as the EMSA-PSS Hash option, MGF1 with SHA-384 as the EMSA-PSS MGF option,
/// and 0 as the EMSA-PSS sLen option (0-byte salt length); it also uses the randomized preparation function.
///
/// - Seealso: [RFC 9474: RSABSSA Variants](https://www.rfc-editor.org/rfc/rfc9474.html#name-rsabssa-variants).
public static let RSABSSA_SHA384_PSSZERO_Randomized = Self<SHA384>(padding: .PSSZERO, preparation: .randomized)
/// RSABSSA-SHA384-PSS-Deterministic
///
/// This named variant uses SHA-384 as the EMSA-PSS Hash option, MGF1 with SHA-384 as the EMSA-PSS MGF option,
/// and 48 as the EMSA-PSS sLen option (48-byte salt length); it also uses the identity preparation function.
///
/// - WARNING: Not all named variants can be used interchangeably. In particular, applications that provide
/// high-entropy input messages can safely use named variants without randomized message preparation, as the
/// additional message randomization does not offer security advantages.
/// For all other applications, the variants that use the randomized preparation function protect clients from
/// malicious signers.
///
/// - Seealso: [RFC 9474: RSABSSA Variants](https://www.rfc-editor.org/rfc/rfc9474.html#name-rsabssa-variants).
public static let RSABSSA_SHA384_PSS_Deterministic = Self<SHA384>(padding: .PSS, preparation: .identity)
/// RSABSSA-SHA384-PSSZERO-Deterministic
///
/// This named variant uses SHA-384 as the EMSA-PSS Hash option, MGF1 with SHA-384 as the EMSA-PSS MGF option,
/// and 0 as the EMSA-PSS sLen option (0-byte salt length); it also uses the identity preparation function
///
/// - NOTE: This is the only variant that produces deterministic signatures over the client's input message.
///
/// - WARNING: Applications that require deterministic signatures can use the RSABSSA-SHA384-PSSZERO-Deterministic
/// variant, but only if their input messages have high entropy. Applications that use
/// RSABSSA-SHA384-PSSZERO-Deterministic SHOULD carefully analyze the security implications, taking into account
/// the possibility of adversarially generated signer keys as described in Section 7.3. When it is not clear whether
/// an application requires deterministic or randomized signatures, applications SHOULD use one of the variants with
/// randomized message preparation.
///
/// - Seealso: [RFC 9474: RSABSSA Variants](https://www.rfc-editor.org/rfc/rfc9474.html#name-rsabssa-variants).
public static let RSABSSA_SHA384_PSSZERO_Deterministic = Self<SHA384>(padding: .PSSZERO, preparation: .identity)
}
extension _RSA.BlindSigning {
/// An input ready to be blinded, possibly prepended with random bytes.
///
/// Users cannot create values of this type manually; it is created and returned by the prepare operation.
public struct PreparedMessage {
var rawRepresentation: Data
}
/// The blinding inverse for a blinded message, used to unblind a blind signature.
///
/// Users cannot create values of this type manually; it is created and returned by the blind operation.
public struct BlindingInverse {
var rawRepresentation: Data
}
/// The blinded message and its blinding inverse for unblinding its blind signature.
///
/// Users cannot create values of this type manually; it is created and returned by the blind operation.
public struct BlindingResult {
/// Blinded message to be sent to the issuer.
public var blindedMessage: Data
/// Blinding inverse for producing a signature for the prepared message from the blinded signature.
public var inverse: BlindingInverse
}
}
extension _RSA.BlindSigning.PrivateKey {
/// Generate a blind signature with the given key for a blinded message.
///
/// - Parameter message: The blinded message to sign.
/// - Returns: A blind signature.
/// - Throws: If there is a failure producing the signature.
///
/// - Seealso: [RFC 9474: BlindSign](https://www.rfc-editor.org/rfc/rfc9474.html#name-blindsign).
public func blindSignature<D: DataProtocol>(for message: D) throws -> _RSA.BlindSigning.BlindSignature {
try self.backing.blindSignature(for: message)
}
}
extension _RSA.BlindSigning.PublicKey {
/// Prepare a message to be signed using the blind signing protocol.
///
/// - Parameter message: The message to be signed.
/// - Parameter parameters: Parameters used in the blind signing protocol.
/// - Returns: A prepared message, modified according to the parameters provided.
///
/// - Seealso: [RFC 9474: Prepare](https://www.rfc-editor.org/rfc/rfc9474.html#name-prepare).
public func prepare<D: DataProtocol>(_ message: D) -> _RSA.BlindSigning.PreparedMessage {
switch self.parameters.preparation {
case .identity:
return _RSA.BlindSigning.PreparedMessage(rawRepresentation: Data(message))
case .randomized:
var preparedMessageBytes = Data(capacity: 32 + message.count)
preparedMessageBytes.append(contentsOf: SystemRandomNumberGenerator.randomBytes(count: 32))
preparedMessageBytes.append(contentsOf: message)
return _RSA.BlindSigning.PreparedMessage(rawRepresentation: preparedMessageBytes)
}
}
/// Blind a message to be signed by the server using the blind signing protocol.
///
/// - Parameter message: The message to be signed.
/// - Returns: The blinded message, and its inverse for unblinding its blind signature.
///
/// - Seealso: [RFC 9474: Blind](https://www.rfc-editor.org/rfc/rfc9474.html#name-blind).
public func blind(_ message: _RSA.BlindSigning.PreparedMessage) throws -> _RSA.BlindSigning.BlindingResult {
try self.backing.blind(message, parameters: self.parameters)
}
/// Unblinds the message and produce a signature for the message.
///
/// - Parameter signature: The signature of the blinded message.
/// - Parameter message: The message to be signed.
/// - Parameter blindInverse: The inverse from the message blinding.
/// - Returns: The signature of the message.
///
/// - Seealso: [RFC 9474: Finalize](https://www.rfc-editor.org/rfc/rfc9474.html#name-finalize).
public func finalize(
_ signature: _RSA.BlindSigning.BlindSignature,
for message: _RSA.BlindSigning.PreparedMessage,
blindingInverse: _RSA.BlindSigning.BlindingInverse
) throws -> _RSA.Signing.RSASignature {
try self.backing.finalize(signature, for: message, blindingInverse: blindingInverse, parameters: self.parameters)
}
/// Validate a signature for a prepared message.
///
/// - Parameter signature: The signature to verify.
/// - Parameter message: The prepared message used in the blind signature protocol.
/// - Returns: True if the signature is valid; false otherwise.
///
/// - Seealso: [RFC 9474: Verification](https://www.rfc-editor.org/rfc/rfc9474.html#name-verification).
public func isValidSignature(
_ signature: _RSA.Signing.RSASignature,
for message: _RSA.BlindSigning.PreparedMessage
) -> Bool {
switch parameters.padding {
case .PSS:
return self.backing.isValidSignature(signature, for: H.hash(data: message.rawRepresentation), padding: .PSS)
case .PSSZERO:
return self.backing.isValidSignature(signature, for: H.hash(data: message.rawRepresentation), padding: .PSSZERO)
}
}
}
extension _RSA.BlindSigning {
/// Errors defined in the RSA Blind Signatures protocol.
///
/// - NOTE: This type does not conform to `Swift.Error`, it is used to construct a `CryptoKitError`.
///
/// - Seealso: [RFC 9474: Errors](https://www.rfc-editor.org/rfc/rfc9474.html#name-errors).
enum ProtocolError {
case messageTooLong
case encodingError
case invalidInput
case signingFailure
case messageRepresentativeOutOfRange
case invalidSignature
case unexpectedInputSize
}
}
extension CryptoKitError {
/// Map an error from the RSA Blind Signatures protocol to a CryptoKitError.
init(_ error: _RSA.BlindSigning.ProtocolError) {
switch error {
case .messageTooLong:
self = .incorrectParameterSize
case .encodingError:
self = .incorrectParameterSize
case .invalidInput:
self = .incorrectParameterSize
case .signingFailure:
self = .authenticationFailure
case .messageRepresentativeOutOfRange:
self = .incorrectParameterSize
case .invalidSignature:
self = .authenticationFailure
case .unexpectedInputSize:
self = .incorrectParameterSize
}
}
}
+8
View File
@@ -246,6 +246,7 @@ extension _RSA.Signing {
internal enum Backing {
case pkcs1v1_5
case pss
case pssZero // NOTE: this is internal-only, for RSABSSA.
}
internal var backing: Backing
@@ -266,6 +267,13 @@ extension _RSA.Signing {
///
/// MGF1 is parameterised with a hash function. The salt length will be the size of the digest from the given hash function.
public static let PSS = Self(.pss)
/// PSS padding using MGF1, with zero-length salt.
///
/// MGF1 is parameterised with a hash function. The salt length is overriden to be zero.
///
/// - NOTE: This is not API and is only accessible through the RSA Blind Signatures API.
internal static let PSSZERO = Self(.pssZero)
}
}
+274 -4
View File
@@ -14,11 +14,10 @@
import Foundation
import Crypto
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
// Nothing; this is implemented in RSA_security
#else
// NOTE: This file is unconditionally compiled because RSABSSA is implemented using BoringSSL on all platforms.
import CCryptoBoringSSL
import CCryptoBoringSSLShims
import CryptoBoringWrapper
internal struct BoringSSLRSAPublicKey: Sendable {
private var backing: Backing
@@ -101,6 +100,10 @@ extension BoringSSLRSAPrivateKey {
internal func decrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
return try self.backing.decrypt(data, padding: padding)
}
internal func blindSignature<D: DataProtocol>(for message: D) throws -> _RSA.BlindSigning.BlindSignature {
return try self.backing.blindSignature(for: message)
}
}
extension BoringSSLRSAPublicKey {
@@ -111,6 +114,22 @@ extension BoringSSLRSAPublicKey {
internal func encrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
return try self.backing.encrypt(data, padding: padding)
}
internal func blind<H: HashFunction>(
_ message: _RSA.BlindSigning.PreparedMessage,
parameters: _RSA.BlindSigning.Parameters<H>
) throws -> _RSA.BlindSigning.BlindingResult {
return try self.backing.blind(message, parameters: parameters)
}
internal func finalize<H: HashFunction>(
_ signature: _RSA.BlindSigning.BlindSignature,
for message: _RSA.BlindSigning.PreparedMessage,
blindingInverse: _RSA.BlindSigning.BlindingInverse,
parameters: _RSA.BlindSigning.Parameters<H>
) throws -> _RSA.Signing.RSASignature {
return try self.backing.finalize(signature, for: message, blindingInverse: blindingInverse, parameters: parameters)
}
}
extension BoringSSLRSAPublicKey {
@@ -264,6 +283,17 @@ extension BoringSSLRSAPublicKey {
signaturePtr.baseAddress,
signaturePtr.count
)
case .pssZero:
return CCryptoBoringSSLShims_RSA_verify_pss_mgf1(
rsaPublicKey,
digestPtr.baseAddress,
digestPtr.count,
hashDigestType.dispatchTable,
hashDigestType.dispatchTable,
CInt(0),
signaturePtr.baseAddress,
signaturePtr.count
)
}
}
return rc == 1
@@ -315,6 +345,94 @@ extension BoringSSLRSAPublicKey {
return output
}
fileprivate func blind<H: HashFunction>(
_ message: _RSA.BlindSigning.PreparedMessage,
parameters: _RSA.BlindSigning.Parameters<H>
) throws -> _RSA.BlindSigning.BlindingResult {
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
let modulusByteCount = Int(CCryptoBoringSSL_RSA_size(rsaPublicKey))
let e = try ArbitraryPrecisionInteger(copying: CCryptoBoringSSL_RSA_get0_e(rsaPublicKey))
let n = try ArbitraryPrecisionInteger(copying: CCryptoBoringSSL_RSA_get0_n(rsaPublicKey))
let finiteField = try FiniteFieldArithmeticContext(fieldSize: n)
// 1. encoded_msg = EMSA-PSS-ENCODE(msg, bit_len(n)) with Hash, MGF, and salt_len as defined in the parameters
// 2. If EMSA-PSS-ENCODE raises an error, re-raise the error and stop
// 3. m = bytes_to_int(encoded_msg)
let m = try BlindSigningHelpers.EMSAPSSEncode(
rsaPublicKey: rsaPublicKey,
modulusByteCount: modulusByteCount,
message: message,
parameters: parameters
)
// 4. c = is_coprime(m, n)
let c = try m.isCoprime(with: n)
// 5. If c is false, raise an "invalid input" error and stop
if !c { throw CryptoKitError(_RSA.BlindSigning.ProtocolError.invalidInput) }
// 6. r = random_integer_uniform(1, n)
// 7. inv = inverse_mod(r, n)
// 8. If inverse_mod fails, raise a "blinding error" error and stop
// NOTE: We retry here until we get an appropriate r, which is suggested.
var r: ArbitraryPrecisionInteger
var inv: ArbitraryPrecisionInteger!
repeat {
r = try ArbitraryPrecisionInteger.random(inclusiveMin: 1, exclusiveMax: n)
inv = try finiteField.inverse(r)
} while inv == nil
// 9. x = RSAVP1(pk, r)
let x = try finiteField.pow(secret: r, e)
// 10. z = (m * x) mod n
let z = try finiteField.multiply(m, x)
// 11. blinded_msg = int_to_bytes(z, modulus_len)
let blindedMessage = try Data(bytesOf: z, paddedToSize: modulusByteCount)
// 12. output blinded_msg, inv
let blindingInverse = _RSA.BlindSigning.BlindingInverse(rawRepresentation: try Data(bytesOf: inv, paddedToSize: modulusByteCount))
return _RSA.BlindSigning.BlindingResult(blindedMessage: blindedMessage, inverse: blindingInverse)
}
fileprivate func finalize<H: HashFunction>(
_ blindSignature: _RSA.BlindSigning.BlindSignature,
for message: _RSA.BlindSigning.PreparedMessage,
blindingInverse: _RSA.BlindSigning.BlindingInverse,
parameters: _RSA.BlindSigning.Parameters<H>
) throws -> _RSA.Signing.RSASignature {
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
let modulusByteCount = Int(CCryptoBoringSSL_RSA_size(rsaPublicKey))
let n = try ArbitraryPrecisionInteger(copying: CCryptoBoringSSL_RSA_get0_n(rsaPublicKey))
let finiteField = try FiniteFieldArithmeticContext(fieldSize: n)
// 1. If len(blind_sig) != modulus_len, raise an "unexpected input size" error and stop
guard blindSignature.rawRepresentation.count == modulusByteCount else {
throw CryptoKitError(_RSA.BlindSigning.ProtocolError.unexpectedInputSize)
}
// 2. z = bytes_to_int(blind_sig)
let z = try ArbitraryPrecisionInteger(bytes: blindSignature.rawRepresentation)
// 3. s = (z * inv) mod n
let inv = try ArbitraryPrecisionInteger(bytes: blindingInverse.rawRepresentation)
let s = try finiteField.multiply(z, inv)
// 4. sig = int_to_bytes(s, modulus_len)
let sig = _RSA.Signing.RSASignature(rawRepresentation: try Data(bytesOf: s, paddedToSize: modulusByteCount))
// 5. result = RSASSA-PSS-VERIFY(pk, msg, sig) with Hash, MGF, and salt_len as defined in the parameters
let result = try BlindSigningHelpers.RSASSAPSSVerify(rsaPublicKey: rsaPublicKey, modulusByteCount: modulusByteCount, message: message, signature: sig, parameters: parameters)
// 6. If result = "valid signature", output sig, else raise an "invalid signature" error and stop
if result {
return sig
} else {
throw CryptoKitError(_RSA.BlindSigning.ProtocolError.invalidSignature)
}
}
deinit {
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
}
@@ -505,6 +623,18 @@ extension BoringSSLRSAPrivateKey {
hashDigestType.dispatchTable,
CInt(hashDigestType.digestLength)
)
case .pssZero:
return CCryptoBoringSSLShims_RSA_sign_pss_mgf1(
rsaPrivateKey,
&outputLength,
bufferPtr.baseAddress,
bufferPtr.count,
digestPtr.baseAddress,
digestPtr.count,
hashDigestType.dispatchTable,
hashDigestType.dispatchTable,
CInt(0)
)
}
}
if rc != 1 {
@@ -564,9 +694,149 @@ extension BoringSSLRSAPrivateKey {
return output
}
fileprivate func blindSignature<D: DataProtocol>(for message: D) throws -> _RSA.BlindSigning.BlindSignature {
let rsaPrivateKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
let signatureByteCount = Int(CCryptoBoringSSL_RSA_size(rsaPrivateKey))
guard message.count == signatureByteCount else {
throw CryptoKitError.incorrectParameterSize
}
let messageBytes: ContiguousBytes = message.regions.count == 1 ? message.regions.first! : Array(message)
let signature = try withUnsafeTemporaryAllocation(of: UInt8.self, capacity: signatureByteCount) { signatureBufferPtr in
try messageBytes.withUnsafeBytes { messageBufferPtr in
/// NOTE: BoringSSL promotes the use of `RSA_sign_raw` over `RSA_private_encrypt`.
var outputCount = 0
guard CCryptoBoringSSL_RSA_sign_raw(
rsaPrivateKey,
&outputCount,
signatureBufferPtr.baseAddress,
signatureBufferPtr.count,
messageBufferPtr.baseAddress,
messageBufferPtr.count,
RSA_NO_PADDING
) == 1 else {
switch ERR_GET_REASON(CCryptoBoringSSL_ERR_peek_last_error()) {
case RSA_R_DATA_TOO_LARGE_FOR_MODULUS:
throw CryptoKitError(_RSA.BlindSigning.ProtocolError.messageRepresentativeOutOfRange)
default:
throw CryptoKitError.internalBoringSSLError()
}
}
precondition(outputCount == signatureBufferPtr.count)
}
return _RSA.BlindSigning.BlindSignature(rawRepresentation: Data(signatureBufferPtr))
}
// NOTE: Verification is part of the specification.
try self.verifyBlindSignature(signature, for: messageBytes)
return signature
}
fileprivate func verifyBlindSignature<D: ContiguousBytes>(_ signature: _RSA.BlindSigning.BlindSignature, for blindedMessage: D) throws {
try signature.withUnsafeBytes { signatureBufferPtr in
try blindedMessage.withUnsafeBytes { blindedMessageBufferPtr in
try withUnsafeTemporaryAllocation(byteCount: blindedMessageBufferPtr.count, alignment: 1) { verificationBufferPtr in
let rsaPublicKey = CCryptoBoringSSL_EVP_PKEY_get0_RSA(self.pointer)
var outputCount = 0
/// NOTE: BoringSSL promotes the use of `RSA_verify_raw` over `RSA_public_decrypt`.
guard CCryptoBoringSSL_RSA_verify_raw(
rsaPublicKey,
&outputCount,
verificationBufferPtr.baseAddress,
verificationBufferPtr.count,
signatureBufferPtr.baseAddress,
signatureBufferPtr.count,
RSA_NO_PADDING
) == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
guard
outputCount == blindedMessageBufferPtr.count,
memcmp(verificationBufferPtr.baseAddress!, blindedMessageBufferPtr.baseAddress!, blindedMessageBufferPtr.count) == 0
else {
throw CryptoKitError(_RSA.BlindSigning.ProtocolError.signingFailure)
}
}
}
}
}
deinit {
CCryptoBoringSSL_EVP_PKEY_free(self.pointer)
}
}
}
#endif
/// This namespace enum just provides helper functions for some of the steps outlined in the RFC.
enum BlindSigningHelpers {
fileprivate static func RSASSAPSSVerify<H: HashFunction>(
rsaPublicKey: OpaquePointer!,
modulusByteCount: Int,
message: _RSA.BlindSigning.PreparedMessage,
signature: _RSA.Signing.RSASignature,
parameters: _RSA.BlindSigning.Parameters<H>
) throws -> Bool {
let hashDigestType = try DigestType(forDigestType: H.Digest.self)
return H.hash(data: message.rawRepresentation).withUnsafeBytes { messageHashBufferPtr in
withUnsafeTemporaryAllocation(byteCount: modulusByteCount, alignment: 1) { encodedMessageBufferPtr in
signature.withUnsafeBytes { signatureBufferPtr in
var outputCount = 0
guard
/// NOTE: BoringSSL promotes the use of `RSA_verify_raw` over `RSA_public_decrypt`.
CCryptoBoringSSL_RSA_verify_raw(
rsaPublicKey,
&outputCount,
encodedMessageBufferPtr.baseAddress,
encodedMessageBufferPtr.count,
signatureBufferPtr.baseAddress,
signatureBufferPtr.count,
RSA_NO_PADDING
) == 1,
outputCount == modulusByteCount,
CCryptoBoringSSL_RSA_verify_PKCS1_PSS_mgf1(
rsaPublicKey,
messageHashBufferPtr.baseAddress,
hashDigestType.dispatchTable,
hashDigestType.dispatchTable,
encodedMessageBufferPtr.baseAddress,
parameters.saltLength
) == 1
else { return false }
return true
}
}
}
}
fileprivate static func EMSAPSSEncode<H: HashFunction>(
rsaPublicKey: OpaquePointer!,
modulusByteCount: Int,
message: _RSA.BlindSigning.PreparedMessage,
parameters: _RSA.BlindSigning.Parameters<H>
) throws -> ArbitraryPrecisionInteger {
try withUnsafeTemporaryAllocation(of: UInt8.self, capacity: modulusByteCount) { encodedMessageBufferPtr in
let hashDigestType = try DigestType(forDigestType: H.Digest.self)
guard H.hash(data: message.rawRepresentation).withUnsafeBytes({ hashBufferPtr in
CCryptoBoringSSL_RSA_padding_add_PKCS1_PSS_mgf1(
rsaPublicKey,
encodedMessageBufferPtr.baseAddress,
hashBufferPtr.baseAddress,
hashDigestType.dispatchTable,
hashDigestType.dispatchTable,
parameters.saltLength
)
}) == 1 else {
switch ERR_GET_REASON(CCryptoBoringSSL_ERR_peek_last_error()) {
case RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE:
throw CryptoKitError(_RSA.BlindSigning.ProtocolError.messageTooLong)
default:
throw CryptoKitError.internalBoringSSLError()
}
}
return try ArbitraryPrecisionInteger(bytes: encodedMessageBufferPtr)
}
}
}
+20 -29
View File
@@ -231,35 +231,26 @@ extension SecurityRSAPublicKey {
extension SecKeyAlgorithm {
fileprivate init<D: Digest>(digestType: D.Type = D.self, padding: _RSA.Signing.Padding) throws {
switch digestType {
case is Insecure.SHA1.Digest.Type:
switch padding.backing {
case .pss:
self = .rsaSignatureDigestPSSSHA1
case .pkcs1v1_5:
self = .rsaSignatureDigestPKCS1v15SHA1
}
case is SHA256.Digest.Type:
switch padding.backing {
case .pss:
self = .rsaSignatureDigestPSSSHA256
case .pkcs1v1_5:
self = .rsaSignatureDigestPKCS1v15SHA256
}
case is SHA384.Digest.Type:
switch padding.backing {
case .pss:
self = .rsaSignatureDigestPSSSHA384
case .pkcs1v1_5:
self = .rsaSignatureDigestPKCS1v15SHA384
}
case is SHA512.Digest.Type:
switch padding.backing {
case .pss:
self = .rsaSignatureDigestPSSSHA512
case .pkcs1v1_5:
self = .rsaSignatureDigestPKCS1v15SHA512
}
switch (digestType, padding.backing) {
case (is Insecure.SHA1.Digest.Type, .pss):
self = .rsaSignatureDigestPSSSHA1
case (is Insecure.SHA1.Digest.Type, .pkcs1v1_5):
self = .rsaSignatureDigestPKCS1v15SHA1
case (is SHA256.Digest.Type, .pss):
self = .rsaSignatureDigestPSSSHA256
case (is SHA256.Digest.Type, .pkcs1v1_5):
self = .rsaSignatureDigestPKCS1v15SHA256
case (is SHA384.Digest.Type, .pss):
self = .rsaSignatureDigestPSSSHA384
case (is SHA384.Digest.Type, .pkcs1v1_5):
self = .rsaSignatureDigestPKCS1v15SHA384
case (is SHA512.Digest.Type, .pss):
self = .rsaSignatureDigestPSSSHA512
case (is SHA512.Digest.Type, .pkcs1v1_5):
self = .rsaSignatureDigestPKCS1v15SHA512
case (_, .pssZero):
// Explicitly unsupported: only used in RSABSSA, which is implemented using BoringSSL on all platforms.
throw CryptoKitError.incorrectParameterSize
default:
throw CryptoKitError.incorrectParameterSize
}
@@ -12,10 +12,10 @@
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
// This is only used when bulding with BoringSSL.
#else
// NOTE: This file is unconditionally compiled because RSABSSA is implemented using BoringSSL on all platforms.
import CCryptoBoringSSL
import CCryptoBoringSSLShims
import CryptoBoringWrapper
import Foundation
import Crypto
@@ -93,4 +93,86 @@ extension FixedWidthInteger {
return try block(&bn)
}
}
#endif
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)
}
}
+2 -4
View File
@@ -11,9 +11,8 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
// Nothing to do in this case
#else
// NOTE: This file is unconditionally compiled because RSABSSA is implemented using BoringSSL on all platforms.
import CCryptoBoringSSL
import Crypto
@@ -55,4 +54,3 @@ struct DigestType {
}
}
}
#endif
+15 -1
View File
@@ -19,8 +19,12 @@ extension UnsafeMutableRawBufferPointer {
return
}
precondition(count <= self.count)
#if canImport(Darwin) || os(Linux) || os(Android) || os(Windows)
var rng = SystemRandomNumberGenerator()
#else
fatalError("No secure random number generator on this platform.")
#endif
precondition(count <= self.count)
// We store bytes 64-bits at a time until we can't anymore.
var targetPtr = self
@@ -39,3 +43,13 @@ extension UnsafeMutableRawBufferPointer {
}
}
}
extension SystemRandomNumberGenerator {
@inlinable
static func randomBytes(count: Int) -> [UInt8] {
Array(unsafeUninitializedCapacity: count) { buffer, initializedCount in
UnsafeMutableRawBufferPointer(start: buffer.baseAddress, count: buffer.count).initializeWithRandomBytes(count: count)
initializedCount = count
}
}
}