JWT使用算法RSA 256验证始终出错

时间:2018-04-10 22:01:54

标签: swift jwt

jwt v 3.0.0-beta7

我尝试使用jwt生成令牌,编码成功 但是当验证总是失败时。如果我在网上成功测试。我正在使用RSA256算法。 错误讯息:

  

签名无效!似乎jwt不匹配的签名部分是由标题中提供的算法生成的。

我使用此代码进行解码和编码

// encode it
        let payload : [AnyHashable:Any] = ["data 1": "this is data 1","data 2": "This is data 2"]

        var resultStr : String?
        do {
            let privateKeyCrypto = try JWTCryptoKeyPrivate(pemEncoded: privateKey, parameters: nil)
            guard let holder = JWTAlgorithmRSFamilyDataHolder().signKey(privateKeyCrypto)?.secretData(privateKey.data(using: .utf8))?.algorithmName(JWTAlgorithmNameRS256) else {return}

            let headers : [AnyHashable:Any] = ["alg": "RS256","typ": "JWT"]

            guard let encoding = JWTEncodingBuilder.encodePayload(payload).headers(headers)?.addHolder(holder) else {return}

            let result = encoding.result
            resultStr = result?.successResult.encoded
            print(result?.errorResult?.error ?? "No encoding error")
            print(result?.successResult?.encoded ?? "Encoding failed")

        } catch {
            print(error)
            return
        }

        // decode it
        let yourJwt = resultStr; // from previous example
        let decodedResult = JWTBuilder.decodeMessage(yourJwt).secretData(publicKey.data(using: .utf8))?.algorithmName(JWTAlgorithmNameRS256)

        if (decodedResult?.decode != nil) {
            // handle decoded result
            print(decodedResult?.decode ?? "payload nil")
        }
        else {
            // handle error
            print(decodedResult?.jwtError.localizedDescription ?? "error was nil value")
        }

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,

class func decrypt(token: String)->[AnyHashable:Any]?
    {
        do {
            let publicKeyCrypto = try JWTCryptoKeyPublic(pemEncoded: AppConstant.Scurity.publicKey, parameters: nil)
            let verifyDataHolder = JWTAlgorithmRSFamilyDataHolder().verifyKey(publicKeyCrypto)?.algorithmName(JWTAlgorithmNameRS256)?.secretData(AppConstant.Scurity.publicKey.data(using: .utf8))
            let verifyResult = JWTDecodingBuilder.decodeMessage(token).addHolder(verifyDataHolder)?.result

            if verifyResult?.successResult != nil, let result = verifyResult?.successResult.payload {
                print("Verification successful, result: \(result)")
                return result
            } else {
                print("Verification error: \(verifyResult!.errorResult.error)")
                return nil
            }
        } catch {
            print("Verification error: \(error)")
            return nil
        }

    }