Skip to content

Commit

Permalink
fix(JWT): ES256K key parameter wrong format
Browse files Browse the repository at this point in the history
  • Loading branch information
goncalo-frade-iohk committed Mar 20, 2023
1 parent adf5a6d commit 3aca97e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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: "[email protected]:GigaBitcoin/secp256k1.swift.git", from: "0.5.0")
.package(url: "[email protected]:GigaBitcoin/secp256k1.swift.git", from: "0.10.0")
],
targets: [
.target(name: "SwiftJWT", dependencies: [
Expand Down
21 changes: 11 additions & 10 deletions Sources/SwiftJWT/ES256K.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Foundation
import LoggerAPI
import secp256k1
import CryptoKit

class ES256KSigner: SignerAlgorithm {
let name: String = "ES256K"
Expand Down Expand Up @@ -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
}
}

Expand Down Expand Up @@ -63,31 +63,32 @@ 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 {
throw JWTError.invalidUTF8Data
}
let keyData = try stripKeyFromPEM(pem: keyString)
let format: secp256k1.Format
switch key[0] {
switch keyData[0] {
case 0x02, 0x03:
format = .compressed
case 0x04:
format = .uncompressed
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)")
Expand Down

0 comments on commit 3aca97e

Please sign in to comment.