How to validate or verify JWT Signature in Swift

Vjardel Source

I want to validate or verify JWT signature.

I don't succeed to use SecKey, to use SecKeyVerifySignature function.

Here is my code:

let parts = session.token.components(separatedBy: ".")

let header = parts[0]
let payload = parts[1]
let signature = Data(base64Encoded: parts[2], options: .ignoreUnknownCharacters)

let pubKey = "-----BEGIN PUBLIC KEY-----xxxxxxxx/xxxxxxxx/xxxxxxxx/xxxxxxxx/xxxxxxx-----END PUBLIC KEY-----"
let encodedPubKey = Data(pubKey.utf8).base64EncodedString()
let attributes: [String:Any] = [
    kSecAttrKeyClass as String: kSecAttrKeyClassPublic,
    kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
    kSecAttrKeySizeInBits as String: 2048,
    ]
let secKey = decodeSecKeyFromBase64(encodedKey: encodedPubKey)
let signingInput = (header + "." + payload).data(using: .ascii)!
let validSignature = SecKeyVerifySignature(secKey!, .rsaSignatureMessagePKCS1v15SHA256, signingInput as CFData, signature as! CFData, nil)

and function decodeSecKeyFromBase64:

// Extract secKey from encoded string - defaults to extracting public keys
func decodeSecKeyFromBase64(encodedKey: String, isPrivate: Bool = false) -> SecKey? {
    var keyClass = kSecAttrKeyClassPublic
    if isPrivate {
        keyClass = kSecAttrKeyClassPrivate
    }
    let attributes: [String:Any] =
        [
            kSecAttrKeyClass as String: keyClass,
            kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
            kSecAttrKeySizeInBits as String: 2048,
            ]

    guard let secKeyData = Data.init(base64Encoded: encodedKey) else {
        print("Error: invalid encodedKey, cannot extract data")
        return nil
    }
    guard let secKey = SecKeyCreateWithData(secKeyData as CFData, attributes as CFDictionary, nil) else {
        print("Error: Problem in SecKeyCreateWithData()")
        return nil
    }

    return secKey
}

I don't know if I have to encode pubKey or not before to valid signature. It prints Error: Problem in SecKeyCreateWithData() from decodeSecKeyFromBase64

iosswiftsecurityjwt

Answers

comments powered by Disqus