SelfSignedCertificateKeyPairs.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Crypto
  17. import Foundation
  18. import SwiftASN1
  19. import X509
  20. struct SelfSignedCertificateKeyPairs {
  21. struct CertificateKeyPair {
  22. let certificate: [UInt8]
  23. let key: [UInt8]
  24. }
  25. let server: CertificateKeyPair
  26. let client: CertificateKeyPair
  27. init() throws {
  28. let server = try Self.makeSelfSignedDERCertificateAndPrivateKey(name: "Server Certificate")
  29. let client = try Self.makeSelfSignedDERCertificateAndPrivateKey(name: "Client Certificate")
  30. self.server = CertificateKeyPair(certificate: server.cert, key: server.key)
  31. self.client = CertificateKeyPair(certificate: client.cert, key: client.key)
  32. }
  33. private static func makeSelfSignedDERCertificateAndPrivateKey(
  34. name: String
  35. ) throws -> (cert: [UInt8], key: [UInt8]) {
  36. let swiftCryptoKey = P256.Signing.PrivateKey()
  37. let key = Certificate.PrivateKey(swiftCryptoKey)
  38. let subjectName = try DistinguishedName { CommonName(name) }
  39. let issuerName = subjectName
  40. let now = Date()
  41. let extensions = try Certificate.Extensions {
  42. Critical(
  43. BasicConstraints.isCertificateAuthority(maxPathLength: nil)
  44. )
  45. Critical(
  46. KeyUsage(digitalSignature: true, keyCertSign: true)
  47. )
  48. Critical(
  49. try ExtendedKeyUsage([.serverAuth, .clientAuth])
  50. )
  51. SubjectAlternativeNames([.dnsName("localhost")])
  52. }
  53. let certificate = try Certificate(
  54. version: .v3,
  55. serialNumber: Certificate.SerialNumber(),
  56. publicKey: key.publicKey,
  57. notValidBefore: now.addingTimeInterval(-60 * 60),
  58. notValidAfter: now.addingTimeInterval(60 * 60 * 24 * 365),
  59. issuer: issuerName,
  60. subject: subjectName,
  61. signatureAlgorithm: .ecdsaWithSHA256,
  62. extensions: extensions,
  63. issuerPrivateKey: key
  64. )
  65. var serializer = DER.Serializer()
  66. try serializer.serialize(certificate)
  67. let certBytes = serializer.serializedBytes
  68. let keyBytes = try key.serializeAsPEM().derBytes
  69. return (certBytes, keyBytes)
  70. }
  71. }