Skip to content

Commit

Permalink
fix(JWT): ES256K reverses the raw signature r and s bytes since libse…
Browse files Browse the repository at this point in the history
…cp does this internally for some reason
  • Loading branch information
goncalo-frade-iohk committed Mar 22, 2023
1 parent 3aca97e commit 1d36500
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion Sources/SwiftJWT/ES256K.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,19 @@ class ES256KSigner: SignerAlgorithm {
.Signing
.PrivateKey(rawRepresentation: keyData)

return try privateKey.ecdsa.signature(for: data).rawRepresentation
let (r, s) = extractRS(from: try privateKey.ecdsa.signature(for: data).rawRepresentation)

// For some reason secp256k1 reverses the bytes of R/S. This fixes that and allows this signature to be valid in bouncy castle.

return Data(r.reversed()) + Data(s.reversed())
}

private func extractRS(from signature: Data) -> (r: Data, s: Data) {
let rIndex = signature.startIndex
let sIndex = signature.index(rIndex, offsetBy: 32)
let r = signature[rIndex..<sIndex]
let s = signature[sIndex..<signature.endIndex]
return (r, s)
}
}

Expand Down

0 comments on commit 1d36500

Please sign in to comment.