Skip to content

Commit

Permalink
Add default value for signature algorithm (#221)
Browse files Browse the repository at this point in the history
Most of the time, the signature algorithm that should be used is
dictated by the type of the private key.

* Ed25519 keys support only one signature algorithm.
* RFC 5753 section 8 recommends that "[the P-256 curve] be used with
SHA-256; the P-384 curve be used with SHA-384; and the P-521 curve be
used with SHA-512".
* RSA keys support 4 signature algorithms. But most people use RSA with
SHA-256 and nobody should use RSA with SHA-1 anymore.

More over, Certificate.PrivateKey is opaque to the user, who may not
know what type of private key they're using and what the appropriate
signature algorithm is.

For those reasons, we add convenience wrappers around methods with a
signature algorithm to provide a reasonable default value.

---------

Co-authored-by: Cory Benfield <[email protected]>
  • Loading branch information
baarde and Lukasa authored Jan 27, 2025
1 parent 2c25efa commit eaed035
Show file tree
Hide file tree
Showing 12 changed files with 662 additions and 348 deletions.
29 changes: 29 additions & 0 deletions Sources/X509/CSR/CertificateSigningRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,35 @@ public struct CertificateSigningRequest {
self.signatureBytes = try DER.Serializer.serialized(element: ASN1BitString(self.signature))[...]
}

/// Construct a CSR for a specific private key.
///
/// This API can be used to construct a certificate signing request that can be passed to a certificate
/// authority. It will correctly generate a signature over the request.
///
/// A default signature algorithm to use for the signature of this CSR is automatically chosen based on
/// the type of the private key.
///
/// - Parameters:
/// - version: The CSR version.
/// - subject: The ``DistinguishedName`` of the subject of this CSR
/// - privateKey: The private key associated with this CSR.
/// - attributes: The attributes associated with this CSR
@inlinable
public init(
version: Version,
subject: DistinguishedName,
privateKey: Certificate.PrivateKey,
attributes: Attributes
) throws {
try self.init(
version: version,
subject: subject,
privateKey: privateKey,
attributes: attributes,
signatureAlgorithm: privateKey.defaultSignatureAlgorithm
)
}

@inlinable
internal init(
info: CertificationRequestInfo,
Expand Down
48 changes: 48 additions & 0 deletions Sources/X509/Certificate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,54 @@ public struct Certificate {
self.signatureBytes = try DER.Serializer.serialized(element: ASN1BitString(self.signature))[...]
}

/// Construct a certificate from constituent parts, signed by an issuer key.
///
/// This API can be used to construct a ``Certificate`` directly, without an intermediary
/// Certificate Signing Request. The ``signature-swift.property`` for this certificate will be produced
/// automatically, using `issuerPrivateKey`.
///
/// A default signature algorithm to use for the signature of this certificate is automatically chosen based
/// on the type of the issuer's private key.
///
/// This API can be used to construct a self-signed key by passing the private key for `publicKey` as the
/// `issuerPrivateKey` argument.
///
/// - Parameters:
/// - version: The X.509 specification version for this certificate.
/// - serialNumber: The serial number of this certificate.
/// - publicKey: The public key associated with this certificate.
/// - notValidBefore: The date before which this certificate is not valid.
/// - notValidAfter: The date after which this certificate is not valid.
/// - issuer: The ``DistinguishedName`` of the issuer of this certificate.
/// - subject: The ``DistinguishedName`` of the subject of this certificate.
/// - extensions: The extensions on this certificate.
/// - issuerPrivateKey: The private key to use to sign this certificate.
@inlinable
public init(
version: Version,
serialNumber: SerialNumber,
publicKey: PublicKey,
notValidBefore: Date,
notValidAfter: Date,
issuer: DistinguishedName,
subject: DistinguishedName,
extensions: Extensions,
issuerPrivateKey: PrivateKey
) throws {
try self.init(
version: version,
serialNumber: serialNumber,
publicKey: publicKey,
notValidBefore: notValidBefore,
notValidAfter: notValidAfter,
issuer: issuer,
subject: subject,
signatureAlgorithm: issuerPrivateKey.defaultSignatureAlgorithm,
extensions: extensions,
issuerPrivateKey: issuerPrivateKey
)
}

@inlinable
init(
tbsCertificate: TBSCertificate,
Expand Down
77 changes: 27 additions & 50 deletions Sources/X509/CertificatePrivateKey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,32 +91,23 @@ extension Certificate {
bytes: Bytes,
signatureAlgorithm: SignatureAlgorithm
) throws -> Signature {
try self.validateAlgorithmForKey(algorithm: signatureAlgorithm)

switch self.backing {
case .p256(let p256):
let digestAlgorithm = try AlgorithmIdentifier(digestAlgorithmFor: signatureAlgorithm)
return try p256.signature(for: bytes, digestAlgorithm: digestAlgorithm)
return try p256.signature(for: bytes, signatureAlgorithm: signatureAlgorithm)
case .p384(let p384):
let digestAlgorithm = try AlgorithmIdentifier(digestAlgorithmFor: signatureAlgorithm)
return try p384.signature(for: bytes, digestAlgorithm: digestAlgorithm)
return try p384.signature(for: bytes, signatureAlgorithm: signatureAlgorithm)
case .p521(let p521):
let digestAlgorithm = try AlgorithmIdentifier(digestAlgorithmFor: signatureAlgorithm)
return try p521.signature(for: bytes, digestAlgorithm: digestAlgorithm)
return try p521.signature(for: bytes, signatureAlgorithm: signatureAlgorithm)
case .rsa(let rsa):
let digestAlgorithm = try AlgorithmIdentifier(digestAlgorithmFor: signatureAlgorithm)
let padding = try _RSA.Signing.Padding(forSignatureAlgorithm: signatureAlgorithm)
return try rsa.signature(for: bytes, digestAlgorithm: digestAlgorithm, padding: padding)
return try rsa.signature(for: bytes, signatureAlgorithm: signatureAlgorithm)
#if canImport(Darwin)
case .secureEnclaveP256(let secureEnclaveP256):
let digestAlgorithm = try AlgorithmIdentifier(digestAlgorithmFor: signatureAlgorithm)
return try secureEnclaveP256.signature(for: bytes, digestAlgorithm: digestAlgorithm)
return try secureEnclaveP256.signature(for: bytes, signatureAlgorithm: signatureAlgorithm)
case .secKey(let secKeyWrapper):
let digestAlgorithm = try AlgorithmIdentifier(digestAlgorithmFor: signatureAlgorithm)
return try secKeyWrapper.signature(for: bytes, digestAlgorithm: digestAlgorithm)
return try secKeyWrapper.signature(for: bytes, signatureAlgorithm: signatureAlgorithm)
#endif
case .ed25519(let ed25519):
return try ed25519.signature(for: bytes)
return try ed25519.signature(for: bytes, signatureAlgorithm: signatureAlgorithm)
}
}

Expand Down Expand Up @@ -145,51 +136,37 @@ extension Certificate {
}

@inlinable
func validateAlgorithmForKey(algorithm: SignatureAlgorithm) throws {
switch self.backing {
case .p256, .p384, .p521:
if !algorithm.isECDSA {
throw CertificateError.unsupportedSignatureAlgorithm(
reason: "Cannot use \(algorithm) with ECDSA key \(self)"
)
}
var defaultSignatureAlgorithm: SignatureAlgorithm {
switch backing {
case .p256:
return .ecdsaWithSHA256
case .p384:
return .ecdsaWithSHA384
case .p521:
return .ecdsaWithSHA512
case .rsa:
if !algorithm.isRSA {
throw CertificateError.unsupportedSignatureAlgorithm(
reason: "Cannot use \(algorithm) with RSA key \(self)"
)
}
return .sha256WithRSAEncryption
#if canImport(Darwin)
case .secureEnclaveP256:
if !algorithm.isECDSA {
throw CertificateError.unsupportedSignatureAlgorithm(
reason: "Cannot use \(algorithm) with ECDSA key \(self)"
)
}
return .ecdsaWithSHA256
case .secKey(let key):
switch key.type {
case .ECDSA:
if !algorithm.isECDSA {
throw CertificateError.unsupportedSignatureAlgorithm(
reason: "Cannot use \(algorithm) with ECDSA key \(self)"
)
}
case .RSA:
if !algorithm.isRSA {
throw CertificateError.unsupportedSignatureAlgorithm(
reason: "Cannot use \(algorithm) with RSA key \(self)"
)
return .sha256WithRSAEncryption
case .ECDSA(let keySize):
switch keySize {
case .P256:
return .ecdsaWithSHA256
case .P384:
return .ecdsaWithSHA384
case .P521:
return .ecdsaWithSHA512
}
}
#endif
case .ed25519:
if algorithm != .ed25519 {
throw CertificateError.unsupportedSignatureAlgorithm(
reason: "Cannot use \(algorithm) with Ed25519 key \(self)"
)
}
return .ed25519
}

}
}
}
Expand Down
52 changes: 11 additions & 41 deletions Sources/X509/CertificatePublicKey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -137,32 +137,17 @@ extension Certificate.PublicKey {
for bytes: Bytes,
signatureAlgorithm: Certificate.SignatureAlgorithm
) -> Bool {
var digest: Digest?

if let digestAlgorithm = try? AlgorithmIdentifier(digestAlgorithmFor: signatureAlgorithm) {
digest = try? Digest.computeDigest(for: bytes, using: digestAlgorithm)
}

switch (self.backing, digest) {
case (.p256(let p256), .some(let digest)):
return p256.isValidSignature(signature, for: digest)
case (.p384(let p384), .some(let digest)):
return p384.isValidSignature(signature, for: digest)
case (.p521(let p521), .some(let digest)):
return p521.isValidSignature(signature, for: digest)
case (.rsa(let rsa), .some(let digest)):
// For now we don't support RSA PSS, as it's not deployed in the WebPKI.
// We could, if there are sufficient user needs.
do {
let padding = try _RSA.Signing.Padding(forSignatureAlgorithm: signatureAlgorithm)
return rsa.isValidSignature(signature, for: digest, padding: padding)
} catch {
return false
}
case (.ed25519(let ed25519), .none):
return ed25519.isValidSignature(signature, for: bytes)
default:
return false
switch self.backing {
case .p256(let p256):
return p256.isValidSignature(signature, for: bytes, signatureAlgorithm: signatureAlgorithm)
case .p384(let p384):
return p384.isValidSignature(signature, for: bytes, signatureAlgorithm: signatureAlgorithm)
case .p521(let p521):
return p521.isValidSignature(signature, for: bytes, signatureAlgorithm: signatureAlgorithm)
case .rsa(let rsa):
return rsa.isValidSignature(signature, for: bytes, signatureAlgorithm: signatureAlgorithm)
case .ed25519(let ed25519):
return ed25519.isValidSignature(signature, for: bytes, signatureAlgorithm: signatureAlgorithm)
}
}
}
Expand Down Expand Up @@ -277,21 +262,6 @@ extension Certificate.PublicKey {
}
}

extension _RSA.Signing.Padding {
@inlinable
init(forSignatureAlgorithm signatureAlgorithm: Certificate.SignatureAlgorithm) throws {
switch signatureAlgorithm {
case .sha1WithRSAEncryption, .sha256WithRSAEncryption, .sha384WithRSAEncryption, .sha512WithRSAEncryption:
self = .insecurePKCS1v1_5
default:
// Either this is RSA PSS, or we hit a bug. Either way, unsupported.
throw CertificateError.unsupportedSignatureAlgorithm(
reason: "Unable to determine RSA padding mode for \(signatureAlgorithm)"
)
}
}
}

extension P256.Signing.PublicKey {
/// Create a P256 Public Key from a given ``Certificate/PublicKey-swift.struct``.
///
Expand Down
21 changes: 21 additions & 0 deletions Sources/X509/CryptographicMessageSyntax/CMSOperations.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,27 @@ public enum CMS {
return try self.serializeSignedData(signedData)
}

@_spi(CMS)
@inlinable
public static func sign<Bytes: DataProtocol>(
_ bytes: Bytes,
additionalIntermediateCertificates: [Certificate] = [],
certificate: Certificate,
privateKey: Certificate.PrivateKey,
signingTime: Date? = nil,
detached: Bool = true
) throws -> [UInt8] {
return try self.sign(
bytes,
signatureAlgorithm: privateKey.defaultSignatureAlgorithm,
additionalIntermediateCertificates: additionalIntermediateCertificates,
certificate: certificate,
privateKey: privateKey,
signingTime: signingTime,
detached: detached
)
}

@inlinable
static func signWithSigningTime<Bytes: DataProtocol>(
_ bytes: Bytes,
Expand Down
Loading

0 comments on commit eaed035

Please sign in to comment.