Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add iOS RS-256 public key algorithm (#2180)

Leendert de Borsta0b7e86cfa9b
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
index 18735368f..029d1ed00 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController+Passkey.swift
@@ -186,6 +186,12 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
prfInputs = extractPrfInputs(from: extensionInput)
}
+ // Pick the credential algorithm from the RP's requested algorithms,
+ // honoring RP preference order. Falls back to ES256 if none/unsupported.
+ let requestedAlgorithms = passkeyRequest.supportedAlgorithms.map { $0.rawValue }
+ let algorithm = (try? PasskeyAuthenticator.pickSupportedAlgorithm(requestedAlgorithms))
+ ?? PasskeyAuthenticator.algES256
+
// Store parameters for use in viewWillAppear
// Vault unlock and UI display will happen in viewWillAppear
self.passkeyRegistrationParams = PasskeyRegistrationParams(
@@ -195,7 +201,8 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
userId: userId,
clientDataHash: clientDataHash,
enablePrf: prfEnabled,
- prfInputs: prfInputs
+ prfInputs: prfInputs,
+ algorithm: algorithm
)
}
@@ -210,7 +217,8 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
clientDataHash: Data,
vaultStore: VaultStore,
enablePrf: Bool = false,
- prfInputs: PrfInputs? = nil
+ prfInputs: PrfInputs? = nil,
+ algorithm: Int = PasskeyAuthenticator.algES256
) {
// Store parameters for closure capture
let capturedRpId = rpId
@@ -221,6 +229,7 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
let capturedVaultStore = vaultStore
let capturedEnablePrf = enablePrf
let capturedPrfInputs = prfInputs
+ let capturedAlgorithm = algorithm
// Query for existing passkeys with this rpId and userName
var existingPasskeys: [PasskeyWithCredentialInfo] = []
@@ -287,7 +296,8 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
vaultStore: capturedVaultStore,
viewModel: viewModel,
enablePrf: capturedEnablePrf,
- prfInputs: capturedPrfInputs
+ prfInputs: capturedPrfInputs,
+ algorithm: capturedAlgorithm
)
},
cancelHandler: { [weak self] in
@@ -338,7 +348,8 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
vaultStore: VaultStore,
viewModel: PasskeyRegistrationViewModel,
enablePrf: Bool = false,
- prfInputs: PrfInputs? = nil
+ prfInputs: PrfInputs? = nil,
+ algorithm: Int = PasskeyAuthenticator.algES256
) {
// Create a Task to handle async operations
Task {
@@ -384,7 +395,8 @@ extension CredentialProviderViewController: PasskeyProviderDelegate {
userDisplayName: userDisplayName,
uvPerformed: true,
enablePrf: enablePrf,
- prfInputs: prfInputs
+ prfInputs: prfInputs,
+ algorithm: algorithm
)
// Create a Passkey model object with correct parentItemId
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
index 8cb783011..58ec0d34b 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
@@ -398,7 +398,8 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
clientDataHash: params.clientDataHash,
vaultStore: vaultStore,
enablePrf: params.enablePrf,
- prfInputs: params.prfInputs
+ prfInputs: params.prfInputs,
+ algorithm: params.algorithm
)
return
}
diff --git a/apps/mobile-app/ios/Autofill/Structs/PasskeyRegistrationParams.swift b/apps/mobile-app/ios/Autofill/Structs/PasskeyRegistrationParams.swift
index 202165358..da33ceb4f 100644
--- a/apps/mobile-app/ios/Autofill/Structs/PasskeyRegistrationParams.swift
+++ b/apps/mobile-app/ios/Autofill/Structs/PasskeyRegistrationParams.swift
@@ -17,4 +17,6 @@ public struct PasskeyRegistrationParams {
public let enablePrf: Bool
/// The PRF inputs
public let prfInputs: PrfInputs?
+ /// The chosen COSE credential algorithm (-7 ES256, -257 RS256)
+ public let algorithm: Int
}
\ No newline at end of file
diff --git a/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyAuthenticator.swift b/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyAuthenticator.swift
index 17222ba7c..278c34af9 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyAuthenticator.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Passkeys/PasskeyAuthenticator.swift
@@ -17,7 +17,7 @@ import Security
* reflected in all ports. Method names, parameters, and behavior should remain consistent.
*
* Key features:
- * - ES256 (ECDSA P-256) key pair generation
+ * - ES256 (ECDSA P-256) and RS256 (RSASSA-PKCS1-v1.5) key pair generation
* - CBOR/COSE encoding for attestation objects
* - Proper authenticator data with WebAuthn flags
* - Self-attestation (packed format) or none attestation
@@ -33,6 +33,33 @@ public class PasskeyAuthenticator {
0x8c, 0x5d, 0x2f, 0x7d, 0x13, 0xe8, 0xc9, 0x42
]
+ /// COSE algorithm identifier for ES256 (ECDSA P-256 with SHA-256).
+ public static let algES256 = -7
+
+ /// COSE algorithm identifier for RS256 (RSASSA-PKCS1-v1.5 with SHA-256).
+ public static let algRS256 = -257
+
+ /// Algorithms supported by this authenticator, in our order of preference.
+ private static let supportedAlgorithms = [algES256, algRS256]
+
+ /**
+ * Pick a supported credential algorithm from the RP's requested algorithms.
+ * Honors the RP's preference order and returns the first algorithm we support.
+ * Defaults to ES256 when the RP provides no algorithms.
+ *
+ * - Parameter algs: COSE algorithm identifiers from the RP (e.g. ASCOSEAlgorithmIdentifier rawValues)
+ * - Returns: The chosen COSE algorithm identifier (-7 for ES256, -257 for RS256)
+ */
+ public static func pickSupportedAlgorithm(_ algs: [Int]) throws -> Int {
+ if algs.isEmpty {
+ return algES256
+ }
+ for alg in algs where supportedAlgorithms.contains(alg) {
+ return alg
+ }
+ throw PasskeyError.unsupportedAlgorithm
+ }
+
// MARK: - Public API
/**
@@ -53,12 +80,26 @@ public class PasskeyAuthenticator {
userDisplayName: String?,
uvPerformed: Bool = false,
enablePrf: Bool = false,
- prfInputs: PrfInputs? = nil
+ prfInputs: PrfInputs? = nil,
+ algorithm: Int = algES256
) throws -> PasskeyCreationResult {
- // 1. Generate ES256 key pair
- let privateKey = P256.Signing.PrivateKey()
- let publicKey = privateKey.publicKey
+ // 1. Generate key pair, build COSE key, and export JWKs for the chosen algorithm
+ let coseKey: Data
+ let publicKeyData: Data
+ let privateKeyData: Data
+ if algorithm == algRS256 {
+ let rsaKey = try generateRsaKey()
+ coseKey = try buildCoseRsaRs256(privateKey: rsaKey)
+ publicKeyData = try exportRsaPublicKeyAsJWK(privateKey: rsaKey)
+ privateKeyData = try exportRsaPrivateKeyAsJWK(privateKey: rsaKey)
+ } else {
+ let privateKey = P256.Signing.PrivateKey()
+ let publicKey = privateKey.publicKey
+ coseKey = try buildCoseEc2Es256(publicKey: publicKey)
+ publicKeyData = try exportPublicKeyAsJWK(publicKey: publicKey)
+ privateKeyData = try exportPrivateKeyAsJWK(privateKey: privateKey)
+ }
// 2. RP ID hash
let rpIdHash = Data(SHA256.hash(data: rpId.data(using: .utf8)!))
@@ -74,10 +115,7 @@ public class PasskeyAuthenticator {
// 4. Sign count (always 0 for syncable credentials)
let signCount = Data([0x00, 0x00, 0x00, 0x00])
- // 5. Build COSE public key
- let coseKey = try buildCoseEc2Es256(publicKey: publicKey)
-
- // 6. Build attested credential data
+ // 5. Build attested credential data
let credIdLength = Data([
UInt8((credentialId.count >> 8) & 0xFF),
UInt8(credentialId.count & 0xFF)
@@ -87,17 +125,17 @@ public class PasskeyAuthenticator {
attestedCredData.append(credentialId)
attestedCredData.append(coseKey)
- // 7. Build authenticator data
+ // 6. Build authenticator data
var authenticatorData = Data()
authenticatorData.append(rpIdHash)
authenticatorData.append(Data([flags]))
authenticatorData.append(signCount)
authenticatorData.append(attestedCredData)
- // 8. Build attestation object (none format)
+ // 7. Build attestation object (none format)
let attestationObject = try buildAttestationObjectNone(authenticatorData: authenticatorData)
- // 9. Generate PRF secret if requested
+ // 8. Generate PRF secret if requested
var prfSecret: Data?
if enablePrf {
var prfBytes = Data(count: 32)
@@ -109,7 +147,7 @@ public class PasskeyAuthenticator {
}
}
- // 10. Evaluate PRF values if requested during registration (some authenticators try this during registration already)
+ // 9. Evaluate PRF values if requested during registration (some authenticators try this during registration already)
var prfResults: PrfResults?
if let inputs = prfInputs, let firstSalt = inputs.first, let secret = prfSecret {
var firstResult = try evaluatePrf(secret: secret, salt: firstSalt)
@@ -120,10 +158,6 @@ public class PasskeyAuthenticator {
prfResults = PrfResults(first: firstResult, second: secondResult)
}
- // 11. Export keys for storage
- let publicKeyData = try exportPublicKeyAsJWK(publicKey: publicKey)
- let privateKeyData = try exportPrivateKeyAsJWK(privateKey: privateKey)
-
return PasskeyCreationResult(
credentialId: credentialId,
attestationObject: attestationObject,
@@ -183,12 +217,17 @@ public class PasskeyAuthenticator {
dataToSign.append(authenticatorData)
dataToSign.append(clientDataHash)
- // 6. Import private key and sign
- let privateKey = try importPrivateKeyFromJWK(jwkData: privateKeyJWK)
- let signature = try privateKey.signature(for: dataToSign)
-
- // 7. Convert raw signature to DER format
- let derSignature = try convertRawSignatureToDER(signature: signature)
+ // 6. Determine algorithm from the stored key, import it, and sign.
+ // The signature is returned in the form the RP expects:
+ // DER-encoded for ES256, raw PKCS#1 v1.5 for RS256.
+ let signatureData: Data
+ if jwkKeyType(jwkData: privateKeyJWK) == "RSA" {
+ signatureData = try signRsa(jwkData: privateKeyJWK, dataToSign: dataToSign)
+ } else {
+ let privateKey = try importPrivateKeyFromJWK(jwkData: privateKeyJWK)
+ let signature = try privateKey.signature(for: dataToSign)
+ signatureData = try convertRawSignatureToDER(signature: signature)
+ }
// 8. Evaluate PRF if requested
var prfResults: PrfResults?
@@ -205,7 +244,7 @@ public class PasskeyAuthenticator {
return PasskeyAssertionResult(
credentialId: credentialId,
authenticatorData: authenticatorData,
- signature: derSignature,
+ signature: signatureData,
userHandle: userId,
prfResults: prfResults
)
@@ -286,6 +325,161 @@ public class PasskeyAuthenticator {
return try P256.Signing.PrivateKey(rawRepresentation: dBytes)
}
+ /**
+ * Read the "kty" field of a JWK ("EC" or "RSA"). Defaults to "EC".
+ */
+ private static func jwkKeyType(jwkData: Data) -> String {
+ guard let jwk = try? JSONSerialization.jsonObject(with: jwkData) as? [String: Any],
+ let kty = jwk["kty"] as? String else {
+ return "EC"
+ }
+ return kty
+ }
+
+ // MARK: - RSA Key Management (RS256)
+
+ /**
+ * Generate an RSA-2048 key pair (returns the private SecKey).
+ */
+ private static func generateRsaKey() throws -> SecKey {
+ let attributes: [String: Any] = [
+ kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
+ kSecAttrKeySizeInBits as String: 2048
+ ]
+ var error: Unmanaged<CFError>?
+ guard let key = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
+ throw PasskeyError.keyGenerationFailed
+ }
+ return key
+ }
+
+ /**
+ * Extract (modulus, exponent) from an RSA private key's public component.
+ * SecKeyCopyExternalRepresentation of an RSA public key is PKCS#1
+ * RSAPublicKey ::= SEQUENCE { modulus INTEGER, publicExponent INTEGER }.
+ */
+ private static func rsaModulusAndExponent(privateKey: SecKey) throws -> (n: Data, e: Data) {
+ guard let publicKey = SecKeyCopyPublicKey(privateKey) else {
+ throw PasskeyError.invalidPublicKey
+ }
+ var error: Unmanaged<CFError>?
+ guard let der = SecKeyCopyExternalRepresentation(publicKey, &error) as Data? else {
+ throw PasskeyError.invalidPublicKey
+ }
+ let ints = try parseDerIntegerSequence(der)
+ guard ints.count == 2 else { throw PasskeyError.invalidPublicKey }
+ return (ints[0], ints[1])
+ }
+
+ /**
+ * Export RSA public key as JWK: {kty: "RSA", n, e}.
+ */
+ private static func exportRsaPublicKeyAsJWK(privateKey: SecKey) throws -> Data {
+ let (n, e) = try rsaModulusAndExponent(privateKey: privateKey)
+ let jwk: [String: Any] = [
+ "kty": "RSA",
+ "n": n.base64URLEncodedString(),
+ "e": e.base64URLEncodedString()
+ ]
+ return try JSONSerialization.data(withJSONObject: jwk)
+ }
+
+ /**
+ * Export RSA private key as JWK: {kty: "RSA", n, e, d, p, q, dp, dq, qi}.
+ * SecKeyCopyExternalRepresentation of an RSA private key is PKCS#1
+ * RSAPrivateKey ::= SEQUENCE { version, modulus, publicExponent, privateExponent,
+ * prime1, prime2, exponent1, exponent2, coefficient } (9 INTEGERs).
+ */
+ private static func exportRsaPrivateKeyAsJWK(privateKey: SecKey) throws -> Data {
+ var error: Unmanaged<CFError>?
+ guard let der = SecKeyCopyExternalRepresentation(privateKey, &error) as Data? else {
+ throw PasskeyError.invalidPrivateKey
+ }
+ let ints = try parseDerIntegerSequence(der)
+ guard ints.count >= 9 else { throw PasskeyError.invalidPrivateKey }
+ let jwk: [String: Any] = [
+ "kty": "RSA",
+ "n": ints[1].base64URLEncodedString(),
+ "e": ints[2].base64URLEncodedString(),
+ "d": ints[3].base64URLEncodedString(),
+ "p": ints[4].base64URLEncodedString(),
+ "q": ints[5].base64URLEncodedString(),
+ "dp": ints[6].base64URLEncodedString(),
+ "dq": ints[7].base64URLEncodedString(),
+ "qi": ints[8].base64URLEncodedString()
+ ]
+ return try JSONSerialization.data(withJSONObject: jwk)
+ }
+
+ /**
+ * Import an RSA private key from JWK and sign data with RS256
+ * (RSASSA-PKCS1-v1.5 over SHA-256). The ".message" variant hashes the
+ * input internally, matching how P256.signature(for:) hashes its input.
+ */
+ private static func signRsa(jwkData: Data, dataToSign: Data) throws -> Data {
+ let key = try importRsaPrivateKeyFromJWK(jwkData: jwkData)
+ var error: Unmanaged<CFError>?
+ guard let sig = SecKeyCreateSignature(
+ key,
+ .rsaSignatureMessagePKCS1v15SHA256,
+ dataToSign as CFData,
+ &error
+ ) as Data? else {
+ throw PasskeyError.invalidSignature
+ }
+ return sig
+ }
+
+ /**
+ * Build a PKCS#1 RSAPrivateKey from a JWK and import it as a SecKey.
+ */
+ private static func importRsaPrivateKeyFromJWK(jwkData: Data) throws -> SecKey {
+ guard let jwk = try JSONSerialization.jsonObject(with: jwkData) as? [String: Any],
+ let nB64 = jwk["n"] as? String,
+ let eB64 = jwk["e"] as? String,
+ let dB64 = jwk["d"] as? String,
+ let pB64 = jwk["p"] as? String,
+ let qB64 = jwk["q"] as? String,
+ let dpB64 = jwk["dp"] as? String,
+ let dqB64 = jwk["dq"] as? String,
+ let qiB64 = jwk["qi"] as? String else {
+ throw PasskeyError.invalidJWK
+ }
+
+ let n = try Data(base64URLEncoded: nB64)
+ let e = try Data(base64URLEncoded: eB64)
+ let d = try Data(base64URLEncoded: dB64)
+ let p = try Data(base64URLEncoded: pB64)
+ let q = try Data(base64URLEncoded: qB64)
+ let dp = try Data(base64URLEncoded: dpB64)
+ let dq = try Data(base64URLEncoded: dqB64)
+ let qi = try Data(base64URLEncoded: qiB64)
+
+ // PKCS#1 RSAPrivateKey DER (version 0, two-prime)
+ let der = derSequence([
+ derInteger(Data([0x00])), // version
+ derInteger(n),
+ derInteger(e),
+ derInteger(d),
+ derInteger(p),
+ derInteger(q),
+ derInteger(dp),
+ derInteger(dq),
+ derInteger(qi)
+ ])
+
+ let attributes: [String: Any] = [
+ kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
+ kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
+ kSecAttrKeySizeInBits as String: n.count * 8
+ ]
+ var error: Unmanaged<CFError>?
+ guard let key = SecKeyCreateWithData(der as CFData, attributes as CFDictionary, &error) else {
+ throw PasskeyError.invalidPrivateKey
+ }
+ return key
+ }
+
// MARK: - CBOR Encoding
/**
@@ -342,6 +536,35 @@ public class PasskeyAuthenticator {
return cbor
}
+ /**
+ * Build COSE RSA public key for RS256 (RFC 8230)
+ * CBOR map: {1: 3 (kty: RSA), 3: -257 (alg: RS256), -1: n (modulus), -2: e (exponent)}
+ */
+ private static func buildCoseRsaRs256(privateKey: SecKey) throws -> Data {
+ let (n, e) = try rsaModulusAndExponent(privateKey: privateKey)
+
+ var cbor = Data()
+ cbor.append(0xA4) // map(4)
+
+ // 1: 3 (kty: RSA)
+ cbor.append(0x01)
+ cbor.append(0x03)
+
+ // 3: -257 (alg: RS256), encoded as negative int with 2-byte argument
+ cbor.append(0x03)
+ cbor.append(contentsOf: [0x39, 0x01, 0x00])
+
+ // -1: n (modulus)
+ cbor.append(0x20)
+ cbor.append(cborBytes(n))
+
+ // -2: e (exponent)
+ cbor.append(0x21)
+ cbor.append(cborBytes(e))
+
+ return cbor
+ }
+
/**
* Build attestation object with "none" format
* CBOR map: {fmt: "none", attStmt: {}, authData: <bytes>}
@@ -461,12 +684,97 @@ public class PasskeyAuthenticator {
var der = Data()
der.append(0x02) // INTEGER
- der.append(UInt8(value.count))
+ der.append(derLength(value.count))
der.append(value)
return der
}
+ // MARK: - ASN.1 DER
+
+ /**
+ * Encode a DER length (definite form), supporting multi-byte lengths.
+ */
+ private static func derLength(_ length: Int) -> Data {
+ if length < 0x80 {
+ return Data([UInt8(length)])
+ }
+ var lenBytes: [UInt8] = []
+ var value = length
+ while value > 0 {
+ lenBytes.insert(UInt8(value & 0xFF), at: 0)
+ value >>= 8
+ }
+ return Data([UInt8(0x80 | lenBytes.count)] + lenBytes)
+ }
+
+ /**
+ * Wrap pre-encoded DER elements in a SEQUENCE.
+ */
+ private static func derSequence(_ elements: [Data]) -> Data {
+ var body = Data()
+ for element in elements {
+ body.append(element)
+ }
+ var result = Data()
+ result.append(0x30) // SEQUENCE
+ result.append(derLength(body.count))
+ result.append(body)
+ return result
+ }
+
+ /**
+ * Parse a DER SEQUENCE of INTEGERs, returning each integer's content as
+ * an unsigned big-endian minimal byte string (leading sign byte stripped).
+ */
+ private static func parseDerIntegerSequence(_ der: Data) throws -> [Data] {
+ var index = der.startIndex
+
+ func readByte() throws -> UInt8 {
+ guard index < der.endIndex else { throw PasskeyError.invalidJWK }
+ let byte = der[index]
+ index = der.index(after: index)
+ return byte
+ }
+
+ func readLength() throws -> Int {
+ let first = try readByte()
+ if first < 0x80 {
+ return Int(first)
+ }
+ let count = Int(first & 0x7F)
+ guard count > 0 && count <= 8 else { throw PasskeyError.invalidJWK }
+ var length = 0
+ for _ in 0..<count {
+ length = (length << 8) | Int(try readByte())
+ }
+ return length
+ }
+
+ guard try readByte() == 0x30 else { throw PasskeyError.invalidJWK } // SEQUENCE
+ let seqLength = try readLength()
+ guard let seqEnd = der.index(index, offsetBy: seqLength, limitedBy: der.endIndex) else {
+ throw PasskeyError.invalidJWK
+ }
+
+ var integers: [Data] = []
+ while index < seqEnd {
+ guard try readByte() == 0x02 else { throw PasskeyError.invalidJWK } // INTEGER
+ let length = try readLength()
+ guard let contentEnd = der.index(index, offsetBy: length, limitedBy: seqEnd) else {
+ throw PasskeyError.invalidJWK
+ }
+ var content = Data(der[index..<contentEnd])
+ index = contentEnd
+ // Strip leading zero bytes to get unsigned minimal representation
+ while content.count > 1 && content.first == 0x00 {
+ content = content.dropFirst()
+ }
+ integers.append(Data(content))
+ }
+ return integers
+ }
+
// MARK: - PRF Extension
/**
@@ -534,6 +842,8 @@ public enum PasskeyError: Error {
case invalidJWK
case invalidSignature
case cborEncodingFailed
+ case keyGenerationFailed
+ case unsupportedAlgorithm
}
// MARK: - Data Extension for Base64URL