Compare commits

...
3 Commits
Author SHA1 Message Date
Jake Petroules a53a7e8f85 Convert PrivacyInfo.xcprivacy symlinks to files (#251)
It is expected behavior of the swift-build build system to copy links as-is, so presenting these as symlinks results in broken symlinks being present in the produced resource bundles, which won't work properly.

On Windows, it even causes the build entirely to fail due to a related bug: https://github.com/apple/swift-foundation/issues/845

Convert these to flat files instead.
2024-08-13 07:53:29 +01:00
Si BeaumontandCory Benfield 8dafe0fdce extras: Provide initializers for RSA keys from RSA numbers as bytes (#247)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-07-22 04:01:44 -07:00
Nicolas BachschmidtandCory Benfield e2dd5a547b Reduce the number of heap allocations when computing hash digests (#238)
* Remove array allocation when computing digest

Instead of creating a temporary array, the digest bytes are stored in a temporary stack-allocated buffer.

This reduces the number of heap allocations needed to hash a message from 7 to 6.

* Store digest context inline

This reduces the number of heap allocations needed to hash a message from 6 to 2.

Before:
  1. the DigestContext object is created
  2. the EVP_MD_CTX struct is allocated by EVP_MD_CTX_new
  3. md_data is allocated when initializing the context

After:
  1. the DigestContext object is created

In both cases, the number is doubled because COW happens during finalize().

* Use temporary variable to finalize context

This reduces the number of heap allocations needed to hash a message from 2 to 1.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-07-18 08:34:52 -07:00
15 changed files with 448 additions and 192 deletions

No files matched your search

-15
View File
@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyTracking</key>
<false/>
<key>NSPrivacyAccessedAPITypes</key>
<array/>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyTrackingDomains</key>
<array/>
</dict>
</plist>
-1
View File
@@ -1 +0,0 @@
../../.PrivacyInfo.xcprivacy
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyTracking</key>
<false/>
<key>NSPrivacyAccessedAPITypes</key>
<array/>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyTrackingDomains</key>
<array/>
</dict>
</plist>
@@ -1 +0,0 @@
../../.PrivacyInfo.xcprivacy
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyTracking</key>
<false/>
<key>NSPrivacyAccessedAPITypes</key>
<array/>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyTrackingDomains</key>
<array/>
</dict>
</plist>
@@ -19,44 +19,128 @@
protocol HashFunctionImplementationDetails: HashFunction where Digest: DigestPrivate {}
protocol BoringSSLBackedHashFunction: HashFunctionImplementationDetails {
static var digestType: DigestContext.DigestType { get }
associatedtype Context
static var digestSize: Int { get }
static func initialize() -> Context?
static func update(_ context: inout Context, data: UnsafeRawBufferPointer) -> Bool
static func finalize(_ context: inout Context, digest: UnsafeMutableRawBufferPointer) -> Bool
}
extension Insecure.MD5: BoringSSLBackedHashFunction {
static var digestType: DigestContext.DigestType {
.md5
static var digestSize: Int {
Int(MD5_DIGEST_LENGTH)
}
static func initialize() -> MD5_CTX? {
var context = MD5_CTX()
guard CCryptoBoringSSL_MD5_Init(&context) == 1 else {
return nil
}
return context
}
static func update(_ context: inout MD5_CTX, data: UnsafeRawBufferPointer) -> Bool {
CCryptoBoringSSL_MD5_Update(&context, data.baseAddress, data.count) == 1
}
static func finalize(_ context: inout MD5_CTX, digest: UnsafeMutableRawBufferPointer) -> Bool {
CCryptoBoringSSL_MD5_Final(digest.baseAddress, &context) == 1
}
}
extension Insecure.SHA1: BoringSSLBackedHashFunction {
static var digestType: DigestContext.DigestType {
.sha1
static var digestSize: Int {
Int(SHA_DIGEST_LENGTH)
}
static func initialize() -> SHA_CTX? {
var context = SHA_CTX()
guard CCryptoBoringSSL_SHA1_Init(&context) == 1 else {
return nil
}
return context
}
static func update(_ context: inout SHA_CTX, data: UnsafeRawBufferPointer) -> Bool {
CCryptoBoringSSL_SHA1_Update(&context, data.baseAddress, data.count) == 1
}
static func finalize(_ context: inout SHA_CTX, digest: UnsafeMutableRawBufferPointer) -> Bool {
CCryptoBoringSSL_SHA1_Final(digest.baseAddress, &context) == 1
}
}
extension SHA256: BoringSSLBackedHashFunction {
static var digestType: DigestContext.DigestType {
.sha256
static var digestSize: Int {
Int(SHA256_DIGEST_LENGTH)
}
static func initialize() -> SHA256_CTX? {
var context = SHA256_CTX()
guard CCryptoBoringSSL_SHA256_Init(&context) == 1 else {
return nil
}
return context
}
static func update(_ context: inout SHA256_CTX, data: UnsafeRawBufferPointer) -> Bool {
CCryptoBoringSSL_SHA256_Update(&context, data.baseAddress, data.count) == 1
}
static func finalize(_ context: inout SHA256_CTX, digest: UnsafeMutableRawBufferPointer) -> Bool {
CCryptoBoringSSL_SHA256_Final(digest.baseAddress, &context) == 1
}
}
extension SHA384: BoringSSLBackedHashFunction {
static var digestType: DigestContext.DigestType {
.sha384
static var digestSize: Int {
Int(SHA384_DIGEST_LENGTH)
}
static func initialize() -> SHA512_CTX? {
var context = SHA512_CTX()
guard CCryptoBoringSSL_SHA384_Init(&context) == 1 else {
return nil
}
return context
}
static func update(_ context: inout SHA512_CTX, data: UnsafeRawBufferPointer) -> Bool {
CCryptoBoringSSL_SHA384_Update(&context, data.baseAddress, data.count) == 1
}
static func finalize(_ context: inout SHA512_CTX, digest: UnsafeMutableRawBufferPointer) -> Bool {
CCryptoBoringSSL_SHA384_Final(digest.baseAddress, &context) == 1
}
}
extension SHA512: BoringSSLBackedHashFunction {
static var digestType: DigestContext.DigestType {
.sha512
static var digestSize: Int {
Int(SHA512_DIGEST_LENGTH)
}
static func initialize() -> SHA512_CTX? {
var context = SHA512_CTX()
guard CCryptoBoringSSL_SHA512_Init(&context) == 1 else {
return nil
}
return context
}
static func update(_ context: inout SHA512_CTX, data: UnsafeRawBufferPointer) -> Bool {
CCryptoBoringSSL_SHA512_Update(&context, data.baseAddress, data.count) == 1
}
static func finalize(_ context: inout SHA512_CTX, digest: UnsafeMutableRawBufferPointer) -> Bool {
CCryptoBoringSSL_SHA512_Final(digest.baseAddress, &context) == 1
}
}
struct OpenSSLDigestImpl<H: BoringSSLBackedHashFunction> {
private var context: DigestContext
private var context: DigestContext<H>
init() {
self.context = DigestContext(digest: H.digestType)
self.context = DigestContext()
}
internal mutating func update(data: UnsafeRawBufferPointer) {
@@ -67,81 +151,49 @@ struct OpenSSLDigestImpl<H: BoringSSLBackedHashFunction> {
}
internal func finalize() -> H.Digest {
// To have a non-destructive finalize operation we must allocate.
let copyContext = DigestContext(copying: self.context)
let digestBytes = copyContext.finalize()
return digestBytes.withUnsafeBytes {
// We force unwrap here because if the digest size is wrong it's an internal error.
H.Digest(bufferPointer: $0)!
}
self.context.finalize()
}
}
class DigestContext {
private var contextPointer: UnsafeMutablePointer<EVP_MD_CTX>
fileprivate final class DigestContext<H: BoringSSLBackedHashFunction> {
private var context: H.Context
init(digest: DigestType) {
// We force unwrap because we cannot recover from allocation failure.
self.contextPointer = CCryptoBoringSSL_EVP_MD_CTX_new()!
guard CCryptoBoringSSL_EVP_DigestInit(self.contextPointer, digest.dispatchTable) != 0 else {
// We can't do much but crash here.
fatalError("Unable to initialize digest state: \(CCryptoBoringSSL_ERR_get_error())")
init() {
guard let contex = H.initialize() else {
preconditionFailure("Unable to initialize digest state")
}
self.context = contex
}
init(copying original: DigestContext) {
// We force unwrap because we cannot recover from allocation failure.
self.contextPointer = CCryptoBoringSSL_EVP_MD_CTX_new()!
guard CCryptoBoringSSL_EVP_MD_CTX_copy(self.contextPointer, original.contextPointer) != 0 else {
// We can't do much but crash here.
fatalError("Unable to copy digest state: \(CCryptoBoringSSL_ERR_get_error())")
}
self.context = original.context
}
func update(data: UnsafeRawBufferPointer) {
guard let baseAddress = data.baseAddress else {
return
guard H.update(&self.context, data: data) else {
preconditionFailure("Unable to update digest state")
}
CCryptoBoringSSL_EVP_DigestUpdate(self.contextPointer, baseAddress, data.count)
}
// This finalize function is _destructive_: do not call it if you want to reuse the object!
func finalize() -> [UInt8] {
let digestSize = CCryptoBoringSSL_EVP_MD_size(self.contextPointer.pointee.digest)
var digestBytes = Array(repeating: UInt8(0), count: digestSize)
var count = UInt32(digestSize)
digestBytes.withUnsafeMutableBufferPointer { digestPointer in
assert(digestPointer.count == count)
CCryptoBoringSSL_EVP_DigestFinal(self.contextPointer, digestPointer.baseAddress, &count)
func finalize() -> H.Digest {
var copyContext = self.context
defer {
withUnsafeMutablePointer(to: &copyContext) { $0.zeroize() }
}
return withUnsafeTemporaryAllocation(byteCount: H.digestSize, alignment: 1) { digestPointer in
defer {
digestPointer.zeroize()
}
guard H.finalize(&copyContext, digest: digestPointer) else {
preconditionFailure("Unable to finalize digest state")
}
// We force unwrap here because if the digest size is wrong it's an internal error.
return H.Digest(bufferPointer: UnsafeRawBufferPointer(digestPointer))!
}
return digestBytes
}
deinit {
CCryptoBoringSSL_EVP_MD_CTX_free(self.contextPointer)
}
}
extension DigestContext {
struct DigestType {
var dispatchTable: OpaquePointer
private init(_ dispatchTable: OpaquePointer) {
self.dispatchTable = dispatchTable
}
static let md5 = DigestType(CCryptoBoringSSL_EVP_md5())
static let sha1 = DigestType(CCryptoBoringSSL_EVP_sha1())
static let sha256 = DigestType(CCryptoBoringSSL_EVP_sha256())
static let sha384 = DigestType(CCryptoBoringSSL_EVP_sha384())
static let sha512 = DigestType(CCryptoBoringSSL_EVP_sha512())
withUnsafeMutablePointer(to: &self.context) { $0.zeroize() }
}
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
-1
View File
@@ -1 +0,0 @@
../../.PrivacyInfo.xcprivacy
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyTracking</key>
<false/>
<key>NSPrivacyAccessedAPITypes</key>
<array/>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyTrackingDomains</key>
<array/>
</dict>
</plist>
@@ -1 +0,0 @@
../../.PrivacyInfo.xcprivacy
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyTracking</key>
<false/>
<key>NSPrivacyAccessedAPITypes</key>
<array/>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyTrackingDomains</key>
<array/>
</dict>
</plist>
@@ -1 +0,0 @@
../../.PrivacyInfo.xcprivacy
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyTracking</key>
<false/>
<key>NSPrivacyAccessedAPITypes</key>
<array/>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyTrackingDomains</key>
<array/>
</dict>
</plist>
@@ -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