From 3aca97e39f9a513a1fe1aeb4474cc8a0fa1ebb38 Mon Sep 17 00:00:00 2001 From: Goncalo-FradeIOHK Date: Thu, 9 Mar 2023 18:54:57 +0000 Subject: [PATCH] fix(JWT): ES256K key parameter wrong format --- Package.swift | 2 +- Sources/SwiftJWT/ES256K.swift | 21 +++++++++++---------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/Package.swift b/Package.swift index 071d124..d6ebe7a 100644 --- a/Package.swift +++ b/Package.swift @@ -36,7 +36,7 @@ let package = Package( .package(name: "CryptorECC", url: "https://github.com/Kitura/BlueECC.git", from: "1.2.200"), .package(url: "https://github.com/Kitura/LoggerAPI.git", from: "2.0.0"), .package(url: "https://github.com/Kitura/KituraContracts.git", from: "2.0.1"), - .package(url: "git@github.com:GigaBitcoin/secp256k1.swift.git", from: "0.5.0") + .package(url: "git@github.com:GigaBitcoin/secp256k1.swift.git", from: "0.10.0") ], targets: [ .target(name: "SwiftJWT", dependencies: [ diff --git a/Sources/SwiftJWT/ES256K.swift b/Sources/SwiftJWT/ES256K.swift index 765505d..7927b16 100644 --- a/Sources/SwiftJWT/ES256K.swift +++ b/Sources/SwiftJWT/ES256K.swift @@ -1,6 +1,7 @@ import Foundation import LoggerAPI import secp256k1 +import CryptoKit class ES256KSigner: SignerAlgorithm { let name: String = "ES256K" @@ -32,8 +33,7 @@ class ES256KSigner: SignerAlgorithm { .Signing .PrivateKey(rawRepresentation: keyData) - let signedData = try privateKey.ecdsa.signature(for: data) - return signedData.rawRepresentation + return try privateKey.ecdsa.signature(for: data).rawRepresentation } } @@ -63,7 +63,7 @@ class ES256KVerifier: VerifierAlgorithm { } } - // Send the base64URLencoded signature and `header.claims` to BlueECC for verification. + // Send the base64URLencoded signature and `header.claims` to libsecp256k1 for verification. private func verify(signature: Data, for data: Data) -> Bool { do { guard let keyString = String(data: key, encoding: .utf8) else { @@ -71,7 +71,7 @@ class ES256KVerifier: VerifierAlgorithm { } let keyData = try stripKeyFromPEM(pem: keyString) let format: secp256k1.Format - switch key[0] { + switch keyData[0] { case 0x02, 0x03: format = .compressed case 0x04: @@ -79,15 +79,16 @@ class ES256KVerifier: VerifierAlgorithm { default: throw JWTError.failedVerification } + let publicKey = try secp256k1 .Signing - .PublicKey(rawRepresentation: key, format: format) - return publicKey + .PublicKey(rawRepresentation: keyData, format: format) + let signatureRaw = try secp256k1.Signing.ECDSASignature(rawRepresentation: signature) + let verification = publicKey .ecdsa - .isValidSignature( - try .init(rawRepresentation: signature), - for: data - ) + .isValidSignature(signatureRaw, for: data) + + return verification } catch { Log.error("Verification failed: \(error)")