1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2021 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
#if !canImport(Security)
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
internal struct BoringSSLRSAPublicKey {
private var backing: Backing
init(pemRepresentation: String) throws {
self.backing = try Backing(pemRepresentation: pemRepresentation)
}
init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
self.backing = try Backing(derRepresentation: derRepresentation)
}
var pkcs1DERRepresentation: Data {
self.backing.pkcs1DERRepresentation
}
var pkcs1PEMRepresentation: String {
self.backing.pkcs1PEMRepresentation
}
var derRepresentation: Data {
self.backing.derRepresentation
}
var pemRepresentation: String {
self.backing.pemRepresentation
}
var keySizeInBits: Int {
self.backing.keySizeInBits
}
fileprivate init(_ backing: Backing) {
self.backing = backing
}
}
internal struct BoringSSLRSAPrivateKey {
private var backing: Backing
init(pemRepresentation: String) throws {
self.backing = try Backing(pemRepresentation: pemRepresentation)
}
init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
self.backing = try Backing(derRepresentation: derRepresentation)
}
init(keySize: _RSA.Signing.KeySize) throws {
self.backing = try Backing(keySize: keySize)
}
var derRepresentation: Data {
self.backing.derRepresentation
}
var pemRepresentation: String {
self.backing.pemRepresentation
}
var keySizeInBits: Int {
self.backing.keySizeInBits
}
var publicKey: BoringSSLRSAPublicKey {
self.backing.publicKey
}
}
extension BoringSSLRSAPrivateKey {
internal func signature<D: Digest>(for digest: D, padding: _RSA.Signing.Padding) throws -> _RSA.Signing.RSASignature {
return try self.backing.signature(for: digest, padding: padding)
}
internal func decrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
return try self.backing.decrypt(data, padding: padding)
}
}
extension BoringSSLRSAPublicKey {
func isValidSignature<D: Digest>(_ signature: _RSA.Signing.RSASignature, for digest: D, padding: _RSA.Signing.Padding) -> Bool {
return self.backing.isValidSignature(signature, for: digest, padding: padding)
}
internal func encrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
return try self.backing.encrypt(data, padding: padding)
}
}
extension BoringSSLRSAPublicKey {
fileprivate final class Backing {
private let pointer: OpaquePointer
fileprivate init(takingOwnershipOf pointer: OpaquePointer) {
self.pointer = pointer
}
fileprivate init(copying other: Backing) {
self.pointer = CCryptoBoringSSL_RSAPublicKey_dup(other.pointer)
}
fileprivate init(pemRepresentation: String) throws {
var pemRepresentation = pemRepresentation
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
// The SPKI form is what we support for EC keys, so we try that first, then we
// fall back to the PKCS#1 form if that parse fails.
do {
self.pointer = try pemRepresentation.withUTF8 { utf8Ptr in
return try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
guard let key = CCryptoBoringSSL_PEM_read_bio_RSA_PUBKEY(bio, nil, nil, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
}
} catch {
self.pointer = try pemRepresentation.withUTF8 { utf8Ptr in
return try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPublicKey(bio, nil, nil, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
}
}
}
fileprivate convenience init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
if derRepresentation.regions.count == 1 {
try self.init(contiguousDerRepresentation: derRepresentation.regions.first!)
} else {
let flattened = Array(derRepresentation)
try self.init(contiguousDerRepresentation: flattened)
}
}
private init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
// There are two encodings for RSA public keys: PKCS#1 and the SPKI form.
// The SPKI form is what we support for EC keys, so we try that first, then we
// fall back to the PKCS#1 form if that parse fails.
do {
self.pointer = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
return try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
guard let key = CCryptoBoringSSL_d2i_RSA_PUBKEY_bio(bio, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
}
} catch {
self.pointer = try contiguousDerRepresentation.withUnsafeBytes { derPtr in
return try BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
guard let key = CCryptoBoringSSL_d2i_RSAPublicKey_bio(bio, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
}
}
}
fileprivate var pkcs1DERRepresentation: Data {
return BIOHelper.withWritableMemoryBIO { bio in
let rc = CCryptoBoringSSL_i2d_RSAPublicKey_bio(bio, self.pointer)
precondition(rc == 1)
return try! Data(copyingMemoryBIO: bio)
}
}
fileprivate var pkcs1PEMRepresentation: String {
return ASN1.PEMDocument(type: _RSA.PKCS1PublicKeyType, derBytes: self.pkcs1DERRepresentation).pemString
}
fileprivate var derRepresentation: Data {
return BIOHelper.withWritableMemoryBIO { bio in
let rc = CCryptoBoringSSL_i2d_RSA_PUBKEY_bio(bio, self.pointer)
precondition(rc == 1)
return try! Data(copyingMemoryBIO: bio)
}
}
fileprivate var pemRepresentation: String {
return ASN1.PEMDocument(type: _RSA.SPKIPublicKeyType, derBytes: self.derRepresentation).pemString
}
fileprivate var keySizeInBits: Int {
return Int(CCryptoBoringSSL_RSA_size(self.pointer)) * 8
}
fileprivate func isValidSignature<D: Digest>(_ signature: _RSA.Signing.RSASignature, for digest: D, padding: _RSA.Signing.Padding) -> Bool {
let hashDigestType = try! DigestType(forDigestType: D.self)
return signature.withUnsafeBytes { signaturePtr in
let rc: CInt = digest.withUnsafeBytes { digestPtr in
switch padding.backing {
case .pkcs1v1_5:
return CCryptoBoringSSLShims_RSA_verify(
hashDigestType.nid,
digestPtr.baseAddress,
digestPtr.count,
signaturePtr.baseAddress,
signaturePtr.count,
self.pointer
)
case .pss:
return CCryptoBoringSSLShims_RSA_verify_pss_mgf1(
self.pointer,
digestPtr.baseAddress,
digestPtr.count,
hashDigestType.dispatchTable,
hashDigestType.dispatchTable,
CInt(hashDigestType.digestLength),
signaturePtr.baseAddress,
signaturePtr.count
)
}
}
return rc == 1
}
}
fileprivate func encrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
let outputSize = Int(CCryptoBoringSSL_RSA_size(self.pointer))
var output = Data(count: outputSize)
let contiguousData: ContiguousBytes = data.regions.count == 1 ? data.regions.first! : Array(data)
let rc: CInt = output.withUnsafeMutableBytes { bufferPtr in
contiguousData.withUnsafeBytes { dataPtr in
let rawPadding: CInt
switch padding.backing {
case .pkcs1_oaep: rawPadding = RSA_PKCS1_OAEP_PADDING
}
let rc = CCryptoBoringSSLShims_RSA_public_encrypt(
CInt(dataPtr.count),
dataPtr.baseAddress,
bufferPtr.baseAddress,
self.pointer,
rawPadding
)
return rc
}
}
if rc == -1 {
throw CryptoKitError.internalBoringSSLError()
}
return output
}
deinit {
CCryptoBoringSSL_RSA_free(self.pointer)
}
}
}
extension BoringSSLRSAPrivateKey {
fileprivate final class Backing {
private let pointer: OpaquePointer
fileprivate init(copying other: Backing) {
self.pointer = CCryptoBoringSSL_RSAPrivateKey_dup(other.pointer)
}
fileprivate init(pemRepresentation: String) throws {
var pemRepresentation = pemRepresentation
self.pointer = try pemRepresentation.withUTF8 { utf8Ptr in
return try BIOHelper.withReadOnlyMemoryBIO(wrapping: utf8Ptr) { bio in
guard let key = CCryptoBoringSSL_PEM_read_bio_RSAPrivateKey(bio, nil, nil, nil) else {
throw CryptoKitError.internalBoringSSLError()
}
return key
}
}
}
fileprivate convenience init<Bytes: DataProtocol>(derRepresentation: Bytes) throws {
if derRepresentation.regions.count == 1 {
try self.init(contiguousDerRepresentation: derRepresentation.regions.first!)
} else {
let flattened = Array(derRepresentation)
try self.init(contiguousDerRepresentation: flattened)
}
}
private init<Bytes: ContiguousBytes>(contiguousDerRepresentation: Bytes) throws {
if let pointer = Backing.pkcs8DERPrivateKey(contiguousDerRepresentation) {
self.pointer = pointer
} else if let pointer = Backing.pkcs1DERPrivateKey(contiguousDerRepresentation) {
self.pointer = pointer
} else {
throw CryptoKitError.internalBoringSSLError()
}
}
private static func pkcs8DERPrivateKey<Bytes: ContiguousBytes>(_ derRepresentation: Bytes) -> OpaquePointer? {
return derRepresentation.withUnsafeBytes { derPtr in
return BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
guard let p8 = CCryptoBoringSSL_d2i_PKCS8_PRIV_KEY_INFO_bio(bio, nil) else {
return nil
}
defer {
CCryptoBoringSSL_PKCS8_PRIV_KEY_INFO_free(p8)
}
guard let pkey = CCryptoBoringSSL_EVP_PKCS82PKEY(p8) else {
return nil
}
defer {
CCryptoBoringSSL_EVP_PKEY_free(pkey)
}
return CCryptoBoringSSL_EVP_PKEY_get1_RSA(pkey)
}
}
}
private static func pkcs1DERPrivateKey<Bytes: ContiguousBytes>(_ derRepresentation: Bytes) -> OpaquePointer? {
return derRepresentation.withUnsafeBytes { derPtr in
return BIOHelper.withReadOnlyMemoryBIO(wrapping: derPtr) { bio in
return CCryptoBoringSSL_d2i_RSAPrivateKey_bio(bio, nil)
}
}
}
fileprivate init(keySize: _RSA.Signing.KeySize) throws {
let pointer = CCryptoBoringSSL_RSA_new()!
// This do block is used to avoid the risk of leaking the above pointer.
do {
let rc = RSA_F4.withBignumPointer { bignumPtr in
CCryptoBoringSSL_RSA_generate_key_ex(
pointer, CInt(keySize.bitCount), bignumPtr, nil
)
}
guard rc == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
self.pointer = pointer
} catch {
CCryptoBoringSSL_RSA_free(pointer)
throw error
}
}
fileprivate var derRepresentation: Data {
return BIOHelper.withWritableMemoryBIO { bio in
let rc = CCryptoBoringSSL_i2d_RSAPrivateKey_bio(bio, self.pointer)
precondition(rc == 1)
return try! Data(copyingMemoryBIO: bio)
}
}
fileprivate var pemRepresentation: String {
return BIOHelper.withWritableMemoryBIO { bio in
let rc = CCryptoBoringSSL_PEM_write_bio_RSAPrivateKey(bio, self.pointer, nil, nil, 0, nil, nil)
precondition(rc == 1)
return try! String(copyingUTF8MemoryBIO: bio)
}
}
fileprivate var keySizeInBits: Int {
return Int(CCryptoBoringSSL_RSA_size(self.pointer)) * 8
}
fileprivate var publicKey: BoringSSLRSAPublicKey {
let backing = BoringSSLRSAPublicKey.Backing(
takingOwnershipOf: CCryptoBoringSSL_RSAPublicKey_dup(self.pointer)
)
return BoringSSLRSAPublicKey(backing)
}
fileprivate func signature<D: Digest>(for digest: D, padding: _RSA.Signing.Padding) throws -> _RSA.Signing.RSASignature {
let hashDigestType = try DigestType(forDigestType: D.self)
let outputSize = Int(CCryptoBoringSSL_RSA_size(self.pointer))
let output = try Array<UInt8>(unsafeUninitializedCapacity: outputSize) { bufferPtr, length in
var outputLength = 0
let rc: CInt = digest.withUnsafeBytes { digestPtr in
switch padding.backing {
case .pkcs1v1_5:
var writtenLength = CUnsignedInt(0)
let rc = CCryptoBoringSSLShims_RSA_sign(
hashDigestType.nid,
digestPtr.baseAddress,
CUnsignedInt(digestPtr.count),
bufferPtr.baseAddress,
&writtenLength,
self.pointer
)
outputLength = Int(writtenLength)
return rc
case .pss:
return CCryptoBoringSSLShims_RSA_sign_pss_mgf1(
self.pointer,
&outputLength,
bufferPtr.baseAddress,
bufferPtr.count,
digestPtr.baseAddress,
digestPtr.count,
hashDigestType.dispatchTable,
hashDigestType.dispatchTable,
CInt(hashDigestType.digestLength)
)
}
}
if rc != 1 {
throw CryptoKitError.internalBoringSSLError()
}
length = outputLength
}
return _RSA.Signing.RSASignature(signatureBytes: output)
}
fileprivate func decrypt<D: DataProtocol>(_ data: D, padding: _RSA.Encryption.Padding) throws -> Data {
let outputSize = Int(CCryptoBoringSSL_RSA_size(self.pointer))
var output = Data(count: outputSize)
let contiguousData: ContiguousBytes = data.regions.count == 1 ? data.regions.first! : Array(data)
let rc: CInt = output.withUnsafeMutableBytes { bufferPtr in
contiguousData.withUnsafeBytes { dataPtr in
let rawPadding: CInt
switch padding.backing {
case .pkcs1_oaep: rawPadding = RSA_PKCS1_OAEP_PADDING
}
let rc = CCryptoBoringSSLShims_RSA_private_decrypt(
CInt(dataPtr.count),
dataPtr.baseAddress,
bufferPtr.baseAddress,
self.pointer,
rawPadding
)
return rc
}
}
if rc == -1 {
throw CryptoKitError.internalBoringSSLError()
}
output.removeSubrange(output.index(output.startIndex, offsetBy: Int(rc)) ..< output.endIndex)
return output
}
deinit {
CCryptoBoringSSL_RSA_free(self.pointer)
}
}
}
#endif
|