公钥私钥签名/编码

时间:2017-06-25 06:18:41

标签: ios swift jwt public-key-encryption private-key

我试图使用base64编码公共私钥。看起来我可以使用SwiftyRSA library单独编码公钥和私钥。

我的问题是我不能像API JWT assertion看起来那样把它们放在一起(在RS256中)。我已经阅读了大量文档,但是我在尝试使用base64编码变量时遇到了麻烦。

我发现下面的代码很有帮助。基本上我想要做的是将公钥和私钥组合成一个令牌。这段代码适用于javascript,但我似乎无法为Swift找到类似的内容。

// First, let's try to use the top-level one-off methods.
jwt = new lib.JsonWebTokens();
 // Encode JWT token using 512-bit RSA signing algorithm.
token = jwt.encode( payload, "HS512", getPublicKey(), getPrivateKey() );

有人愿意看这个并告诉我我失踪的一两步吗?

其他细节: 这是针对Box api

提前致谢!

---------------编辑------------------------------- ----------------

我能够实现SwiftyRSA库。示例代码如下。输出给了我一个与 jwt.io网站一起使用的JWT断言。但是......(请参阅下面的代码)

        do {
        // the keys
        let publicKey = try PublicKey(pemNamed: "public_key")
        let privateKey = try PrivateKey(pemNamed: "dec_private_key")

        // signing the base64url string
        let clear = try ClearMessage(string: encodedStuff, using: .utf8)
        let signature = try clear.signed(with: privateKey, digestType: .sha256)
        print(signature.data)

        // making the signature string base64url encoded
        let finalSig = signature.base64String.replacingOccurrences(of: "/", with: "_")
        .replacingOccurrences(of: "+", with: "-")
        .replacingOccurrences(of: "=", with: "")
        print("finalSig: ", finalSig)

        // encrypt the signature and make sure it's in base64url
        let dataToEncrypt = try ClearMessage(string: finalSig, using: .utf8)
        let encryptedData = try dataToEncrypt.encrypted(with: publicKey, padding: .PKCS1)
        let finalEncryptedData = encryptedData.base64String.replacingOccurrences(of: "/", with: "_")
        .replacingOccurrences(of: "+", with: "-")
        .replacingOccurrences(of: "=", with: "")
        print(finalEncryptedData)

        // concatenate assertion
        jwtAssertion = encodedStuff + "." + finalEncryptedData
        print("JWT Assertion: \(jwtAssertion)")

        // decrypt to see if it works
        let recodedBase64 = base64urlToBase64(base64url: finalEncryptedData)
        let theEncrypted = try EncryptedMessage(base64Encoded: recodedBase64)
        let clearMessage = try theEncrypted.decrypted(with: privateKey, padding: .PKCS1)
        // decode decrypted message
        let finalDecrypted1 = clearMessage.base64String
        let finalDecrypted2 = Data(base64Encoded: finalDecrypted1)
        let finalDecrypted3 = String(data: finalDecrypted2!, encoding: .utf8)
        print("finalDecrypted3: ", finalDecrypted3 ?? "no go!") //this gives you the finalSig (which is decrypted)



    } catch let thisError {
        print("An error has occurred!",thisError)
    }

事实证明我必须为每个使用base64url,这只是用其他人替换一些字符等问题。所以,一切看起来都很好并且仍然可以在jwt网站上运行,但是当我使用下面的代码发送它时我收到此错误消息:

  

{"错误":" invalid_grant"," error_description":" OpenSSL无法验证数据:错误:0906D06C:PEM例程:PEM_read_bio:没有起跑线"}

我已经完成了有关如何为Box API执行此操作的所有步骤,但它还没有成功。我真的很想知道我在这里做错了什么。

提前致谢!

0 个答案:

没有答案